Loops in C++





Loops in C++
Loop is used when we want to execute a part of a program or a block of statements several times. It causes a section of the program to be repeated for a certain number of times. The repetition continues as long the loop condition is true. When the condition becomes false, the looping ends and control is passed to the statement following the loop. The following loop structures are supported by c++:

  • For loop

This loop consists of three expressions. The first expression is used to initialize the control variable, the second is to test the value of the control variable to check whether or not the loop is to be continued again and the third is to change the value of control variable for future repetition.

The syntax of the for loop is:

For (initialization variable; test expression; update expression)
{
Body of the loop
}

A program to find the square of the number from 1 to 100.

#include<iostream.h>
#include<conio.h>
Void main ()
{
Int I;
For (i=1; i<=100; i++)
{
Cout<<”\n the square of “<<i<<”is :”<< i*I;
}
getch ();
}

 

  • While loop

The syntax of while loop:-

While (condition)
{
Body of the loop;
}

The while loop evaluates the condition first, if the condition is true, the body of the loop is executed. The loop continues as long as the condition is true.
E.g.
A program to find the sum of the first 100 natural numbers. Sum=1+2+3+….100.

#include<iostream.h>
#include<conio.h>
Void main ()
{
Int i=1; sum =0;
Clrscr ();
While (i<=100)
{
Sum=sum+I;
I++;
}
Cout<<”\n sum=”<<sum;
getch ();
}

  • Do – while loop

The syntax of the do while loop is:-

Do
{
Body of loop
}
While (expression);

This construct executes the body of the loop exactly once, and hen evaluates the test condition. If the loop condition is true, the execution is repeated, otherwise the loop ends and control is passed to the statement following the loop.

A program to find the sum of the even number using do while loop. I.e.  Sum= 2+4+6….n

#include<iostream.h>
#include<conio.h>
Void main ()
{
Int n, sum, I;
I=2; sum=0;
Cout<<”\n how many numbers?”;
Cin>>n;
Do
{
Sum=sum+I;
I=i+2;
}
While (i<=n);
Cout<<”\n sum=”<<sum;
getch ();
}



Related posts:

  1. If Statements In C++ If statements in c++ It is used to test the...
  2. If Else Statement In C++ If else statement in c++ Its general form is:- If...
  3. Switch Statement In C++ Switch statement in c++ C++ provides a multi way decision...
  4. Type Conversion In C++ Type Conversion In C++ This process of converting one predefined...
  5. C++ Cast Explicit type conversion (casts) in c++ or c++ cast It...