5.1.While loop

While loop will check the condition first and process again and again until the condition failed.

Syntax:

while (condition)
{
	statement;
	increment / decrement;
}

Example 1:

#include<iostream.h>
#include<conio.h>
void main()
{
	int i=1;
	while(i<=100)
	{
		cout<<"I: "<<i<<endl;
		i++;
	}
	getch();
}

Example 2:

#include<iostream.h>
#include<conio.h>
void main()
{
        int i=1,n,sum=0;
        cout<<"Enter N: "; cin>>n;
        while(i<=n)
        {
   	        sum+=i;
    	        cout<<i<<"+";
                i++;
        }
        cout<<"\b="<<sum;
        getch();
}

Example 3:

#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
        int i,n;
        long sum=0;
        char sym=253;
        cout<<"Enter N: "; cin>>n;
        i=n;
        while(i>0)
        {
    	        sum+=pow(i,2);
                cout<<i<<sym<<"+";
                i--;

        }
        cout<<"\b="<<sum;
        getch();
 }

Example 4:

#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
        int ascii=1;
        char sym;
        while(ascii<=255)
        {
                sym=ascii;
                cout<<ascii<<"="<<sym<<endl;
                ascii++;
        }
        getch();
 }

Example 5:

#include<iostream.h>
#include<conio.h>
void main()
{
        int i=1,n;
        cout<<"Enter N: ";        cin>>n;
        while(i<=10)
        {
                cout<<n<<" * "<<i<<" = "<<n*i<<endl;
                i++;
        }
        getch();
 }

Example 6:

#include<iostream.h>
#include<conio.h>
void main()
{
        char ch;
        int a=97,z=122;
        while(a<=z)
        {
                cout<<(char)a<<",";
                a++;
        }
        getch();
}
Suggest Edit