Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Home About Us Portfolio Contact

Iteration structures
(loops)

30/1/2024
Home About Us Portfolio Contact

Iteration structures (loops)

There are three types of loop for us to cover with c_language : a For
loop, a While and Do While loop. Loops have as purpose to repeat a
statement a certain number of times or while a condition is fulfilled.
The for loop
The for statement repeats the execution of a part of a program.
The syntax:
for (initialization; condition; increment)
{statement to repeat}
It works in the following way:
1. Initialization is executed. Generally it is an initial value setting
for a counter variable.
2. Condition is checked. If it is true the loop continues,
otherwise the loop ends and statement is skipped(not
executed).
3. Statement is executed. As usual, it can be either a single
statement or a block enclosed in braces { }.
4. finally, whatever is specified in the increase field is executed
and the loop gets back to step 2.
Example
write a program to calculate the sum of numbers and compute the average of them .
#include<iostream>
using namespace std;
main()
{ int n,i;
float ave ,sum,num;
sum=0.0;
cout<<" n=";
cin>>n;
for(i=0;i<n;i++)
{ cout<<"enter num";
cin>>num;
sum+=num;
}
ave=sum/n;
cout<<"\n the average of all number=";
cout<<ave ; }
Example
Write a program to evaluate the sum of even integers between 2 and 50.
#include<iostream>
using namespace std;
int main()
{ int sum=0;
for(int i=2;i<=50;i++){
if(i%2==0){
sum+=i;
cout<<“ ”<<i;
}
}
cout<<sum<<endl;}
Example
Write a program to print alphabets descending from Z to A

#include<iostream>
using namespace std;
int main()
{
for(char ch='Z';ch>='A';--ch){

cout<<ch<<" ";
}
}
Example
The following program demonstrates the use of the infinite for clause.

#include<iostream>
using namespace std;
int main()
{ int i=2;
for(;;){
cout<<i<<" ";
i+=2;
}

}
The while statement

The while statement repeats the execution of a statement as long as a condition Istrue.

The syntax :
While(condition)
{statement }
Example
write a program to find the sum of the numbers from 1 to 99.

/*1+2+3+……………+99*/
#include<iostream >
void main()
{ int i,sum;
sum=0;
i=1;
while(i<=99)
{
sum=sum+i;
i++; }
cout<<" sum ="<<sum;
}
Example
Write a program to print alphabets from A to Z

#include<iostream >
using namespace std;
main()
{char x='A';
while(x<='Z')
{cout<<x<<" ";
x++;} }
Example
example for nested while loop

#include<iostream >
void main()
{ int i,j;
i=j=1;
while(i<=4)
{while(j<=6)
{cout<<"\n"<<i*j;
++j;}
++i;
j=1;}
Do _while loop:

General syntax:

Do
{
Statement
}while(condition);

The test is performed at the end of loop .So the loop executed at least once.
Example
write a program to find the sum of the numbers from 1 to 99.

/*1+2+3+……………+99*/
#include<iostream >
void main()
{ inti,sum;
sum=0;
i=1;
do
{
sum=sum+i;
i++; } while(i<=99);

cout<<" sum ="<<sum;


}

You might also like