Loops and Repetition

Loops and Repetition

Loops in programs allow us to repeat blocks of code.

Useful for:

Trying again for correct input

Counting

Repetitive activities

Programs that never end

Loops and Repetition

Three Types of loops/Repetition in C

while

top-tested loop (pretest)

for

counting loop

forever-sentinel

do ... while

bottom-tested (posttest)

Loops and Repetition

The while loop

Top-Tested loop (pretest)

while(condition)
	statment;
				
Note that, as in IF selection, only one statement is executed. You need a block to repeat more than one statement (using {})
the while loop
Loops and Repetition

The while loop

Similar to the if statement

Check the boolean condition

If true, execute the statement/block

Repeat the above until the boolean is false

the while loop
Loops and Repetition

The while loop

while(condition)
	statement;

while(condition){
	statement1;
	statement2;
}
				
the while loop
Loops and Repetition

How to count using while

First, outside the loop, initialize the counter variable

Test for the counter's value in the boolean

Do the body of the loop

Last thing in the body should change the value of the counter!

int i = 0;
while(i <= 10){
	printf("i=%d\n", i);
	i = i + 1;
}
				
Loops and Repetition

The for Loop

The while loop is pretty general. Anything that can be done using repetition can be done with a while loop.

Because counting is so common, there si a specitalized construct called a for loop.

A for loop makes it easy to set up a counting loop.

The for Loop
Loops and Repetition

The for Loop

Three parts to a for loop (just like the while)

Set the initial value for the counter

Set the condition for the counter

Set how the counter changes each time through the loop

The for Loop
Loops and Repetition

The for Loop

Example

for(count = 1; count <= 5; count++)
	printf("count = %d", count);
			
The for Loop
Loops and Repetition

Ascending for (<=, ++)

for(control_var = init_value; control_var <= limit_value; control_var++)
	statement;
			
Ascending for
Loops and Repetition

Descending for (>=, --)

for(control_var = init_value; control_var >= limit_value; control_var--)
	statement;
			
Descending for
Loops and Repetition

Top-Tested Equivalence For

The following loop

for(x = init; x <= limit; x++)
	statement_list;
			
is equivalent to
x = init;
while (x <= limit){
	statement_list;
	x++;
}
			
Loops and Repetition

break;

The break; statement exits the containing loop immediately!

The following loop

while(true){
	printf("Enter the Positive number: ");
	scanf_s("%d", &a);
	if(a < 0){
		printf("You entered an invalid\n");
	}ele{
		printf("Okay");
		break;
	}
}
			
Loops and Repetition

The do/while loop

do/while

bottom-tested loop (posttest)

do{
	angle += 2 * M_PI / 20;
	sinVal = sin(angle);
	printf("sin(%f) = %f\n", angle, sinVal);
}while(sinVal < 0.5);
			
Loops and Repetition

The do/while loop

do{
	statement;
}while(condition);
			
the do while loop