Presentation is loading. Please wait.

Presentation is loading. Please wait.

Repetition and while loops. Assignments Due – Lab 4.

Similar presentations


Presentation on theme: "Repetition and while loops. Assignments Due – Lab 4."— Presentation transcript:

1 Repetition and while loops

2 Assignments Due – Lab 4

3 Examples Where is repetition necessary –List a set of problems

4 Types of Loops Counting loop –Know how many times to loop Sentinel-controlled loop –Expect specific input value to end loop Endfile-controlled loop –End of data file is end of loop Input validation loop –Valid input ends loop General conditional loop –Repeat until condition is met

5 while while(condition) { statements }

6 while int i = 0; //initialization of control variable while(i < end_value) //condition { printf(“%d\n”, i); i++; //update – DO NOT FORGET THIS! }

7 for int i; for(i = 0; i < end_value; i++) { printf(“%d\n”, i); }

8 Sentinel-controlled int input; printf(“enter number – 0 to quit: “); scanf(“%d”, &input); while(input != 0) { printf(“your number is %d”, input); printf(“enter number – 0 to quit: “); scanf(“%d”, &input); }

9 Input Validation int input; printf(“enter number – 0 to 100: “); scanf(“%d”, &input); while(input 100) { printf(“enter number – 0 to quit: “); scanf(“%d”, &input); }

10 do-while int input; do { printf(“enter number – 0 to quit: “); scanf(“%d”, &input); } while(input 100);

11 Infinite Loops If your program “hangs” – you probably forgot to update your control variable Why is this bad? for(i = 0; i != end_value; i++) //BAD

12 Infinite Loops If your program “hangs” – you probably forgot to update your control variable Why is this bad? for(i = 0; i != end_value; i++) //BAD { printf(“Hello”); i *=5; } for(i = 0; i < end_value; i++) //BETTER


Download ppt "Repetition and while loops. Assignments Due – Lab 4."

Similar presentations


Ads by Google