Presentation is loading. Please wait.

Presentation is loading. Please wait.

Control Structures Lecture 7.

Similar presentations


Presentation on theme: "Control Structures Lecture 7."— Presentation transcript:

1 Control Structures Lecture 7

2 Outline Control Structures Repetiton structure While Do while For

3 Repetition Example: Write a program that read 3 integer and compute average It is easy. 3 scanf, an addition, a division and, a printf Example: Write a program that read 3000 integer and compute average  ?? 3000 scanf !!! Example: Write a program that read n integer and compute average N??? scanf Repetition in algorithms

4 Repetition: counter controlled
When we know the number of iteration Average of 10 number Initialize counter  0 Initialize other variables While (counter < number of loop repetition) do something (e.g. read input, take sum) counter  counter + 1

5 Repetition: counter controlled
Consider the following problem statement: A class of ten 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.

6 Repetition: sentinel controlled
When we do NOT know the number of iteration But we know, when loop terminates E.g. Average of arbitrary positive numbers ending with <0 Get first input  n While (n is not sentinel) do something (sum, …) get the next input  n if (there is not any valid input) then S1 else S2

7 Repetition: sentinel controlled
Consider the following problem: Develop a class averaging program that will process an arbitrary number of grades each time the program is run. One way to solve this problem is to use a special value called a sentinel value (also called a signal value, a dummy value, or a flag value) to indicate “end of data entry.”

8 Repetition: sentinel controlled
The user types in grades until all legitimate grades have been entered. The user then types the sentinel value to indicate that the last grade has been entered. Clearly, the sentinel value must be chosen so that it cannot be confused with an acceptable input value.

9 Repetition: sentinel controlled

10 Repetition Repetition is performed by loops Don’t loop to infinity
Put all statements to repeat in a loop Don’t loop to infinity Stop the repetition Based on some conditions (counter, sentinel) C has 3 statements for loops while statement do-while statement for statement

11 Repetition Structure A loop tests a condition, and if the condition exists, it performs an action. Then it tests the condition again. If the condition still exists, the action is repeated. This continues until the condition no longer exists x < y? Process A YES

12 Repetition Essentials
A loop is a group of instructions the computer executes repeatedly while some loop-continuation condition remains true. We have discussed two means of repetition: Counter-controlled repetition Sentinel-controlled repetition Counter-controlled repetition is sometimes called definite repetition because we know in advance exactly how many times the loop will be executed. Sentinel-controlled repetition is sometimes called indefinite repetition because it’s not known in advance how many times the loop will be executed.

13 Counter-Controlled Repetition
In counter-controlled repetition, a control variable is used to count the number of repetitions. Counter-controlled repetition requires: The initial value of the control variable. The increment (or decrement) by which the control variable is modified each time through the loop. The condition that tests for the final value of the control variable (i.e., whether looping should continue).

14 Sentinel-Controlled Repetition
Sentinel values are used to control repetition when: The precise number of repetitions is not known in advance, and The loop includes statements that obtain data each time the loop is performed. The sentinel is entered after all regular data items have been supplied to the program. Sentinels must be distinct from regular data items.

15 While statement while ( <expression> ) <statements>

16 #include <stdio.h> برنامه ای بنویسید که عدد n را از کاربر بگیرد و اعداد 0 تا n را چاپ کند. int main(void){ int n, number; number = 0; printf("Enter n: "); scanf("%d", &n); while(number <= n){ printf("%d \n", number++; number); } return 0; number = -1; while(++number <= n) printf("%d \n", number); }

17 #include <stdio.h>
int main(void){ int negative_num, positive_num; int number; negative_num = positive_num = 0; printf("Enter Zero to stop \n"); printf("Enter next number: "); scanf("%d", &number); while(number != 0){ if(number > 0) positive_num++; else negative_num++; printf("Enter next number: "); scanf("%d", &number); } printf("The number of positive numbers printf("The number of negative numbers return 0; = %d\n", positive_num); = %d\n", negative_num); }

18 Another Example Consider a program segment designed to find the first power of 3 larger than 100. When the following while repetition statement finishes executing, product will contain the desired answer: product = 3; while ( product <= 100 ) { product = 3 * product; } /* end while */

19 Do-while statement do <statements> while (<expression>);

20 #include <stdio.h>
int main(void){ int n; double number, sum; printf("Enter n > 0: "); scanf("%d", &n); if(n < 1){printf("wrong input"); return sum = 0; number = 0.0; do{ number++; sum += number / (number + 1.0); }while(number < n); -1;} printf("sum = %f\n", sum); return 0; }

21 #include <stdio.h>
int main(void){ int negative_num=0, positive_num=0; int number; printf("Enter Zero to stop \n"); do{ printf("Enter next number: "); scanf("%d", &number); if(number > 0) positive_num++; else if(number < 0) negative_num++; }while(number != 0); printf("The number of positive printf("The number of negative return 0; numbers numbers = %d\n", positive_num); = %d\n", negative_num); }

22 for(<expression1>;<expression2>; <expression3>) <statements>

