Posts

Showing posts with the label while statement example

while statement in C plus plus

Image
The while statement In some cases, the number of times the body of a loop would be executed is not known in advance, or depends only on the truth or falsity of an expression. In such cases, the for loop could not be used. Hence the while loop could be used instead. The syntax of the while loop is as follows: While (test_expression) { // block of statements } A while loop will begin by checking to see if the test_expression is true. It the test_expression is true the body of the loop will be executed, and then the test_expression will be checked again and if the test_expression is true the body of the loop will be executed again. This will continue until the value of the test_expression turns up false, and the loop body will not be executed – control will pass to the statements following the while loop. The sum example discussed in the previous section could be rewritten using while loop as follows: int sumSoFar =0; int i=0; // while (test_expression) while(I <