C Programming Language OUTLINE Repetition and Loop Statements

  • Slides: 109
Download presentation
C Programming Language OUTLINE Repetition and Loop Statements Arrays Multi-Dimensional Arrays

C Programming Language OUTLINE Repetition and Loop Statements Arrays Multi-Dimensional Arrays

Repetition and Loop Statements

Repetition and Loop Statements

Categories of Flow Controls • Relational, Equality, Logical Operators are provided to facilitate flow

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). 3

Loops So far our programs are very limited - they can only run “straight

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”. 4

A “loop” is a repeated (“iterated”) sequence of statements. Like conditionals, loops let us

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 code within loop is known as the loop body 5

We will study three types of loops: - while loops - for loops -

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 6

 • Counter-controlled repetition – Definite repetition: know how many times loop will execute

• 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" 7

 • Counter-controlled repetition requires – The name of a control variable (or loop

• 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. 8

The while loop repetition condition The syntax is while (condition) { statements; } loop

The while loop repetition condition The syntax is while (condition) { statements; } loop body Note indentation! 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! 9

Steps in using while loop 1. Initialize loop count (loop control variable) 2. Test

Steps in using while loop 1. Initialize loop count (loop control variable) 2. Test loop repetition condition for termination 3. Update loop count 10

Example - Add five integers: int i = 0; // initialize i int temp,

Example - Add five integers: int i = 0; // initialize i int temp, sum = 0; while (i < 5) { // initialize sum // test if i < 5 scanf(“%d”, &temp); sum = sum + temp; i++; // read an integer // add to sum // increment i } Important to initialize the loop count before starting the loop, and to increment the count within the loop. 11

Example - Accumulating a sum int sum, x, count; int number_inputs; /* Number of

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; Initialization while ( count <= number_inputs ) { scanf("%d", &x); Condition sum = sum + x; count = count + 1; Update } 12

Example - Calculate pay count_emp = 0; /* no employees processed yet */ while

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. 2 fn", pay); count_emp = count_emp + 1; /* increment count_emp */ } printf("n. All employees processedn"); 13 */

Example - Computing a Factorial 7! = 1 * 2 * 3 * 4

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. x = 1 * 2 * 3 * 4 * 5 * 6 * 7; printf ( "%d", x ) ; int i = 1; int product = 1; while(i <= 7){ product = product * i; i++; } 14

Example - Factorial Function Even better if we generalize the algorithm and make it

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; Local variables re-initialized at each call while(i <= number){ product = product * i; i++; } return product; } 15

Infinite Loop Using while (1) statement; next statement; • Stop the program in the

Infinite Loop Using 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! 16

The for Loop The syntax is for ( initialization ; condition; update ) {

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. 17

If the initialization, condition and/or update parts are long, place each on a separate

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. initialization 2. 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. 18

for loop versus while loop for and while loops can always be interchanged …

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) { for(i = 0; i < 10; i++) { printf(“%dn”, i); i++; printf(“%dn”, i); } } 19

Which Loop Should You Choose? They are interchangeable, so to some extent it is

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. 20

