Answer to Question #295641 in C for Nil

Question #295641

When will the ‘while’ loop be preferred over the for loop? Mention the scenario and write the


programme to demonstrate this.



1
Expert's answer
2022-02-09T13:08:14-0500

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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS