While loop is used in a program to do the work which contains repetition. For eg: If you have to print the numbers from 1-100 then it will be harder to write the code for printing the statement 100 times. In that type of case we use loops and one of the loop is while loop.
Syntax: while(expression){
Statement 1; // Repeated Action
Statement 2;
:
Statement n;
}
Working:
- First the compiler check whether the condition / expression is correct or not.
- If not then it will move to the very next line where the while loop is closed.
Example 1 - If the condition is true then the compiler moves inside the loop.
- It will execute each and every statement inside the loop and at the end the compiler will again move to the condition of while loop.
Example 2 - Break statement or Update statement should be used inside the loop to make the given condition false at one moment, if not the loop becomes infinite.
Some examples of "while loop"
- To print 10 times "Program".(Exit statement is Update statement)
Example 3
- To print "Code" if n > 10 or print "Dong" if n<10.(Exit statement is break statement)
Example 4
So the OUTPUT is - DONG
Things To Remember
- If the condition is false then while loop doesn't execute itself and jumps to very next statement after it.
- Condition is compulsory in the case of while loop, you can't leave it.
- If no exit condition is written inside the loop then the loop becomes Infinite loop.
- Exit condition can be written in the form of "Update Statement" or "Break Statement".
Check out our different post to get more concept.
For giving some suggestion please check our "Contact us" page. Also more update related to coding will be added in this Blog later on, so please get attached with this Blog. Thank you for your support and time...
0 Comments