Loops in c++ with examples
Loops make the set of statements executed until a specific condition met. The types of loops in c++ are given below..
- · ‘for loop’
- · ‘while’ loop
- · ‘do -while’ loop
Each and
every loop is illustrated with an example.
‘for loop’:
Most common type of loop is for
loop. It has following syntax.
‘for(initialization;
condition; increment)’
Eg:
‘for(i=0;i<n;i++)’
C++
Program:
#include
<iostream>
using
namespace std;
int main()
{
int i,n;
cout<<"Enter the number of
elements:"<<endl;
cin>>n;
cout<<"The elements
are:"<<endl;
for(i=1;i<=n;i++)
{
cout<<i<<endl;
}
return 0;
}
Output:
Enter the
number of elements:
7
The
elements are:
1
2
3
4
5
6
7
Next one is
while loop.
‘while loop’
This is also a loop which makes
the condition is satisfied to execute the set of statements.
Syntax:
While(condition)
{
----------------------
}
C++ Program
to find the sum of the digit:
#include
<iostream>
using
namespace std;
int main()
{
int n,a,s=0;
cout<<"Enter the n
value"<<endl;
cin>>n;
while(n>0)
{
a=n%10;
s = s+a;
n=n/10;
}
cout<<"The sum of the digit
is:"<<s;
return 0;
}
Output:
Enter the n
value
897
The sum of
the digit is:24
Next one is
‘do while’ loop.
‘do while
loop’:
This loop has following syntax
‘ do {
…………
}
while(Condition);
C++ Program
to find count the number of digits:
#include <iostream>
using namespace std;
int main() {
int n,a,c=0;
cout<<"Enter the n value"<<endl;
cin>>n;
do
{
a=n%10;
c=c+1;
n=n/10;
}while(n>0);
cout<<"The count of the digit is:"<<c;
return 0;
}
Output:
Enter the n
value
564
The count
of the digit is:3
These are
the various types of loops in c++ was explained briefly with examples. Hope,
this will help you to understand the concept. Keep Coding!!!
Comments
Post a Comment