23 int x, sum, i; sum = 0; for (i = 1; i < 6; i++) { scanf(“%d”,&x);
counter ← 1, sum ← 0 int x, sum, i; sum = 0; for (i = 1; i < 6; i++) { scanf(“%d”,&x); sum = sum + x; } counter < 6 false true input n sum ← sum + n counter++ printf(“%d”,sum); output sum 23

24 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
??? Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num _ 24

25 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num _ 25

26 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num _ 26

27 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 _ 27

28 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
2 Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 _ 28

29 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
2 Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 _ 29

30 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
2 Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 _ 30

31 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 _ 31

32 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 _ 32

33 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 3 _ 33

34 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
4 Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 3 _ 34

35 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
4 Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 3 _ 35

36 for (num = 1; num <= 3; num++ ) printf(“%d\t”, num);
4 Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 3 have come to exit_ 36

37 #include <stdio.h> int main(void){
int grade, count, i; double average, sum; sum = 0; printf("Enter the number of students: "); scanf("%d", &count); for(i = 0; i < count; i++){ printf("Enter the grade of %d-th student: scanf("%d", &grade); sum += grade; } average = sum / count; ", (i + 1)); printf("The average of your class is %0.3f\n", return 0; average); }

38 #include <stdio.h> int main(void){
int n, number; printf("Enter n: "); scanf("%d", &n); <= n; number++) 0) for(number = 1; number if((number % 2) == printf("%d \n", number); return 0; }

39 #include <stdio.h> int main(void){
int n, number; printf("Enter n: "); scanf("%d", &n); for(number = 2; number <= n; number += 2) printf("%d \n", number); return 0; }

40 Expressions in for statements
Expression1 and Expression3 can be any number of expressions  for(i = 0, j = 0; i < 10; i++, j--) Expression2 at most should be a single expression  for(i = 0, j = 0; i < 10, j > -100; i++, j--) //ERROR Any expression can be empty expression for(;i<10;t++) for(;;)//infinite loop

41 Expressions in for statements
The three expressions in the for statement are optional. One may omit expression1 if the control variable is initialized elsewhere in the program. If expression2 is omitted, C assumes that the condition is true, thus creating an infinite loop. expression3 may be omitted if the increment is calculated by statements in the body of the for statement or if no increment is needed.

42 for Repetition Statement
The for repetition statement handles all the details of counter-controlled repetition.

43 Examples The following examples show methods of varying the control variable in a for statement. Vary the control variable from 1 to 100 in increments of 1. for ( i = 1; i <= 100; i++ ) Vary the control variable from 100 to 1 in increments of -1 (decrements of 1). for ( i = 100; i >= 1; i-- ) Vary the control variable from 7 to 77 in steps of 7. for ( i = 7; i <= 77; i += 7 ) Vary the control variable from 20 to 2 in steps of -2. for ( i = 20; i >= 2; i -= 2 ) Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17. for ( j = 2; j <= 17; j += 3 ) Vary the control variable over the following sequence of values: 44, 33, 22, 11, 0. for ( j = 44; j >= 0; j -= 11 )

44 Empty statements <statement> in loops can be empty
while(<expression>) ; E.g., while(i++ <= n) ; for(<expression1>; <expression2>;<expression3>); E.g., for(i = 0; i < 10; printf("%d\n",i), i++) ;

45 Nested loops <statement> in loops can be loop itself
while(<expression0>) for(<expression1>; <expression2>;<expression3>) <statements> do while(<expression>);

46 Nested loops example 1 A program that takes n and m and prints
*** ….* (m * in each line) *** ….* *** ….* (n lines)

47 #include <stdio.h>
int main(void){ int i, j, n, m; printf("Enter n & scanf("%d%d", &n, m: "); &m); for(i = 0; i < n; i++){ for(j = 0; j < m; j++) printf("*"); printf("\n"); } return 0;

48 Nested loops example 2 A program that takes n and prints * ** *** (i * in i-th line) *** ….* (n lines)

49 #include <stdio.h> int main(void){ int i, j, n; printf("Enter n: "); scanf("%d", &n); i = 1; while(i <= n){ for(j = 0; j < i; j++) printf("*"); printf("\n"); i++; } return 0;

50 Nested loops example 3 A program that takes a number and generates the following pattern for(i= 1; i <= n; i++){ for(j= 0; j < i-1;j++) printf(" "); for(j= 1; j <= i; j++) printf("*"); printf("\n"); } for(i=n-1; i >= 1; i--){ for(j= 1; j < i; j++) for(j = 1; j <= i; j++) Input = 5 * ** *** **** *****

51 break statement The break and continue statements are used to alter the flow of control. The break statement, when executed in a while, for, do…while or switch statement, causes an immediate exit from that statement. Program execution continues with the next statement.

52 break statement Exit from loop based on some conditions do{ scanf("%d", &a); scanf("%d", &b); if(b == 0) break; res = a / b; printf("a /= %d\n", res); }while(b > 0);

53

54 break statement int i,j; for(i=1; i<6;i++){ for(j =1; j<6;j++) { printf("%d %d\n" , i,j); if(j==3) break; }

55 continue statement Jump to end of loop and continue repetition
The continue statement, when executed in a while, for or do…while statement, skips the remaining statements in the body of that control statement and performs the next iteration of the loop. do{ scanf("%f", &a); scanf("%f", &b); if(b == 0) continue; res = a / b; printf("a / b= %f\n", res); }while(a> 0);

56

57 Which loop? When you know the number of repetition
Counter-controlled loops Usually, for statements When you don’t know the number of repetitions (sentinel loop) Some condition should be check before starting loop Usually, while statement The loop should be executed at least one time Usually, do-while statement

58 Common bugs and avoiding them
Loop should terminate E.g., in for loops, after each iteration, we should approach to the stop condition for(i = 0; i < 10; i++) //OK i--) //Bug Initialize loop control variables int i; for( ; i < 10; i++) //Bug

59 Common bugs and avoiding them
Don’t modify for loop controller in loop body for(i = ... i--; 0; i < 10; i++){ //Bug } Take care about wrong control conditions  < vs. <=  = vs. == int b = 10; while(a = b){//it means while(true) scanf("%d",&a) {


Download ppt "Control Structures Lecture 7."

Similar presentations


Ads by Google