Download Loops in C++

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Addition wikipedia , lookup

Mathematics of radio engineering wikipedia , lookup

Transcript
Loops in C++
1. Define loop.
A loop is a sequence of instruction s that is continually repeated until a certain condition is
reached.
2.Which are the different types of loop?
While loop, do…while loop and for loop are the different types of loop.
3. Define while loop.
While loop is an entry controlled loop. A while loop statement repeatedly executes a set of
statements as long as a given condition is true.
Syntax:
The syntax of a while loop in C++ is:
while(condition)
{
statement(s);
}
4.Write a program to print numbers from 1 to 10 using while loop.
#include<iostream.h>
#include<conio.h>
void main()
{
int i=1;
while(i<=10)
{
cout<<i;
i++;
}
getch();
}
5.Write a program to print numbers from 1 to n using while loop.
#include<iostream.h>
#include<conio.h>
void main()
{
int i=1,n;
cout<<”Enter the limit”;
cin>>n;
while(i<=n)
{
cout<<i;
i++;
}
getch();
}
6.Write a program to print even numbers from 1 to n using while loop.
#include<iostream.h>
#include<conio.h>
void main()
{
int i=2,n;
cout<<”Enter the limit”;
cin>>n;
while(i<=n)
{
cout<<i;
i=i+2;
}
getch();
}
7. Write a program to print odd numbers from 1 to n using while loop.
#include<iostream.h>
#include<conio.h>
void main()
{
int i=1,n;
cout<<”Enter the limit”;
cin>>n;
while(i<=n)
{
cout<<i;
i=i+2;
}
getch();
}
8. Write a program to find the reverse of a number using while loop.
#include<iostream.h>
#include<conio.h>
void main()
{
int n,r=0,d;
cout<<”Enter the number”;
cin>>n;
while(n>0)
{
d=n%10;
r=(r*10)+d;
n=n/10;
}
cout<<”Reverse=”<<r;
getch();
}
9. Define do…while loop.
While loop is an exit controlled loop.The do-while loop is similar to the while loop,except the
test condition occurs at the end of the loop.The do...while loop is guaranteed to execute at least
one time.
Syntax:
The syntax of a do…while loop in C++ is:
do
{
statement(s);
}while(condition);
10.Write a program to print numbers from 1 to 10 using do…while loop.
#include<iostream.h>
#include<conio.h>
void main()
{
int i=1;
do {
cout<<i;
i++;
} while(i<=10);
getch();
}
11.Write a program to print numbers from 1 to n using do….while loop.
#include<iostream.h>
#include<conio.h>
void main()
{
int i=1,n;
cout<<”Enter the limit”;
cin>>n;
do
{
cout<<i;
i++;
} while(i<=n);
getch();
}