Example total_pay = 0. 0; for (count_emp = 0; /* initialization */ count_emp <

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. 2 fnn", pay); total_pay = total_pay + pay; } printf("All employees processedn"); printf("Total payroll is $%8. 2 fn", total_pay); 21

Example - Factorial int factorial(int n) { int i, /* local variables */ product;

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 may decrement or increment the loop count - it depends on how we write the initialization and condition parts } 22

Increments and decrements other than one Not obliged to increment / decrement the loop

Increments and decrements other than one Not obliged to increment / decrement the loop count by 1. May use any value. 23

Infinite Loop Using for (; ; ) { statements; } • Stop the program

Infinite Loop Using 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! 24

Example - Celsius / Fahrenheit table #define CBEGIN 10 #define CLIMIT -5 #define CSTEP

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 Fahrenheitn"); /* Display the table */ for (celsius = CBEGIN; celsius >= CLIMIT; celsius -= CSTEP) { fahrenheit = 1. 8 * celsius + 32. 0; printf("%6 c%3 d%8 c%7. 2 fn", ' ', celsius, ' ', fahrenheit); } Practice: C-to-F-table-part. c 25

The Comma Operator and for expr 1 , expr 2 • Lowest precedence of

The Comma Operator and for expr 1 , expr 2 • Lowest precedence of all operators. • Left-to-right associativity. • Value of expr 2 taken as value of the whole expression. • Example, a = 0 , b = 1; • Example for (i=1, factorial=1; i<=n; i++) factorial *= i; 26

Conditional Loops In some situations, you may not know the exact number of loop

Conditional Loops In some situations, you may not know the exact number of loop iterations required. It is still possible to write a loop in such circumstances. Steps: 1. Initialize loop control variable 2. As long as exit condition has not been met 3. Continue processing 27

Loop Design Sentinel-controlled Loops Input a list of data values of any length, terminated

Loop Design Sentinel-controlled Loops Input a list of data values of any length, terminated by a 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; 28

Example - Average Inputs printf ( "Enter values to average, end with -1. 0

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 ; Loop terminates when a sentinel value (-1) is entered at keyboard count = count + 1; scanf ( "%lf", &next ) ; Comments } if (count > 0) printf( "The average is %f. n", sum / (double) count ); 29

Endfile-controlled Loops Input from a file of data and do not know how many

Endfile-controlled Loops Input from a file of data and do not know how many data items 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 using the eof marker - in C, the eof marker is denoted by the reserved word, EOF 30

Example sum = 0; input_status = fscanf(inp, "%d", &score); while (input_status != EOF) {

Example sum = 0; input_status = fscanf(inp, "%d", &score); while (input_status != EOF) { printf("%5 dn", score); sum += score; input_status = fscanf(inp, "%d", &score); } 31

Nested Loops How would you print the following diagram? ***** Solution: repeat 3 times

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! 32

When you put one loop inside another, then you have nested loops Nested loops

When you put one loop inside another, then you have nested loops Nested loops can be much more confusing than single loops! 33

#define ROWS 3 #define COLS 5 … row = 1; while ( row <=

#define ROWS 3 #define COLS 5 … row = 1; while ( row <= ROWS ) { /* print a row of COLS *s */. . . row = row + 1; } 34

#define ROWS 3 #define COLS 5 row = 1; while ( row <= ROWS

#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; Inner loop print one row Outer loop print three rows } printf( "n" ); row = row + 1; } 35

#define ROWS 3 #define COLS 5 outer loop - print 3 rows. . .

#define ROWS 3 #define COLS 5 outer loop - print 3 rows. . . for ( row = 1; row <= ROWS ; row = row + 1 ) { for ( col = 1 ; col <= COLS ; col = col + 1 ) { printf(“*”); } printf( "n" ); inner loop - print one row } 36

How would you print the following diagram? * ** Solution: *** for every row

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" ); } 37

Remember the function to print rows of asterisks between lines of output? Now we

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”); } } 38

Exercise Study and execute the following program. #include <stdio. h> #define N 7 int

Exercise Study and execute the following program. #include <stdio. h> #define N 7 int 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("%3 d%3 d%3 dn", i, j, k); } printf("n. Count: %dn", cnt); return (0); } 39

do. . . while loop The do…while loop is like a while loop, but

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. 40

41

41

Example Checking user input: do { printf(“Enter your age: “); scanf(“%d”, &age); } while

Example Checking user input: do { printf(“Enter your age: “); scanf(“%d”, &age); } while (age < 0); 42

