You are on page 1of 12

Repetition Structure

in C++
What is Repetition Structure?

 RepetitionStructure or loops permits a


sequence of instructions to be executed
repeatedly until a certain condition is
reached.
 Each pass of the loop is called iteration.
 Loops comes in three forms: while, do-while
and for.
Kinds of Loops

 Forloop
 While loop
 Do-while loop
Importance of loops…

#include <iostream.h>  The program will show 5


main() siena’s on the screen.
however, if you were ask to
{
do the same program except
cout<<“Siena\n”; this time you print siena 100
cout<<“Siena\n”; times, are you willing to type
cout<<“Siena\n”; cout<< 100 times?
cout<<“Siena\n”;
cout<<“Siena\n”;

}
While loops
Syntax: Example: This program will print
out the number from 1-5.
While (condition) #include <iostream.h>
{ main()
Statement1; {
Statement2; int ctr;
Statementn; ctr=1;
} while(ctr<=5)
{
cout<<“ \n”<<ctr;
++ctr;
}
}
What is wrong in the program?
Example: This program will print out the number from 1-5.
#include <iostream.h>
main()
{
int ctr;
ctr=1;
while(ctr<=5)
{
cout<<“ \n”<<ctr;
}
}
Do-while loops
 Syntax:  Example: This program will
print out all even nos. from
 do{ 1-10.
#include <iostream.h>
main()
Statement1;
{
Statement2;
int ctr;
Statementn;
}while(condition); ctr=1;
do{
cout<<“ \n”<<ctr;
++ctr;
}while(ctr<=10);
What do this program display?

Example: This program will print out all even nos. from 1-10.
#include <iostream.h>
main()
{
int ctr;
ctr=1;
do{
++ctr;
cout<<“ \n”<<ctr;
} while(ctr<=10);
While vs. Do-while

 What makes differ?


Example: This program will print Example: This program will print
out the number from 1-5. out the number from 1-5.
#include <iostream.h> #include <iostream.h>
main() main()
{ {
int ctr; int ctr;
ctr=0; ctr=1;
while(ctr<=5)
do{
{
++ctr; cout<<“ \n”<<ctr;
cout<<“ \n”<<ctr; ++ctr;
} while(ctr<5); }
} }
For loops

Syntax: A program that will print all


for(initialization; condition; statement) even numbers
{ -from 0 – 10.
statement1; #include <iostream.h>
statement2; main()
statementn; {
} int ctr;
for(ctr=0;ctr<=10;ctr+=2)
{
cout<<ctr;
}
Solution…

#include <iostream.h>
main()
{
int ctr;
for(ctr=1;ctr<=5;++ctr)
{
cout<<“siena\n”;
}

}
 Using three kinds of loops, Create a program
to display All ODD numbers from 0 -15 in
decreasing order.
 Ex:
– 15 13 11 9 7 5 3 1

You might also like