Thursday, October 11, 2018

What are the 3 types of loops explain with example?

There are three Types of loops.

i)          for loop
ii)         while loop
iii)        do while loop

Examples of loops

For loop example code
 
#include <iostream.h>
#include <conio.h>
void main(void)
{    clrscr();
int num, fact=1;
cout<<"Enter a number ";
cin>>num;
for(int a=num;a>0;a--)
{
  fact *= a;
}
cout<<"Factorial of "<<num<<" is "<<fact;
getch();
}
While Loop example code


#include<iostream.h>
#include<conio.h>
void main(void)
{    clrscr();
int a=15;
while(a<1 || a>10)
{
   cout<<"Enter a value (1-10) ";
cin>>a;
}
cout<<"Value entered is between 1 - 10";
getch();
}
do while loop example code


#include<iostream.h>
#include<conio.h>
void main(void)
{ char ch;
   int t;
   do
{   clrscr();
  cout<<"Enter Table value ";
  cin>>t;
  for(int a=1;a<=10;a++)
      cout<<t<<" x "<<a<<" = "<<t*a<<endl;
  cout<<“Press Y to Continue ";
  ch=getche();
     }while(ch=='Y' || ch=='y');
  cout<<"\nThanks for using program";
  getch();
}
n
 

No comments:

Post a Comment