Sunday, 1 March 2015

Nested while loop

Nested while loop   Nested while loop In nested while loop the outer loop condition is checked first if the outer while loop con... thumbnail 1 summary

Nested while loop

 

Nested while loop In nested while loop the outer loop condition is checked first if the outer while loop condition is true then the next inner while loop condition will be checked and if the inner while loop condition is true then it will executed and then next and so on. The program will not terminate until the outer while loop condition is true when the outer loop condition become wrong then program will terminate.


Syntax
while()
{
Statement 1
Increment or decrement
while ()
{
Statement 2
Interment or decrement


Example 1 

#include<iostream.h>
int main()
{
int a=1;
while(a<2)
{
cout<<"Cat"<<endl;
a=a+1;
int b=0;
while(b<3)
{
cout<<"Dog"<<endl;
b=b+1;
}
};
system("pause");
return 0;
};
Output:
Cat Dog Dog Dog
In this example the outer loop condition is true so the Cat is printed on the screen and then the inner
loop condition is checked it is also true so it will print the Dog on the screen three times and when its
condition is become wrong then the outer loop condition is checked if it also wrong then program is terminated.


Example 2
#include<iostream.h>
int main()
{
int a=3;
while(a<2)
{
cout<<"Cat"<<endl;
a=a+1;
int b=0;
while(b<3)
{
cout<<"Dog"<<endl;
b=b+1;
}
};
system("pause");
return 0;
};

no output will display

 This is because the outer while loop condition is wrong and the inner while loop condition is true but still no output will displayed.

Example 3

#include<iostream.h>
int main()
{
int a=1;
while(a<2)
{
cout<<"Cat"<<endl;
a=a+1;
int b=4;
while(b<3)
{
cout<<"Dog"<<endl;
b=b+1;
}
};
system("pause");
return 0;
}; 

output: Cat

In this example the outer while loop condition is true so the statement which is defined in the body of for loop will executed but the inner loop condition is wrong so it will not executed.

Example 4
#include<iostream.h>
int main()
{
int a=1;
while(a<3)
{
cout<<"Cat"<<endl;
a=a+1;
int b=0;
while(b<2)
{
cout<<"Dog"<<endl;
 b=b+1;
}
};
system("pause");
return 0;
};

Output:

Cat Dog Dog Cat Dog Dog

 It this example the outer while loop and the inner while loop condition is true so both of the statement will executed. In this example the outer loop condition is true so the Cat will display on the screen then the value of variable used in outer for loop is increases by 1 and the next inner loop condition will be checked and it is also true in this case so it will print the Dog on the screen two time because of it condition and then its condition will become wrong then compiler jumps on the outer loop and checked its condition and it true so it will executed and so on.