Repetition and while loops. Assignments Due – Lab 4.

12
Repetition and while loops

Transcript of Repetition and while loops. Assignments Due – Lab 4.

Page 1: Repetition and while loops. Assignments Due – Lab 4.

Repetition and while loops

Page 2: Repetition and while loops. Assignments Due – Lab 4.

Assignments

• Due – Lab 4

Page 3: Repetition and while loops. Assignments Due – Lab 4.

Examples

• Where is repetition necessary – List a set of problems

Page 4: Repetition and while loops. Assignments Due – Lab 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

Page 5: Repetition and while loops. Assignments Due – Lab 4.

while

while(condition)

{

statements

}

Page 6: Repetition and while loops. Assignments Due – Lab 4.

while

int i = 0; //initialization of control variable

while(i < end_value) //condition

{

printf(“%d\n”, i);

i++; //update – DO NOT FORGET THIS!

}

Page 7: Repetition and while loops. Assignments Due – Lab 4.

for

int i;

for(i = 0; i < end_value; i++)

{

printf(“%d\n”, i);

}

Page 8: Repetition and while loops. Assignments Due – Lab 4.

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

}

Page 9: Repetition and while loops. Assignments Due – Lab 4.

Input Validation

int input;

printf(“enter number – 0 to 100: “);scanf(“%d”, &input);while(input < 0 || input > 100) {

printf(“enter number – 0 to quit: “);scanf(“%d”, &input);

}

Page 10: Repetition and while loops. Assignments Due – Lab 4.

do-while

int input;

do

{

printf(“enter number – 0 to quit: “);

scanf(“%d”, &input);

} while(input < 0 || input > 100);

Page 11: Repetition and while loops. Assignments Due – Lab 4.

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

Page 12: Repetition and while loops. Assignments Due – Lab 4.

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