You are on page 1of 12

Repetition and while loops

Assignments
Due Lab 4
Examples
Where is repetition necessary
List a set of problems
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
while
while(condition)
{
statements
}
while
int i = 0; //initialization of control variable
while(i < end_value) //condition
{
printf(%d\n, i);
i++; //update DO NOT FORGET THIS!
}
for
int i;
for(i = 0; i < end_value; i++)
{
printf(%d\n, i);
}
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);
}
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);
}
do-while
int input;

do
{
printf(enter number 0 to quit: );
scanf(%d, &input);
} while(input < 0 || input > 100);
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
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

You might also like