If programmer wants to perform “specific operation” multiple times then he uses a loop. The “specific operation” should be kept inside the loop and are called “controlled statements” or “body of a loop”.
The body of a loop gets executed repeatedly until the condition becomes false or the programmer breaks the loop.
In above diagram, if the body of a loop contains a
break; statement then the loop will break.
In the above diagram if a condition is always true then control can never come outsite the loop body and we say those kind of loops as an infinite loop.
There are 5 types of loops in C++ as listed below. Click the following links to check their detail.
Types of Loops
|while loop||While a given expression is true it repeats the statement in the loop body. Before executing the loop body it tests the condition for true or false.|
|do…while loop||It is like a while loop but it tests the condition after executing the loop body.|
|for loop||In above two loops we need to write the increment or decrement operation to break the loop after sometime. But in for loop we have an option of incrementing or decrementing outside the loop body.|
|for-each loop||This loop applies a function to the range of elements in a collection.|
|nested loops||When using one or more loops inside a loop is known as nested loop.|
Loop Control Statements
Normally the statements inside the loop body executes sequentially. But by using loop control statements we can change the flow of execution of statements inside the loop body. If we are exiting the loop body then all automatic and local variables/objects which got created in loop’s scope will be destroyed.
C++ supports the three control statements as listed below. Click the following links to check their detail.
|break statement||Break terminates immediately the loop statement from executing further and execution reaches just outside the loop body containing the break statement.|
|continue statement||Continue statement is equivalent to going to the very end of the loop immediately by skipping further statements.|
|goto statement||It is equivalent to skipping the further statements and immediately jumping to the labeled statement.|
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?