c programming language
DESCRIPTION
C Programming Language. OUTLINE Repetition and Loop Statements Arrays Multi-Dimensional Arrays. Repetition and Loop Statements. Categories of Flow Controls. Relational, Equality, Logical Operators are provided to facilitate flow controls. - PowerPoint PPT PresentationTRANSCRIPT
C Programming Language
OUTLINE
Repetition and Loop StatementsArraysMulti-Dimensional Arrays
Repetition and Loop Statements
3
Categories of Flow Controls
•Relational, Equality, Logical Operators are provided to facilitate flow controls.
•Sequential - Statements in a program are executed one after another.
•Selection - A choice of alternative actions (if, if-else, and switch).
•Repetition - Repeat certain actions (while, for, and do).
4
Loops
So far our programs are very limited - they can only run “straight through” the code.
But many situations require programs to repeat actions.
Repeating actions is called iteration
The control structures that we use to perform iteration are called loops - we speak of programs “looping”.
5
A “loop” is a repeated (“iterated”) sequence of statements.
Like conditionals, loops let us control the flow of our program in powerful ways.
Like functions, loops take code that has been generalized and execute it many times.
Block of codewithin loop isknown as the
loop body
6
We will study three types of loops:
- while loops
- for loops
- do…while loops
We will also look at nested loops - what happens when you put one loop inside another
7
• Counter-controlled repetition
– Definite repetition: know how many times loop will execute
– Control variable used to count repetitions
• Sentinel-controlled repetition
– Indefinite repetition
– Used when number of repetitions not known
– Sentinel value indicates "end of data"
8
• Counter-controlled repetition requires– The name of a control variable (or loop counter).– The initial value of the control variable.– A condition that tests for the final value of the control variable (i.e. whether looping should continue).– An increment (or decrement) by which the control variable is modified each time through the loop.
9
The while loop
The syntax is
while (condition) {
statements;
}
Its meaning is
(a) evaluate the condition(b) if its value is true (i.e., not zero) do the statements, and go
back to (a)
The while loop will repeatedly execute the statements in the loop body until the condition is false.
Something in the body of the while loop must change the condition, or the loop will never end!
loop body
Note indentation!
loop repetition condition
10
Steps in using while loop
1. Initialize loop count (loop control variable)
2. Test loop repetition condition for termination
3. Update loop count
11
Example - Add five integers:
int i = 0; // initialize i
int temp, sum = 0; // initialize sum
while (i < 5) { // test if i < 5
scanf(“%d”, &temp); // read an integer
sum = sum + temp; // add to sum
i++; // increment i
}
Important to initialize the loop count before starting the loop, and to increment the count within the loop.
12
Example - Accumulating a sum
int sum, x, count;
int number_inputs; /* Number of inputs */
sum = 0;
printf("How many numbers? ");
scanf("%d", &number_inputs);
printf("Enter %d numbers: ", number_inputs);
count = 1;
while ( count <= number_inputs ) {
scanf("%d", &x);
sum = sum + x;
count = count + 1;
}
Update
Condition
Initialization
13
Example - Calculate pay
count_emp = 0; /* no employees processed yet */
while (count_emp < num_emp) { /* test value of count_emp */
printf("Hours> ");
scanf("%d", &hours);
printf("Rate> ");
scanf("%lf", &rate);
pay = hours * rate;
printf("Pay is $%6.2f\n", pay);
count_emp = count_emp + 1; /* increment count_emp */
}
printf("\nAll employees processed\n");
14
Example - Computing a Factorial
7! = 1 * 2 * 3 * 4 * 5 * 6 * 7
We could write this without a loop (Yuck!). But easier to write it with a loop.
int i = 1;
int product = 1;
while(i <= 7){
product = product * i;
i++;
}
x = 1 * 2 * 3 * 4 * 5 * 6 * 7;printf ( "%d", x ) ;
15
Example - Factorial Function
Even better if we generalize the algorithm and make it in to a function. Can compute N!
int fact(int number){
int i = 1;
int product = 1;
while(i <= number){
product = product * i;
i++;
}
return product;
}
Local variables -re-initialized at each call
16
Infinite Loop Using while
while (1)
statement;
next statement;
•Stop the program in the operating system level, for example, Ctrl-C or Ctrl+Break in DOS. •There is a break statement for terminating the loop (discussed later).
•Use carefully!
17
The for Loop
The syntax is
for ( initialization ; condition; update ) {
statements;
}
Note that the for loop statement, as well as having a condition, has an initialization and an update part also.
Another construct for doing the same thing - iteration.
18
If the initialization, condition and/or update parts are long, place each on a separate line for clarity.
for ( initialization;
condition;
update ) {
statements;
}
next_statement;
Execution Steps:1. initialization2. condition expression is evaluated.- if true,
(a) statements are executed.(b) update expression is executed.(c) goto step (2) again.
- if false, next statement is executed.
19
for loop versus while loop
for and while loops can always be interchanged … but some cases are much better suited to for loops than while loops.
i = 0;
while (i < 10) {
printf(“%d\n”, i);
i++;
}
for(i = 0; i < 10; i++) {
printf(“%d\n”, i);
}
20
Which Loop Should You Choose?
They are interchangeable, so to some extent it is personal preference.
Use the for loop if you know how many times you are going to do something.
Think which construct will yield the simplest, clearest code.
21
Example
total_pay = 0.0;
for (count_emp = 0; /* initialization */
count_emp < number_emp; /* loop repetition condition */
count_emp += 1) { /* update */
printf("Hours> ");
scanf("%lf", &hours);
printf("Rate > $");
scanf("%lf", &rate);
pay = hours * rate;
printf("Pay is $%6.2f\n\n", pay);
total_pay = total_pay + pay;
}
printf("All employees processed\n");
printf("Total payroll is $%8.2f\n", total_pay);
22
Example - Factorial
int factorial(int n)
{
int i, /* local variables */
product; /* accumulator for product computation */
product = 1;
for (i = n; i > 1; --i) {
product = product * i;
}
return (product);
}
Note that we maydecrement or
increment the loop count- it depends on how
we write the initializationand condition parts
23
Increments and decrements other than one
Not obliged to increment / decrement the loop countby 1.
May use any value.
24
Infinite Loop Using for
for (;;) {
statements;
}
•Stop the program in the operating system level, for example, Ctrl-C or Ctrl+Break in DOS.
•There is a break statement for terminating the loop (discussed later).
•Use carefully!
25
Example - Celsius / Fahrenheit table
#define CBEGIN 10#define CLIMIT -5#define CSTEP 5
/* Variable declarations */int celsius;double fahrenheit;
/* Display the table heading */ printf(" Celsius Fahrenheit\n");
/* Display the table */ for (celsius = CBEGIN; celsius >= CLIMIT; celsius -= CSTEP) { fahrenheit = 1.8 * celsius + 32.0; printf("%6c%3d%8c%7.2f\n", ' ', celsius,
' ', fahrenheit); }Practice: C-to-F-table-part.c
26
The Comma Operator and for
expr1 , expr2
• Lowest precedence of all operators.
• Left-to-right associativity.
• Value of expr2 taken as value of the whole expression.
• Example, a = 0 , b = 1;
• Example
for (i=1, factorial=1; i<=n; i++)
factorial *= i;
27
Conditional Loops
In some situations, you may not know the exact numberof loop iterations required.
It is still possible to write a loop in such circumstances.
Steps:
1. Initialize loop control variable2. As long as exit condition has not been met
3. Continue processing
28
Loop Design
Sentinel-controlled Loops
Input a list of data values of any length, terminated bya special (sentinel) value.
double variable; /* current input */
declarations;
initial statements;
scanf("%lf", &variable);
while (variable is not equal to sentinel){
process;
scanf("%lf", &variable);
}
final statements;
29
Example - Average Inputs
printf ( "Enter values to average, end with -1.0 \n") ;
sum = 0.0 ;
count = 0 ;
scanf ( "%lf", &next ) ;
while ( next != -1.0 ) {
sum = sum + next ;
count = count + 1;
scanf ( "%lf", &next ) ;
}
if (count > 0)
printf( "The average is %f. \n", sum / (double) count );
Loop terminates when asentinel value (-1) isentered at keyboard
Comments
30
Endfile-controlled Loops
Input from a file of data and do not know how many dataitems there are.
Files have a special marker to indicate the end of data -end-of-file (eof) marker
Condition to terminate loop can be controlled by usingthe eof marker
- in C, the eof marker is denoted by the reservedword, EOF
31
Example
sum = 0;
input_status = fscanf(inp, "%d", &score);
while (input_status != EOF) {
printf("%5d\n", score);
sum += score;
input_status = fscanf(inp, "%d", &score);
}
32
Nested Loops
How would you print the following diagram?
***** ***** *****
Solution:
repeat 3 times print a row of 5 *s repeat 5 times print *
print newline
It seems as if a loop within a loop is needed!
33
When you put one loop inside another, then you have nested loops
Nested loops can be much more confusing than single loops!
34
#define ROWS 3
#define COLS 5
…
row = 1;
while ( row <= ROWS ) {
/* print a row of COLS *s */
...
row = row + 1;
}
35
#define ROWS 3
#define COLS 5
row = 1;
while ( row <= ROWS ) {
/* print a row of 5 *s */
col = 1;
while (col <= COLS) {
printf("*");
col = col + 1;
}
printf( "\n" );
row = row + 1;
}
Inner loop -print one row
Outer loop -print three rows
36
#define ROWS 3
#define COLS 5
...
for ( row = 1; row <= ROWS ; row = row + 1 ) {
for ( col = 1 ; col <= COLS ; col = col + 1 ) {
printf(“*”);
}
printf( "\n" );
}
inner loop - print one row
outer loop - print 3 rows
37
How would you print the following diagram?
Solution:
for every row ( row = 1, 2, 3, 4, 5 )
print row stars#define ROWS 5
...
int row, col ;
for ( row = 1 ; row <= ROWS ; row = row + 1 ) {
for ( col = 1 ; col <= row ; col = col + 1) {
printf( “*” ) ;
}
printf( "\n" );
}
*
**
***
****
*****
38
Remember the function to print rows of asterisks between lines of output?
Now we can write a generalized function:
void print_banner( int lines, int numchar, char ch ) {
int i, j ;
for ( i = 0 ; i < lines ; i = i + 1 ) {
for ( j = 0 ; j < numchar ; j = j + 1 ) printf ( "%c", ch); }
print (“\n”); }
}
39
#include <stdio.h>#define N 7int main(void){int cnt = 0, i, j, k;for (i = 0; i <= N; ++i)
for (j = 0; j <= N; ++j)for (k = 0; k <= N; ++k)if (i + j + k == N) {
++cnt;printf("%3d%3d%3d\n", i, j, k);
}printf("\nCount: %d\n", cnt);return (0);}
ExerciseStudy and execute the followingprogram.
40
do...while loop
The do…while loop is like a while loop, but it does the condition test at the end of the loop
all statements in loop body are executed at least once
This can be very useful for doing things like checking user input.
41
42
Example
Checking user input:
do {
printf(“Enter your age: “);
scanf(“%d”, &age);
} while (age < 0);
43
counter = 1;
do {
printf( "%d ", counter );
} while (++counter <= 10);
Example
Example - sum the digits of a positive number
sum = 0; do { sum += n % 10; n /= 10; } while(n > 0); printf("The sum of the digits is = %d\n", sum);
44
#include <stdio.h>
void main(){
int n, sum;
while ( (printf("Enter number = ") && scanf("%d",&n) && n) != 0 )
{
sum = 0;
do {
sum += n % 10;
n /= 10;
}
while(n > 0);
printf("The sum of the digits is = %d\n", sum);
}
}
Practice: sum-digit.c
while condition
true (1) true (1)
false (n==0)true (n != 0)
45
Controlling Repetition
#include <stdio.h>
#include <math.h>
int main(void)
{
int x;
while (1) {
scanf("%d", &x);
If (x < 0)
break;
printf ("square root = %.2f\n", sqrt(x));
}
printf ("Bye!\n");
return (0);
}
break and whileCauses an exit from the innermost enclosing loop.
46
Controlling Repetition …
#include <stdio.h>
int main(void)
{
int i, x;
for (i=0; i<10; i++) {
printf("i = %d\t", i);
printf("x = ? ");
scanf("%d", &x);
if (x==0)
break;
}
printf("After the loop, i = %d\n", i);
printf ("Bye!\n");
return (0);
}
break and forCauses an exit from the innermost enclosing loop.
Will update be executed before leaving the for loop?
i = 0 x = ? 10i = 1 x = ? 20i = 2 x = ? 4i = 3 x = ? 5i = 4 x = ? 0After the loop, i = 4Bye!
47
Controlling Repetition …continueCauses the current iteration of a loop to stop, and beginsthe next iteration.
#include <stdio.h>#define MAX 5int main(void){int data, sum=0, k;for (k=0; k<MAX; k++) {
scanf ("%d", &data);if (data <= 0)continue;sum += data;}
printf ("Sum of positive values is %d\n.", sum);return (0);}
1020-190-5Sum of positive values is 120.
48
How to debug and test programs
• Debugger Program– Single-step execution (F8)– Add Watch-window (Alt+W W)– Breakpoints
• Debugging without a debugger– Insert additional diagnostic calls to printf to trace the values
of critical values
#define DEBUG 0
if (DEBUG)
printf ……
49
Common Programming errors
• Off-by-One Loop errors
for (i =0; i<n; i++)
sum+= i;
for (i =0; i<=n; i++)
sum+= i;
Loop body is executed n times
Loop body is executed n+1 times
50
Syntax of the for statement
for (initialization expression;
loop repetition condition;
update expression )
Common Programming errors …
Do not put ; here
Always use braces around the loop body, whether it contains one or many statements
51
• Be careful when testing for inequality (!=) to control repetition of a loop (infinite loop may result)
• In sentinel-controlled loop:– Provide a prompt to program’s user what value to
enter as sentinel– Make sure that the sentinel value cannot be
confused with a normal data item
• Do not mistype equality test (==) and assignment operator (=)
Common Programming errors …
Arrays
53
Up to now have dealt with a small number of variablesand we have had a separate name for each one
- these are so-called scalar variables.
But what if we have
10 variables?100 variables?1000 variables?…
54
The C programming language (like many other languages)has a construct that allows us to deal with a collection of many similar variables, and identify the collection with a single name.
This construct is called an array - a structured variable- data structure
55
Data Structures
Functions give us a way to organize programs (code).
Data structures are needed to organize data, especially:
- large amounts of data
- variable amounts of data
- sets of data where the individual pieces arerelated to one another
The array is our first view of such data structures.
56
Array
– A structure of related data items
– A static entity – same size throughout program - size cannot be altered, i.e. number of elements in collection is fixed at compile time.
– But there are dynamic data structures - see later!
Definition: a named, ordered collection of variables of identical type
57
Array– Group of consecutive memory locations – Elements of array referred to by one (same) name– All elements must be of same type
To refer to an element of an array, must specify– Array name, and– Position in array - index or subscript
– either by number or arithmetic expression
Syntax:
arrayname[position number]– First element is at position 0– n element array named c
c[0], c[1] ... c[n – 1]
58
Name of array is c(Note that all elements of the array have the same name)
Position number of the element within array c - starting at 0
c[6]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
59
Array elements are like normal variables - manipulate them just like simple (scalar) variables:
E.g.
c[0] = 3;
printf( "%d", c[0] );
– Perform operations on subscript.
If x equals 3, then
c[5 - 2] == c[3] == c[x]
60
Initialization of array elements
Like simple variables, array elements may be initialized by assignment, by inputting into array element position, or at declaration time.
E.g.
int n[5] = { 1, 2, 3, 4, 5 };
If not enough initializers are specified, the rightmost elements become 0
E.g.
int n[5] = { 0 };
- All elements initialized to 0
61
If size of array is omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
– Five initializers, therefore a 5 element array
The above definition is equivalent to: int n[5] = { 1, 2, 3, 4, 5 };
62
Example
Grades of 7 students
63
How Do We Average These?
Use a loop to add them up:
sum = 0for each array index
add the indexed value to sumWhen finished, divide like usual
double grades[7] = {1.2, 4.0, 3.8, 2.5, 3.3, 0.0, 3.4} ;
int i;double sum = 0, average;...for (i=0; i<7; i++){
sum = sum + grades[i];}average = sum/7.0;
64
Declaring Arrays• When declaring arrays, must specify
– Name of array– Data type of array elements– Number of elements in array
arrayType arrayName[numberOfElements];
– Examples:
int c[10]; float myArray[999];
• Declaring multiple arrays of same type– Format similar to regular variables– Example:
int b[100], x[27];
65
Terminology
double rain[7];
rain is of type array of double with size 7.
rain[0], rain[1], ... rain[6] are the elements of the array rain. Each is a variable of type double.
0,1, ... 6 are the indices of the array. Also called subscripts.
The bounds are the lowest and highest values of the subscripts (here: 0 and 6).
66
When you declare an array, the size must be an integer constant!
Consider this set of declarations:
int size = 5;double foo[3.0];char bar[size];
Wrong!
Right!
67
Accessing Array Elements
If we have an array int foo[100], then we can access each element using its subscript:E.g.
foo[3] = 12;
printf(“theValue: %d\n”, foo[20]);
scanf(“%d”, &foo[66]);
for (i = 0; i < 100; i++)foo[i] = -10;
Arrays are ideal forusing in loops!
68
When Can You Use Array Elements?
You can use an array element wherever you could use a normal variable of the same type
- If we have an array of doubles, for example, each element is of type double
69
Array Indices (or Indexes)
Array indexes always begin at 0 in C
There is no way to change this!
What are valid indexes in this array?
char Characters[20];
Characters[0] is the name of the first element, not Characters[1]. The last element is Characters[19], not Characters[20].
70
Index Rule
Rule: An array index must evaluate to an int between 0 and n-1, where n is the number of elements in the array. No exceptions!
Example:
rain[i+3+k] /* OK as long as 0 < i+3+k < 6 */
The index may be very simple
rain[0]
or incredibly complex
rain[(int) (3.1 * fabs(sin (2.0*PI*sqrt(29.067))))]
71
Array Bounds
These array indexes are not checked!
This is called array bounds checking.
What happens if you access element 10 in this array?
double foo[10];
Trouble!
72
What You Cannot Do With Arrays
You cannot use = to assign arrays.
You cannot use == to compare two arrays.
You cannot scanf or printf an entire array.
But, you can do these things to the individual array elements.
73
More flexible way to declare arrays
#define hours_size 10
int main(){ double hours[hours_size];
Also creates an array with 10 storage locations for array elements. Can change this to 20 elements easily - just change the constant definition:
#define hours_size 20
74
We use for loops often to process arrays. Enables us to access all array elements in sequence and to process all the elements in a consistent and uniform manner.
#define hours_size 10
double hours[hours_size]; int i;
/* Set all array elements to 0 */ for (i = 0; i < hours_size; i++)
hours[i] = 0;
/* What does this one do? */ for (i = 0; i < hours_size; i++)
hours[i] = 10 * i;
/* answer - sets array elements to 0, 10, 20, ... */
75
/* What about this one? */ hours[0] = 20; for (i = 1; i < hours_size; i++) hours[i] = hours[i-1] + 5;
/* answer - sets array elements to 20, 25, 30, ... */
/* print the array subscripts and element values */ printf(“%s %s\n”, “I”, “hours[i]”); for (i = 0; i < hours_size; i++) printf("%d %f\n", i, hours[i]);
Reading data into an array: Read the values one at a time.
for (i = 0; i < hours_size; i++){ printf("Enter value for hours[%d]: ", i); scanf("%lf", &hours[i]);}
76
Write a loop that finds the sum of all values in array hours. Also write a statement to find the average of these values.
double sum, average;sum = 0;for (i = 0; i < hours_size; i++) sum += hours[i]; /* sum = sum + hours[i]; */
average = sum / hours_size;
77
E.g. Grading program
#include <stdio.h>
#define NUM_QUEST 10
#define NUM_CLASS_DAYS 5
typedef enum
{Monday, Tuesday, Wednesday, Thursday, Friday}
class_days;
void main () {
char answer[NUM_QUEST]= {'T','F','T','T','T','F','T','T'};
int score[NUM_CLASS_DAYS] = {0}, i;
for (i = 0; i < 10; i++) {
score[Monday] += answer[i] == 'T';
}
printf("\nMonday results = %d\n", score[Monday]);
}
78
E.g. Grading program ….
#include <stdio.h>
#define NUM_QUEST 10
#define NUM_CLASS_DAYS 5
typedef enum
{Monday, Tuesday, Wednesday, Thursday, Friday}
class_days;
void main () {
char answer[NUM_QUEST]= {'T','F','T','T','T','F','T','T'};
int score[NUM_CLASS_DAYS] = {0}, i;
for (i = 0; i < 10; i++) {
score[Friday + 1] += answer[i] == 'T';
}
printf("\nMonday results = %d\n", score[Friday + 1]);
}
What will happen if make this change?
79
Using array elements as function arguments
You can pass individual array elements to a function just like other variables.
Passing array elements:– Passed by call-by-value– Pass subscripted name (e.g. myArray[3]) to function.– Array element must correspond to formal parameter in type.
80
If you have declared a function with prototype
void my_fun(int, double);
and arrays
int id[10];double hours[10];
then you can write
my_fun(id[3], hours[9]);
Array element id[3] (type int variable) is the first actual argument and array element hours[9] (type double variable) is the second actual argument.
81
Individual array elements can be used as parameters, just like other simple variables.
Examples:
printf( "Last two are %f, %f", rain[5], rain[6] );
draw_house( color[i], x[i], y[i], windows[i] );
scanf( "%lf", &rain[0] );
swap( &rain[i], &rain[i+1] );
82
Array arguments
You can also pass entire arrays to functions as arguments.
Passing arrays:– To pass an array argument to a function, specify the name of the array without any brackets :
int myArray[24];
myFunction( myArray, 24 );
• Array size usually passed to function.– Arrays are passed by call-by-reference – Name of array is the address of first element. Function knows where the array is stored May modify original memory locations.
83
An array is never copied (no call by value)
The array name is always treated as a pointer parameter.
The & and * operators are not used.
Programming issue: in C, arrays do not containinformation about their size, so the size often needs to be passed as an additional parameter.
84
Example: function print_int_array displays all elements of a type int array.
void print_int_array(int list[], /* array to print */ int n) /* number of elements */{
int i; /* subscript and loop control variable */
for (i = 0; i < n; i++)printf("% %d", i, list[i]);
}
There is no actual array with the name list. The array that is processed is determined by the first actual argument in a function call.
Number of elements in array is a parametersince we do not know the size of the actual
argument array when function is called.
85
The statement
print_int_array(id, 10);
displays all values in array id (array id corresponds to the first formal parameter - int list[]). Each reference to list[i] processes the element in actual array id with subscript i.
Notice there are no brackets after the array name in the function call, but brackets are required to identify the formal parameter as an array (int list[]).
The function prototype is:
void print_int_array(int[], int);
First parameter is an int array
86
#define ARRAY_SIZE 200
double average( int a[ARRAY_SIZE] ) { int i, total = 0; for ( i = 0 ; i < ARRAY_SIZE ; i = i + 1 ) total = total + a[i]; return ((double) total / (double) ARRAY_SIZE);}
int x[ARRAY_SIZE];...x_avg = average ( x );
87
void vectorSum( int a[3], int b[3], int vsum[3] ){ int i; for ( i = 0 ; i < 3 ; i = i + 1 ) vsum[i] = a[i] + b[i];}
int main(void){ int x[3] = {1,2,3}, y[3] = {4,5,6}, z[3]; vectorSum( x , y , z ); printf( "%d %d %d", z[0], z[1], z[2] );}
Note:No *No &
88
Function to add two arrays and store the result in a third array.
void add_arrays(double a[], /* input - first array */ double b[], /* input - second array */ double sum[], /* output - array of sums*/ int n) /* input- number of elements*/{ int i;
for (i = 0; i < n; i++)sum[i] = a[i] + b[i];
}
Notice that the assignment statement in the function changes the value stored in the element of array sum with subscript i. This is an example of a function that changes an argument value. The array is considered a function output argument, not an input argument.
Multi-Dimensional Arrays
90
Arrays as Data Structures
Review: An array is an ordered collection of values of identical type -
Name the collection; number the elements
Arrays are the natural choice for organizing a large number of values, all of identical type.
In the mathematical sense, a (one-dimensional) array represents a vector.
91
Beyond Simple Arrays
Sometimes the collection of values has some additional regular pattern or structure.
One common such structure is the matrix or table
In C, we can express this as a two-dimensional array.
Higher-dimensional arrays (3-D, 4-D, …) are possible, but we will not use them in this course.
92
Two-Dimensional Arrays
An ordered collection of values of identical type -
- Name the collection; number the elements
Sounds familiar? Just like 1-D arrays, but a different numbering scheme.
Rows
Columns
93
Example: scores for 7 students on 4 homeworks
int score[7][4];
Number of rows Number of columns
First dimension specifies number of rowsSecond dimension specifies number of columns
Note that element indexes run from 0 - 6 and 0 - 3
94
2-D Arrays: Terminology
Syntax:
type name[# rows][# columns]
E.g.
int score[7][4];
says that score is a two-dimensional array of int of size 7 by 4
score[0][0], score[0][1], .... , score[6][3] are the elements of the array
95
Declaring a 2-D Array
#define MAX_STUDENTS 7
#define MAX_HWKS 4
...
int score [MAX_STUDENTS][MAX_HWKS];
96
An Alternate View
int score[7][4];
We could also view each row as an element:“score is an array of size 7”
With this view, each element (i.e. row) is a 1-D array of type “array of size 4 of int”
We can either think of scores as a 7 by 4 array of scores
... or as an array of 7 one dimensional arrays of size 4
97
Accessing Array Elements
We access the elements of the array just like we did for 1-D arrays, but now with 2 subscripts:
E.g.scores[5][1];
As before, each element of the array behaves exactly like a regular variable.
98
Reading in an Array
Use nested for loops
E.g. read in assignment scores for 7 students:
int i, j, scores[7][4];
for (i=0; i<7; j++{ for (j=0; j<4; i++) { scanf(“%d”, &scores[i][j]); }}
Read row by row
99
Printing the Array
Again, use for loops
for (i=0; i<7; j++){ for (j=0; j<4; i++) { printf(“%d”, &scores[i][j]); }}
100
Bookkeeping
As with 1-D arrays, often we only use part of the space available in a 2-D array.
Declared size of the array specifies its maximum capacity.
The current size (# of rows and columns currently in use) needs to be kept track of in separate variables
101
Reading in Data
Problem: Read in data for student assignments
Input data format: The number of students, then the number of assignments, followed by the data per student.
A nested loop is the right program structure for reading in the data details
int score [MAX_STUDENTS][MAX_HWKS] ;int nstudents, nhwks, i, j ;
102
Reading a 2-D Array
/* Read the number of students and assignments,then loop to read detailed data */
scanf ("%d %d", &nstudents, &nhwks);if (nstudents <= MAX_STUDENTS && nhws <= MAX_HWKS){ for ( i = 0 ; i < nstudents ; i = i + 1 ) for ( j = 0 ; j < nhwks ; j = j + 1 ) scanf("%d", &score [i][j]) ;}
Partially-used array
103
Printing a 2-D Array
if (nstudents <= MAX_STUDENTS && nhwks <= MAX_HWKS){ for ( i = 0 ; i < nstudents ; i = i + 1 ) { for ( j = 0 ; j < nhwks ; j = j + 1 ) printf("%d", score [ i ][ j ]); printf("\n") ; }}
104
2-D Arrays as Parameters
Same as 1-D arrays (almost!):- Individual array elements can be either value orpointer parameters.
- Entire arrays are always passed as pointerparameters - never copied
- Don’t use & and * with entire array parameters
Difference:- Must always specify the size of each dimensionexcept for the first one - no empty brackets, except the first
105
2-D Array As Parameter
A function to read into array a the grade information for the given number of students and assignments
void read_2D( int a[MAX_STUDENTS][MAX_HWS], int nstudents, int nhws )
{ ...}
106
Array Function Arguments
int main(void){ int score[MAX_STUDENTS][MAX_HWS]; int nstudents, nhws;
scanf (“%d %d”, &nstudents, &nhws); if ( nstudents <= MAX_STUDENTS && nhws <= MAX_HWS) read_2D (score, nstudents, nhws) ; ...}
107
Example - Images
An image is normally stored as a 2D array - a rectangular grid.
Image may be moved across screen - animation - by re-positioning black and white squares of image in the grid.
108
Representation of Arrays
A computer’s memory is a one-dimensional array of cells.
How is a 2-D array stored?
Answer: In C, the array rows are stored sequentially: row 0, 1, 2, …
We think:
Actually:
109
Representation
Each row of the array is laid out sequentially in memory,one after the other.