When while loop is use ?
When we do not know about how many times loops are perform or iteration of loop is unknown
The while statement is also a looping statement. The while loop evaluates the test expression before every loop, so it can execute zero times if the condition is initially false. It has the following syntax.
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following the loop.
Example of while loop statement:
example 2: while loop This construct is also used for looping. In this case the loop condition is tested at the end of the body of the loop. Hence the loop is executed at least one. The do-while is an unpopular area of the language, most programmers’ tries to use the straight while if it is possible.Syntax of do while loop is
Here the block of statement following the do is executed without any condition check. After this expression is evaluated and if it is true the block of statement in the body of the loop is executed again. Thus the block of statement is repeatedly executed till the expression is evaluated to false.
do-while construct is not used as often as the while loops or for loops in normal case of iteration but there are situation where a loop is to be executed at least one, in such cases this construction is very useful.
Fig:example 3 of while loop
Compare between while loop and do while loop:
In many cases we may use loop statement inside another looping statement. This type of looping is called nested loop. In nested loop the inner loop is executed first and then outer. The nested loop must be used to input or output multi-dimensional array elements.
The following program illustrates the use of Nested loop.
Write a C program to enter a number from user and find first and last digit of number using loop. How to find first and last digit of a number in C.
Example: If number = 1234
First digit = 1
Last digit = 4
continue statement is a jump statement. The continue statement can be used only inside for loop, while loop and do-while loop. Execution of these statement does not cause an exit from the loop but it suspend the execution of the loop for that iteration and transfer control back to the loop for the next iteration.
The break statement is a jump instruction and can be used inside a switch construct, for loop, while loop and do-while loop. The execution of break statement causes immediate exit from the concern construct and the control is transferred to the statement following the loop. In the loop construct the execution of break statement terminates loop and further execution of the program is reserved with the statement following the body of the loop.
The following program illustrates the use of break statement.