Example counter = 1; do { printf( "%d ", counter ); } while (++counter

Example counter = 1; do { printf( "%d ", counter ); } while (++counter <= 10); 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 = %dn", sum); 43

#include <stdio. h> while condition void main(){ int n, sum; while ( (printf("Enter number

#include <stdio. h> while condition void main(){ int n, sum; while ( (printf("Enter number = ") && scanf("%d", &n) && n) != 0 ) { sum = 0; true (1) do { sum += n % 10; true (1) false (n==0) true (n != 0) n /= 10; } while(n > 0); printf("The sum of the digits is = %dn", sum); } } Practice: sum-digit. c 44

Controlling Repetition break and while #include <stdio. h> Causes an exit from the innermost

Controlling Repetition break and while #include <stdio. h> Causes an exit from the innermost enclosing loop. #include <math. h> int main(void) { int x; while (1) { scanf("%d", &x); If (x < 0) break; printf ("square root = %. 2 fn", sqrt(x)); } printf ("Bye!n"); return (0); } 45

Controlling Repetition … break and for #include <stdio. h> Causes an exit from the

Controlling Repetition … break and for #include <stdio. h> Causes an exit from the innermost enclosing loop. int main(void) Will update be executed before leaving the for loop? { int i, x; for (i=0; i<10; i++) { printf("i = %dt", i); i=0 x = ? 10 i=1 x = ? 20 i=2 x=? 4 i=3 x=? 5 i=4 x=? 0 After the loop, i = 4 Bye! printf("x = ? "); scanf("%d", &x); if (x==0) break; } printf("After the loop, i = %dn", i); printf ("Bye!n"); return (0); } 46

Controlling Repetition … continue Causes the current iteration of a loop to stop, and

Controlling Repetition … continue Causes the current iteration of a loop to stop, and begins the next iteration. #include <stdio. h> #define MAX 5 int 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 %dn. ", sum); return (0); } 10 20 -1 90 -5 Sum of positive values is 120. 47

How to debug and test programs • Debugger Program – Single-step execution (F 8)

How to debug and test programs • Debugger Program – Single-step execution (F 8) – 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 …… 48

Common Programming errors • Off-by-One Loop errors for (i =0; i<n; i++) sum+= i;

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 49

Common Programming errors … Syntax of the for statement for (initialization expression; loop repetition

Common Programming errors … Syntax of the for statement for (initialization expression; loop repetition condition; update expression ) Do not put ; here Always use braces around the loop body, whether it contains one or many statements 50

Common Programming errors … • Be careful when testing for inequality (!=) to control

Common Programming errors … • 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 (=) 51

Arrays

Arrays

Up to now have dealt with a small number of variables and we have

Up to now have dealt with a small number of variables and we have had a separate name for each one - these are so-called scalar variables. But what if we have 10 variables? 1000 variables? … 53

The C programming language (like many other languages) has a construct that allows us

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 54

Data Structures Functions give us a way to organize programs (code). Data structures are

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 are related to one another The array is our first view of such data structures. 55

Array – A structure of related data items – A static entity – same

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 56

Array – Group of consecutive memory locations – Elements of array referred to by

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] 57

Name of array is c (Note that all elements of the array have the

Name of array is c (Note that all elements of the array have the same name) c[0] -45 c[1] 6 c[2] 0 c[3] 72 c[4] 1543 c[5] -89 c[6] 0 c[7] 62 c[8] -3 c[9] 1 c[10] 6453 c[11] 78 Position number of the element within array c - starting at 0 58

Array elements are like normal variables - manipulate them just like simple (scalar) variables:

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] 59

Initialization of array elements Like simple variables, array elements may be initialized by assignment,

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 60

If size of array is omitted, initializers determine it int n[ ] = {

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 }; 61

Example Grades of 7 students 62

Example Grades of 7 students 62

How Do We Average These? Use a loop to add them up: sum =

How Do We Average These? Use a loop to add them up: sum = 0 for each array index add the indexed value to sum When 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; 63

Declaring Arrays • When declaring arrays, must specify – Name of array – Data

Declaring Arrays • When declaring arrays, must specify – Name of array – Data type of array elements – Number of elements in array. Type array. Name[number. Of. Elements]; – Examples: int c[10]; float my. Array[999]; • Declaring multiple arrays of same type – Format similar to regular variables – Example: int b[100], x[27]; 64

Terminology double rain[7]; rain is of type array of double with size 7. rain[0],

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). 65

When you declare an array, the size must be an integer constant! Consider this

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! 66

Accessing Array Elements If we have an array int foo[100], then we can access

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(“the. Value: %dn”, foo[20]); scanf(“%d”, &foo[66]); for (i = 0; i < 100; i++) foo[i] = -10; Arrays are ideal for using in loops! 67

When Can You Use Array Elements? You can use an array element wherever you

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 68

Array Indices (or Indexes) Array indexes always begin at 0 in C There is

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]. 69

Index Rule: An array index must evaluate to an int between 0 and n-1,

Index 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))))] 70

Array Bounds These array indexes are not checked! This is called array bounds checking.

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! 71

What You Cannot Do With Arrays You cannot use = to assign arrays. You

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. 72

More flexible way to declare arrays #define hours_size 10 int main() { double hours[hours_size];

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 73

We use for loops often to process arrays. Enables us to access all array

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, . . . */ 74

