1.09k likes | 1.1k Views
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.
E N D
C Programming Language OUTLINE Repetition and Loop Statements Arrays Multi-Dimensional Arrays
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).
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”.
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
We will study three types of loops: - whileloops - forloops - do…whileloops We will also look at nestedloops - what happens when you put one loop inside another
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"
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.
loop repetition condition • 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 whileloop 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!
Steps in using while loop 1. Initialize loop count (loop control variable) 2. Test loop repetition condition for termination 3. Update loop count
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.
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; } Initialization Condition Update
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");
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 ) ;
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
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!
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.
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.
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); }
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.
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);
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
Increments and decrements other than one Not obliged to increment / decrement the loop count by 1. May use any value.
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!
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
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;
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
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;
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 a sentinel value (-1) is entered at keyboard Comments
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
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); }
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!
When you put one loop inside another, then you have nested loops Nested loops can be much more confusing than single loops!
#define ROWS 3 #define COLS 5 … row = 1; while ( row <= ROWS ) { /* print a row of COLS *s */ ... row = row + 1; }
#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
#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" ); } outer loop - print 3 rows inner loop - print one 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" ); }
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”); } }
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("%3d%3d%3d\n", i, j, k); } printf("\nCount: %d\n", cnt); return (0); }
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.
Example Checking user input: do { printf(“Enter your age: “); scanf(“%d”, &age); } while (age < 0);
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 = %d\n", sum);
#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)
Controlling Repetition break and while Causes an exit from the innermost enclosing loop. • #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); • }
Controlling Repetition … break and for Causes an exit from the innermost enclosing loop. Will update be executed before leaving the for loop? • #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); • } 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!
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 %d\n.", sum); • return (0); • } 10 20 -1 90 -5 Sum of positive values is 120.
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 ……
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
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