Loop statements | do-while | while | for | #Tut-05
In this tutorial we are going to cover the types of loops..
What is loop..?
In the program so many times we come across the situation where we want to execute some part of the program again and again for some particular number of times. In such situations we make use of loop statements.
When we want to repeat some part of procedure for some particular number of times then we make use of loops..
In this language there are three types loops
1. do-while
2. while
3. for
Basic syntax for the working of any loop..?
While Loop..
- while statement is one of the frequently used loop statement in programming. The while statement tells the compiler to repeat the series of statements as long as the certain condition is true. As soon as the certain condition becomes false computer stops repeating and goes to the next statement.
syntax :
{
//body
}
- in this loop condition is given at the top of loop
- In while loop first the condition is checked, if the condition is true then and then only our control goes inside the while loop and then the pointer is incremented by one and again condition is get checked. So in this way till our condition is true loop will keep runing..
Program :
Output :
Do - While loop..
Do - while loop is executed at least once, it is said because here loop statements are executed first and then the condition is checked. Now if we run our loop with a false condition then whatever statements present in the loop are executed first and then the condition is checked.
So the condition is given at the bottom of loop.
Syntax :
Code Snippet :
output :
Now let us see the basic difference between while loop and do-while loop..!
For Loop..
For loop.. |
The for loop consist of three actions
- initialization
- condition
- increment/decrement
Each action should be separated by the semicolon(;).
Why use for loop..?
- The for loop is used to iterate the statements or a part of program several times.
- It is used to traverse the data structures like an array, linked list etc.
- It has little different syntax than while and do-while loop which help to reduce the line of codes in out program.
- The break statement is used when we want to break the cycle of execution after satisfying the certain condition.
- This statement breaks the further operation of loop and stops the process of execution and comes out of the loop.
- If break statement is inside a nested loop then it breaks the inner loop in which it is contained. The break statement is used with while, do-while and for loop.
- The continue statement is used when execution of further statements in the loop is to be skipped.
- This statement bypass the execution of next statement and transfers control to the start of the loop for further execution of loop.
- This statement should be used only within a loop.
Comments
Post a Comment