/* What about this one? */ hours[0] = 20; for (i = 1; i

/* 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 %sn”, “I”, “hours[i]”); for (i = 0; i < hours_size; i++) printf("%d %fn", 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]); } 75

Write a loop that finds the sum of all values in array hours. Also

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; 76

E. g. Grading program #include <stdio. h> #define NUM_QUEST 10 #define NUM_CLASS_DAYS 5 typedef

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', 'F', 'T'}; int score[NUM_CLASS_DAYS] = {0}, i; for (i = 0; i < 10; i++) { score[Monday] += answer[i] == 'T'; } printf("n. Monday results = %dn", score[Monday]); } 77

E. g. Grading program …. #include <stdio. h> #define NUM_QUEST 10 What will happen

E. g. Grading program …. #include <stdio. h> #define NUM_QUEST 10 What will happen if make this change? #define NUM_CLASS_DAYS 5 typedef enum {Monday, Tuesday, Wednesday, Thursday, Friday} class_days; void main () { char answer[NUM_QUEST]= {'T', 'F', 'T', 'F', 'T'}; int score[NUM_CLASS_DAYS] = {0}, i; for (i = 0; i < 10; i++) { score[Friday + 1] += answer[i] == 'T'; } printf("n. Monday results = %dn", score[Friday + 1]); } 78

Using array elements as function arguments You can pass individual array elements to a

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. my. Array[3]) to function. – Array element must correspond to formal parameter in type. 79

If you have declared a function with prototype void my_fun(int, double); and arrays int

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. 80

Individual array elements can be used as parameters, just like other simple variables. Examples:

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] ); 81

Array arguments You can also pass entire arrays to functions as arguments. Passing arrays:

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 my. Array[24]; my. Function( my. Array, 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. 82

An array is never copied (no call by value) The array name is always

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 contain information about their size, so the size often needs to be passed as an additional parameter. 83

Example: function print_array displays all elements of a type int array. Number of elements

Example: function print_array displays all elements of a type int array. Number of elements in array is a parameter since we do not know the size of the actual argument array when function is called. void print_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. 84

The statement print_array(id, 10); displays all values in array id (array id corresponds to

The statement print_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_array(int[], int); First parameter is an int array 85

#define ARRAY_SIZE 200 double average( int a[ARRAY_SIZE] ) { int i, total = 0;

#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 ); 86

void vector. Sum( int a[3], int b[3], int vsum[3] ) { int i; for

void vector. Sum( int a[3], int b[3], int vsum[3] ) { int i; for ( i = 0 ; i < 3 ; i = i + 1 ) Note: vsum[i] = a[i] + b[i]; No * } No & int main(void) { int x[3] = {1, 2, 3}, y[3] = {4, 5, 6}, z[3]; vector. Sum( x , y , z ); printf( "%d %d %d", z[0], z[1], z[2] ); } 87

Function to add two arrays and store the result in a third array. void

Function to add two arrays and store the result in a third array. void add_arrays(double a[], double b[], double sum[], int n) { int i; /* /* input - first array */ input - second array */ output - array of sums*/ input- number of elements*/ 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. 88

Multi-Dimensional Arrays

Multi-Dimensional Arrays

Arrays as Data Structures Review: An array is an ordered collection of values of

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. 90

Beyond Simple Arrays Sometimes the collection of values has some additional regular pattern or

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. 91

Two-Dimensional Arrays An ordered collection of values of identical type - Name the collection;

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 92

Example: scores for 7 students on 4 homeworks int score[7][4]; Number of rows Number

Example: scores for 7 students on 4 homeworks int score[7][4]; Number of rows Number of columns First dimension specifies number of rows Second dimension specifies number of columns Note that element indexes run from 0 - 6 and 0 - 3 93

2 -D Arrays: Terminology Syntax: type name[# rows][# columns] E. g. int score[7][4]; says

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 94

Declaring a 2 -D Array #define MAX_STUDENTS 7 #define MAX_HWKS 4. . . int

Declaring a 2 -D Array #define MAX_STUDENTS 7 #define MAX_HWKS 4. . . int score [MAX_STUDENTS][MAX_HWKS]; 95

An Alternate View int score[7][4]; We could also view each row as an element:

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 96

Accessing Array Elements We access the elements of the array just like we did

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. 97

Reading in an Array Use nested for loops E. g. read in assignment scores

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 98

Printing the Array Again, use for loops for (i=0; i<7; j++) { for (j=0;

Printing the Array Again, use for loops for (i=0; i<7; j++) { for (j=0; j<4; i++) { printf(“%d”, &scores[i][j]); } } 99

Bookkeeping As with 1 -D arrays, often we only use part of the space

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 100

Reading in Data Problem: Read in data for student assignments Input data format: The

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 ; 101

Reading a 2 -D Array /* Read the number of students and assignments, then

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 102

Printing a 2 -D Array if (nstudents <= MAX_STUDENTS && nhwks <= MAX_HWKS) {

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") ; } } 103

2 -D Arrays as Parameters Same as 1 -D arrays (almost!): - Individual array

2 -D Arrays as Parameters Same as 1 -D arrays (almost!): - Individual array elements can be either value or pointer parameters. - Entire arrays are always passed as pointer parameters - never copied - Don’t use & and * with entire array parameters Difference: - Must always specify the size of each dimension except for the first one - no empty brackets, except the first 104

2 -D Array As Parameter A function to read into array a the grade

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_2 D( int a[MAX_STUDENTS][MAX_HWS], int nstudents, int nhws ) {. . . } 105

Array Function Arguments int main(void) { int score[MAX_STUDENTS][MAX_HWS]; int nstudents, nhws; scanf (“%d %d”,

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_2 D (score, nstudents, nhws) ; . . . } 106

Example - Images An image is normally stored as a 2 D array -

Example - Images An image is normally stored as a 2 D array - a rectangular grid. Image may be moved across screen - animation - by repositioning black and white squares of image in the grid. 107

Representation of Arrays A computer’s memory is a one-dimensional array of cells. How is

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: 108

Representation Each row of the array is laid out sequentially in memory, one after

Representation Each row of the array is laid out sequentially in memory, one after the other. 109