C++ while executive control statement

The C++ ‘while()’ control executive statement is similar to ‘do() while’ statement.Like the ‘do() while’ statement the ‘while()’ statement is use for iterating a code or program until certain condition has been fulfilled.The pictorial representation of ‘while()’ statement is given below.

Link :C++ do() while statement
 

 

The syntax of while statement is given below.

while( expression1 )
{
//code1
}

Until the expression expression1 is false the code code1 will keep on executing.A code example is given below.

int ii=0;

while( ii<5 )
{
cout<< ii << endl ;

++ii;
}

Output,

0
1
2
3
4

The code example above prints the number lesser than 5,when reaching 5 the expression ‘i<5' returns false so the program is thrown out of the 'while()' loop.

 

Another program is given below where we will find out the number of ‘m’ or ‘M’ characters in a string/text.

#include <iostream>

using namespace std;

int main( )
{
 char st[]= "Many wonderous and marvelous moments!!" ;

 int i = 0 , count=0 ;

 while( i<sizeof(st) ) /**the sizeof(st) gives the total number of characters in 'st' string**/
 {
  if (st[i] == 'm' || st[i] == 'M')
  {
   ++count;
  }
  ++i ;
 }

 cout << "The number of \'m\' characters in \"" << st << "\" is " << count ;

 cin.get( );
 return 0;
}

Output,

The number of ‘m’ characters in “Many wonderous and marvelous moments!!” is 4

A point to note,if you want to write double quotation(“”) of single quotation(”) in the console screen when using ‘cout’,always use slash(\) before the quotation like in the above code.




Leave a Reply

Your email address will not be published. Required fields are marked *