04 Loops in C++
04 Loops in C++
04 Loops in C++
Increment or Decrement
While Example Program
// Print the I Values Numbers from 0-10
#include <stdio.h>
int main()
{
int i;
i = 0;
while(i<=10)
{
printf(“The Value is %d\n”,i);
++i;
}
return 0;
}
Do While Repetition Structure
• do while structure first executes initialize loop counter;
the statements in the braces do
then checks the condition so
even if the condition is false {
body statements are executed statements;
once increment or decrement loop counter;
Control Flow of
Initialize
do while Loop
Body of Loop
Increment or Decrement
True
Test Condition
False
Stop
#include <iostream>
int main ()
{
// variable declaration:
Program of do
int a = 10;
// do while loop execution
do
Example
{
cout<<“value of a is ”<<a<<endl;
a++;
while
} while( a < 20 ) ;
return 0;
}
FOR REPETITION STRUCTURE
• for loop is another repetitive control structure used to execute
statements repeatedly until condition becomes false
• for loop structure is divided by semicolons into three separate
expressions: the “Initialize expression”, the “test expression”, and the
“Increment/Decrement expression”
{
Body Statements of the for loop;
}
Initialization
Test
Expression Exit
/Condition False
True
Body of loop
loop
Increment /
Decrement
Expression
for loop structure Example Program:
#include <iostream>
using namespace std;
int main()
{
int counter;
for(counter = 1; counter <= 10; counter++ )
{
cout <<“counter = “<<counter<<endl;
}
return 0;
}
Nested Loops
• One loop inside another loop
• In nested loop the inner loop is executed first and then outer
Syntax of for Nested Loop:
continue statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
• If you are using nested loops ( i.e. one loop inside another loop), the
break statement will stop the execution of the innermost loop and
start executing the next line of code after the block
#include <iostream>
EXAMPLE
PROGRAM
using namespace std;
Void main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 )
{
cout<<"value of a “<<a<<endl;
a++;
if( a > 15)
{
/* terminate the loop using break statement */
break;
}
}
}
#include <iostream>