Control Flow - Loops

Prateek Narang

Topics

  • Loops

  • While Loop

  • For Loop

  • Do While Loop

  • Examples

  • Nested Loops

Think of a situation ....

When you are repeating certain action again & again!

We can encounter situtations ....

When we want to repeat a set of instructions again & again 

Loops

In programming, we often encounter situations, when a block of code needs to be executed several number of times.

A loop statement allows us to execute a statement or group of statements multiple times.

 

While Loop

Loops Control Flow

Example - Say count 50 steps on treadmill.

While Loop

// initialisation

while(condition){
	
    // code block
    
    // update
}

The while loop loops through a block of code as long as a specified condition is true.

While Loop Example

int i = 0;
while (i < 5) {
  cout << i << "\n";
  i++;
}

Problems

For Loop

For Loop

for(init; condition ; update){
	// code block 

}

For loop is very similar to while loop, it combines the 3 steps that have seen in a single line. Both for loop and while loop can be used interchangeably and have same performance.

For Loop Example

for(int step=1; step<=5 ; step=step+1){
	// code block 
    cout << step <<endl;
}

Do While

The do/while loop is a exit controlled loop.
This loop will execute the code block  at-least once, before checking if the condition is true, then it will repeat the loop as long as the condition is true

Do While

do {
  // code block to be executed
  
}
while (condition);

The do/while loop is a exit controlled loop.
This loop will execute the code block  at-least once, before checking if the condition is true, then it will repeat the loop as long as the condition is true

Do While Example

int i = 0;
do {
  cout << i << "\n";
  i++;
}
while (i < 5)

Common Mistakes!

The do/while loop is a exit controlled loop.
This loop will execute the code block  at-least once, before checking if the condition is true, then it will repeat the loop as long as the condition is true

Do While Example

int i = 0;
do {
  cout << i << "\n";
  i++;
}
while (i < 5)

Break Statement

Break Statement

Break statement is used to explicitly terminate the loop based upon a certain condition.

As soon as the break statement is encountered from within a loop, the loop stops and control returns from the loop immediately to the first statement after the loop.


while(....){

	if(condition){
		break;
	}
}

Continue

It is also a control statement, it takes control to execute the next iteration of the loop.

 

Continue Statement


while(....){

	if(condition){
		continue;
	}
}

Problems!

Made with Slides.com