Loop in c++
"Loops are used to do 1 task for multiple number of times until the condition becomes false."
There are 3 types of loops:
- while
- do_while
- For
Essential things for loop
- Initialization of loop variable.
- Condition.
- Increment / decrement.
while:
In this loop the loop variable is initialize before the loop or a loop body.Then loop will apply & the increment/decrement are done in the loop body.First the condition will be checked and if the condition is true then the body of loop will be executed.
Syntax:
Initialization;
while(condition)
{
increment/decrement;
}
Example:
#include<iostream>
using namespace std;
void main()
{
cout<<"Printing alphabets using while loop"<<endl;
char ch= 'A';
while( ch>=65 && ch<=90)
{
cout<<ch<<"\t";
ch++; //increment in loop control variable.
}
system("pause");
}
Output:
do-while:
In this the loop variable should also initialize before the loop or a body of loop.First the body of will always be executed 1 time then the condition will be checked if it's true or not.
Syntax:
do
{
increment/decrement;
}
while(condition);
Example:
#include<iostream>
using namespace std;
void main()
{ char ch='A';
do
{
cout<<ch<<"\t";
ch++;
}
while(ch>=65 && ch<=90);
system("pause");
}
using namespace std;
void main()
{ char ch='A';
do
{
cout<<ch<<"\t";
ch++;
}
while(ch>=65 && ch<=90);
system("pause");
}
Output:
Video:
For loop:
We have three expressions in for loop statement:
- Initialization of loop control variable.
- Condition.
- Increment/decrement of loop control variable
- Initialization expression is executed only the first iteration OR initialization expression is only executed one time when the control is enter first time in the loop.
- Then condition is check. when the condition is true then the body of loop is executed. If the condition is false then the body of loop is not executed.it is also called termination of loop.
- After execution of body of loop the increment/decrement expression is execute. After the execution of increment/decrement statement condition is checked if it is true then the body is executed. if it is false the loop is terminated.
Syntax:
for( initialization ; condition ; increment/decrement )
{ body of loop;
}
Comments
Post a Comment