Mastery 22

When to use what type of repetition in a program

A repetition statement (or the looping statements or loops) enables the program to repeat an action as long as a particular set condition remains true. Its form goes as follow, “As long as you are at school, I will continue to pay your allowances”. This means that the action of paying you allowances will be done over and over again on condition that you go to school, but if you finish or drop out of school, you will have to fend for yourself. There are three types of repetition (loop) statements. They include the while,do.....while and for loop statements

while Repetition Statements

The while loop statements allows the program to perform a particular action while a set condition is true. In the case of our going to school example, the while statement can be stated as “while you go to school, I will pay your allowances”. Now this statement gives you the ability to determine how much you will earn while you go to school.
 

do..while statement

The do....while loop allows for executing an action at least before a condition is tested. To enable the loop automatically execute its statement at least once, the while condition is put at the end instead of the beginning. The loop executes its body before the condition is tested. So whether condition is true or false, the loop will execute at least once. 
 

for loop statement

The for loop is another form of repetition statements in C++. The for loop provides for the beginning of the condition, the limit of the condition and updates after every execution. The for loop takes the following form; for ( starting point; limiting condition; update ) { Code to execute while the condition is true }
The stating point can include an initialized control variable either declared internally or using an already existing variable. Any expression however that evaluates to a value can also be used. 
 
Credit:

1017 22

CC BY 4.0 Mastery 22 by Mauricio Cooper is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.