Hey Grade 12 Students, your exams are near so work hard.

Difference between for loop and while loop in C. | NEB Board Exam Class 12

Major Difference

for loop while loop
for (initialization; condition; increment/decrement) { statement(s); } while (condition) { statement(s); }
Initialization and increment/decrement expressions are specified within the loop header Initialization and increment/decrement need to be done manually
Typically used when you know the number of iterations in advance Used when you don't know the number of iterations in advance
The loop control variable is scoped to the loop body and header The loop control variable is scoped to the surrounding block
Can create infinite loops using for (;;) Can create infinite loops using while (1) or while (true)

Example:

For Loop

#include <stdio.h>

int main() {
    int n, factorial = 1;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        factorial *= i;
    }

    printf("Factorial of %d is %d\n", n, factorial);

    return 0;
}

While Loop

#include <stdio.h>

int main() {
    int n, sum = 0;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }

    printf("Sum of digits of %d is %d\n", n, sum);

    return 0;
}

Getting Info...

About the Author

A free online educational resource provider.

Post a Comment

Please do not enter any spam link in the comment box.
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.