The while loop construct contains only the condition. The programmer has to take care about the other elements (initialization and incrementing). The general form of the while loop is:
while (condition)
{
statement(s);
}
The loop is controlled by the logical expression that appears between the parentheses. The loop continues as long as the expression is TRUE. It will stop when the condition becomes FALSE it will stop. You need to make sure that the expression will stop at some point otherwise it will become an infinite loop. The while loop is suitable in cases where the exact number of repetitions is not known in advance. Consider the following example:
/* Program-5.4 */
#include <stdio.h>
int main()
{
int num;
printf("Enter number of times to repeat: ");
scanf("%d", &num);
while (num != 0)
{
printf("Hello World!\n");
num--;
}
return 0;
}
Execution of Program-5.4 with 5 as the input will display the following:
Enter number of times to repeat: 5
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
In Program-5.4 the number of times to loop, depends on the user input. In such cases use of while loop is desirable than the for loop. In program-5.4 variable “num” act as the counter. The conditions inside the while loop check whether the counter is not equal to zero (num != 0) if so it will execute the printf function. Next we need to make sure that the program loops only 5 times. That is achieved by decrementing the counter (num--) at each round. If the counter is not decremented the program will loop forever.
No comments:
Post a Comment