When will the ‘while’ loop be preferred over the for loop? Mention the scenario and write the
programme to demonstrate this.
The while loop is used when the number of iterations is not known in advance, while the for loop is used to iterate a known number of elements. An example is the processing of data before the occurrence of some predetermined event. For example, counting the sum of numbers entered by the user as long as the sum remains less than 1000.
#include <stdio.h>
int main() {
int sum = 0;
int n = 0;
int x;
while (sum < 1000) {
printf("Enter a number: ");
scanf("%d", &x);
sum += x;
n++;
}
printf("The sum of %d numbers is %d\n", n, sum);
return 0;
}
Comments
Leave a comment