Saturday 14 October 2017

While Loop

WHILE LOOP

while studying for loop we have seen that all the three parts of the loop are present in a line but in while loop, there is a difference in the syntax.In while loop, we initialize the loop outside the loop then test condition where the loop is defined and update condition in the body of the loop.

syntax:-
initialization expression;
while (test_expression)
{
   // statements
 
  update_expression;
}
program to print even number between 0 to 10:-

#include<iostream>
using namespace std;
int main(){
 int i=0; //initialization 
 while(i<=10)   //test condition
 {
  
  cout<<i<<endl;
  i=i+2;     //update condition
  
 }
 return 0;
}
output:-
0
2
4
6
8
10
In the above program, we declare and initialize i=0, then it will compare the value of i with the test condition, if it is true then the body will execute and give increment to the i and the condition run itself again and again. when i is greater then test condition, the condition became false and the loop will terminate. 

INFINITE WHILE LOOP:-
In this loop, there is no initialization, test condition, and update condition just provide 1 instead of the test condition.

syntax:-
#include<iostream>
using namespace std;
int main(){
 
 while(1)  
 {
 
  cout<<"hello world"<<endl;
 
  
 }
 return 0;
}
Note: you will use CTRL+C to terminate the loop.

NESTED WHILE LOOP:-
In nested while loop, a while loop is present inside the body of the while loop.

syntax:-
 initialization;
 while(test condition)  
 {
  initialization;
      while(test condition)
      {
       //statements
       update condition;
          }
   update condition;
       
 }
HOW TO USE WHILE LOOP IN COMPETITIVE PROGRAMMING:-

program:-
#include<iostream>
using namespace std;
int main()
{
 int t;
 cin>>t;
 int n;
 while(t--)
 {
  cin>>n;
  if(n<10)
   cout<<endl<<"what an obedient servant you are!";
  else
   cout<<endl<<"-1";
 }
 return 0; 
}
Now understand the program, you want to run the program for different test cases, you will use while loop in the above manner.

KEEP CLAM AND CODE C++.....





0 comments:

Post a Comment