Repetition Structure in C++
What is Repetition Structure? Repetition
Structure 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 For
loop While loop Do-while loop
Importance of loops… #include main() { cout<<“Siena\n”; cout<<“Siena\n”; cout<<“Siena\n”; cout<<“Siena\n”; cout<<“Siena\n”; }
The program will show 5 siena’s on the screen. however, if you were ask to do the same program except this time you print siena 100 times, are you willing to type cout<< 100 times?
While loops Syntax: While (condition) { Statement1; Statement2; Statementn; }
Example: This program will print out the number from 1-5. #include main() { int ctr; ctr=1; while(ctr<=5) { cout<<“ \n”<
What is wrong in the program? Example: This program will print out the number from 1-5. #include main() { int ctr; ctr=1; while(ctr<=5) { cout<<“ \n”<
Do-while loops
Syntax:
do{ Statement1; Statement2; Statementn; }while(condition);
Example: This program will print out all even nos. from 1-10. #include main() { int ctr; ctr=1; do{ cout<<“ \n”<
What do this program display? Example: This program will print out all even nos. from 1-10. #include main() { int ctr; ctr=1; do{ ++ctr; cout<<“ \n”<
While vs. Do-while What
makes differ?
Example: This program will print out the number from 1-5. #include main() { int ctr; ctr=0; do{ ++ctr; cout<<“ \n”<
Example: This program will print out the number from 1-5. #include main() { int ctr; ctr=1; while(ctr<=5) { cout<<“ \n”<
For loops Syntax: for(initialization; condition; statement)
{ statement1; statement2; statementn; }
A program that will print all even numbers -from 0 – 10. #include main() { int ctr; for(ctr=0;ctr<=10;ctr+=2) { cout<
Solution… #include 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