Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1
Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions C has three kinds of repetition statements: –while loop –do loop –for loop The programmer should choose the right kind of loop for the situation BBS514 Structured Programming (Yapısal Programlama)2
while Statement The most general one of these loop statements is while. while ( boolean-expression ) statement where statement can be any statement including a compound statement, an if-statement, another loop statement,... Statement is repeated as long as the condition (boolean-expression) is true. When the condition gets false, the statement is not executed anymore. If the condition never gets false infinite loop If the condition gets immediately false the loop will be repeated zero times. BBS514 Structured Programming (Yapısal Programlama)3
while Statement – Flow Diagram BBS514 Structured Programming (Yapısal Programlama)4 while ( condition ) statement condition statement true false
while Statement Example: int product = 2; while ( product <= 100 ) product = 2 * product; BBS514 Structured Programming (Yapısal Programlama)5 product <= 100 product = 2 * product true false
while Statement – Counter Controlled Loop Print 5 asterisk characters This loop will be repeated for 5 times (count: 0,1,...,4) count = 0; while ( count < 5 ) { printf(“*\n”); count = count + 1; } printf(“done\n”); BBS514 Structured Programming (Yapısal Programlama)6 * * * * * done
while Statement – Counter Controlled Loop Read & sum 5 values sum = 0; count = 0; while ( count < 5 ) { scanf(“%d”, &value); sum = sum + value; count = count + 1; } printf(“sum is %d \n”, sum); BBS514 Structured Programming (Yapısal Programlama) sum is 20
Counter-Controlled Repetition – Example Program A class of 10 students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz The algorithm Set total to zero Set grade counter to one While grade counter is less than or equal to 10 Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average BBS514 Structured Programming (Yapısal Programlama)8
Counter-Controlled Repetition – Example Program /* Class average program with counter-controlled repetition */ #include int main() { int counter, grade, total, average; /* initialization phase */ total = 0; counter = 1; /* processing phase */ while ( counter <= 10 ) { printf( "Enter grade: " ); scanf( "%d", &grade ); total = total + grade; counter = counter + 1; } /* termination phase */ average = total / 10.0; printf( "Class average is %d\n", average ); return 0; /* indicate program ended successfully */ } BBS514 Structured Programming (Yapısal Programlama)9 Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81
Infinite Loops The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally int count = 1; while (count <= 25){ printf(“%d \n”, count); count = count - 1; } BBS514 Structured Programming (Yapısal Programlama)10
Infinite Loops i = 1; while ( i != 50 ) { printf(“%d\n”,i); i = i + 2; } printf(“done”); scanf(“%d”, &i); while ( i != 1 ) { if ( i % 2 == 0) i = i / 2; else i = 3 * i + 1; } printf(“done”); BBS514 Structured Programming (Yapısal Programlama)11 Sometimes, it is difficult to check loop terminating condition.
Sentinel-Controlled Loops What happens if we don’t know how many times a loop will run. Ex: a loop which reads the scores of the students in an exam and find the average of the scores; –we don’t know the number of students. –How are we going to stop the loops? use a sentinel-value We choose a sentinel-value which can not be a score (e.g. –1) We read the scores until this sentinel-value has been entered. When this sentinel-value has been read, we stop the loop. BBS514 Structured Programming (Yapısal Programlama)12
Sentinel-Controlled Loops Problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run. –Unknown number of students –How will the program know to end? Use sentinel value –Also called signal value, dummy value, or flag value –Indicates “end of data entry.” –Loop ends when user inputs the sentinel value –Sentinel value chosen so it cannot be confused with a regular input (such as -1 in this case) BBS514 Structured Programming (Yapısal Programlama)13
/* Class average program with sentinel-controlled repetition */ #include int main() { float average; int counter, grade, total; /* initialization phase */ total = 0; counter = 0; /* processing phase */ printf( "Enter grade, -1 to end: " ); scanf( "%d", &grade ); while ( grade != -1 ) { total = total + grade; counter = counter + 1; printf( "Enter grade, -1 to end: " ); scanf( "%d", &grade ); } /* termination phase */ if ( counter != 0 ) { average = ( float ) total / counter; printf( "Class average is %.2f", average ); } else printf( "No grades were entered\n" ); return 0; /* indicate program ended successfully */ } BBS514 Structured Programming (Yapısal Programlama)14 Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82.50
for Statement Another loop statement in C is for-statement. for-statement is more suitable for counter-controlled loops. for ( initialization ; condition ; increment ) statement which is equivalent to initialization ; while ( condition ){ statement ; increment ; } BBS514 Structured Programming (Yapısal Programlama)15
for Statement – Flow Diagram BBS514 Structured Programming (Yapısal Programlama)16 initialization statement increment condition false true for ( initialization ; condition ; increment ) statement
for Statement Example: for(counter = 1; counter <= 10; counter++ ) printf( "%d\n", counter ); –Prints the integers from one to ten Initialization and increment –Can be comma-separated lists –Example: for (i = 0, j = 0; j + i <= 10; j++, i++) printf( "%d\n", j + i ); BBS514 Structured Programming (Yapısal Programlama)17 No semicolon ( ; ) after last expression
for statement -- Example int i;int sum = 0; for (i=1; i<=20; i++) i = 1; sum = sum + i;while (i<=20) { sum = sum + i; i++; } --- int i; int sum = 0; for (i=100; i>=1; i--) i = 100; sum = sum + i;while (i>=1) { sum = sum + i; i++; } BBS514 Structured Programming (Yapısal Programlama)18
for statement -- Example int i, j; int count=0; for (i=1, j=10; i<j; i++, j--) count is 5 count++; int i, j; int count=0; i=1; j=10; for (; i<j; ) { count++; i++; j--; } BBS514 Structured Programming (Yapısal Programlama)19
The do / while Repetition Structure The do / while repetition structure –Similar to the while structure –Condition for repetition tested after the body of the loop is performed All actions are performed at least once –Format: do { statement; } while ( condition ); BBS514 Structured Programming (Yapısal Programlama)20
do-while statement – Flow Diagram BBS514 Structured Programming (Yapısal Programlama)21 statement condition false true
do-while statement – Example /*Using the do/while repetition structure */ #include int main() { int counter = 1; do { printf( "%d ", counter ); counter = counter + 1; } while ( counter <= 10 ); return 0; } Program Output: BBS514 Structured Programming (Yapısal Programlama)
Nested Loops When a loop body includes another loop construct this is called a nested loop. In a nested loop structure the inner loop is executed from the beginning every time the body of the outer loop is executed. Example 1: value = 0; for (i=1; i<=10; i=i+1) for (j=1; j<=5; j=j+1) value = value + 1; How many times the inner loop is executed? value is 10*5=50 BBS514 Structured Programming (Yapısal Programlama)23
Nested Loops Example 2: value = 0; for (i=1; i<=10; i=i+1) for (j=1; j<=i; j=j+1) value = value + 1; How many times the inner loop is executed? value is =55 BBS514 Structured Programming (Yapısal Programlama)24
Nested Loops - Printing a triangle Write a program to draw a triangle like the following: (The number of lines is an input) * ** *** **** ***** We can use a nested for-loop: for (i=1; i<=num_lines; ++i){ for (j=1; j<=i; ++j) printf("*"); printf("\n"); } BBS514 Structured Programming (Yapısal Programlama)25
Nested Loops – Example2 a triangle shape (1 st line contains 1 star, 2 nd line contains 3 star,..., nth line contains 2n-1 stars) *for (i=1; i<=n; i++) { // for each line *** for (j=1; j<=(n-i); j++) ***** printf(“ ”);. for (j=1; j<=(2*i-1); j++). printf(“*”); ***.....*** printf(“\n”); } BBS514 Structured Programming (Yapısal Programlama)26
Nested Loops – Example3 /* This program reads numbers until the user enters a negative number. For each number read, it prints the number and the summation of all values between 1 and the given number. */ int main() { int num, count, total = 0; printf( "Enter a value or a negative number to end: " ); scanf( "%d", &num ); while ( num >= 0 ) { for (count = 1; count <= num; count++) total = total + count; printf(“%5d%5d”,num, total); printf( "Enter a value or a negative number to end:"); scanf( "%d", &num ); total = 0; } return 0; } BBS514 Structured Programming (Yapısal Programlama)27
Nested Loops – Example4 Nesting can be more than one level int sum=0; for (i=1; i<=5; i++) for (j=1; j<=5; j++) for (k=1; k<=5; k++) sum=sum+1; sum is 125 BBS514 Structured Programming (Yapısal Programlama)28
Loop - Exercises Write a program that reads an integer N and computes N! fact = 1; for (j = 1; j <= n; j++) fact = fact * j; Write a program for finding the sum of the first n terms of the series 1 + 1/2+ 1/3 + …. float sum = 0; for (j = 1; j <= n; j++) sum = sum / j; BBS514 Structured Programming (Yapısal Programlama)29
Loop - Exercises Write a program that reads numbers until a negative number is read and prints the number of values read, the largest value, the smallest value and the range. count =0; scanf (“%d”,&num); min = max = num; while (num >= 0){ count ++; if (num < min) min = num; else if (num > max) max = num; scanf (“%d”,&num); } printf(“count:%d max:%d min:%d range:[%d.. %d]”, count,max,min,min,max); BBS514 Structured Programming (Yapısal Programlama)30
Loop - Exercises Consider the Fibonacci sequence: … Write a program to find the nth Fibonnacci number. int main () { int n, prev1=1, prev2=0, temp, j; printf(“Enter n > “); scanf(“%d”, &n); if (n==0 || n== 1) printf(“%d th Fib number is %d”, n, n); else { prev1 = 0; prev2 = 1; for (j=1; j <= n; j++) { temp = prev1 + prev2; prev2 = prev1; prev1 = temp; } printf(“%d th Fib number is %d”, n, prev1); } BBS514 Structured Programming (Yapısal Programlama)31
Loop - Exercises Write a program to test whether a given positive integer (> 1) is a prime number of not. if (n == 2) printf(“%d is prime”, n); else if (n%2 == 0) printf(“%d is NOT prime”, n); else { flag = 1; for (i = 3; i < (n/2) && flag ); i += 2) { if (n%i == 0) flag = 0; } if (flag == 1) printf(“%d is prime”, n); else printf(“%d is NOT prime”, n); } BBS514 Structured Programming (Yapısal Programlama)32