×

Advanced Coding & Software Engineering Program

Duration: 1 Year (12 Months)

Join our premium 1-year program to master cutting-edge technologies and become an industry-ready Software Engineer!

Course Coverage

  • Languages: C, C++, Java, JavaScript, Python
  • Web Technologies: HTML, CSS, Bootstrap 5, MERN Stack, Full Stack Development
  • Databases: MySQL, MongoDB
  • Data Science Libraries: Pandas, NumPy
  • Development Tools: Visual Studio Code, IntelliJ IDEA, PyCharm, Postman, Git, GitHub
  • Cloud Platforms: Vercel, MongoDB Atlas

Program Highlights

  • Live Classes: Interactive sessions with real-time doubt resolution
  • Hands-On Sessions: Practical coding exercises to build real-world skills
  • Industry Experts: Learn from professionals with years of experience
  • Live Project: Work on real-world projects to apply your skills
  • Get Certificate: Earn a professional certificate upon program completion

Course Fee: Only ₹1020 / month
Limited Period Offer!

Loop Statements in C: From Basics to Advanced



Last Updated on: 11th Jul 2025 12:50:05 PM

Loops in C are like the heartbeat of repetitive tasks, allowing your program to execute code multiple times based on conditions. Whether you're printing numbers, processing data, or building games, loops are essential. In this tutorial, we'll explore the for, while, and do-while loops, with examples ranging from beginner-friendly to advanced. We'll also compare the three loops to clarify their differences. Each example includes code, output, and a detailed explanation to make learning fun and clear. Let’s dive in!

 

1. The for Loop

The for loop is perfect when you know the number of iterations in advance. It’s like setting a timer for a specific number of repetitions.

 

Syntax:

for (initialization; condition; update) {
    // Code to repeat
}

 

Basic Example: Print Squares of Numbers

This example prints the squares of numbers from 1 to 5.

#include <stdio.h>
int main() {
    for (int i = 1; i <= 5; i++) {
        printf("Square of %d is %d\n", i, i * i);
    }
    return 0;
}

 

Output:

Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25

 

Explanation: The for loop initializes i to 1, checks if i <= 5, and increments i after each iteration. It calculates and prints the square of i each time.

 

Advanced Example: Prime Number Generator

This program finds and prints all prime numbers up to a user-specified limit.

#include <stdio.h>
int main() {
    int limit, isPrime;
    printf("Enter a number to find primes up to: ");
    scanf("%d", &limit);
    
    for (int num = 2; num <= limit; num++) {
        isPrime = 1; // Assume num is prime
        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                isPrime = 0; // Not prime
                break;
            }
        }
        if (isPrime) {
            printf("%d is a prime number.\n", num);
        }
    }
    return 0;
}

 

Output (if user enters 20):

Enter a number to find primes up to: 20
2 is a prime number.
3 is a prime number.
5 is a prime number.
7 is a prime number.
11 is a prime number.
13 is a prime number.
17 is a prime number.
19 is a prime number.

 

Explanation: The outer for loop iterates from 2 to limit. For each number, an inner for loop checks divisibility up to the square root of the number (an efficient optimization). If no divisors are found (isPrime remains 1), the number is prime and printed. The break statement exits the inner loop early if a divisor is found.

 

2. The while Loop

The while loop continues as long as a condition is true. It’s ideal when the number of iterations isn’t known upfront, like waiting for valid user input.

 

Syntax:

while (condition) {
    // Code to repeat
}

 

Basic Example: Sum of Digits

This example calculates the sum of digits in a number.

#include <stdio.h>
int main() {
    int num = 1234, sum = 0;
    while (num > 0) {
        sum += num % 10; // Get last digit
        num /= 10; // Remove last digit
    }
    printf("Sum of digits: %d\n", sum);
    return 0;
}

 

Output:

Sum of digits: 10

 

Explanation: The while loop continues as long as num > 0. In each iteration, it extracts the last digit (num % 10), adds it to sum, and removes the digit by dividing num by 10.

 

Advanced Example: Fibonacci Sequence with Limit

This program generates Fibonacci numbers until they exceed a user-specified limit.

#include <stdio.h>
int main() {
    long long limit, a = 0, b = 1, next;
    printf("Enter upper limit for Fibonacci sequence: ");
    scanf("%lld", &limit);
    
    printf("Fibonacci numbers up to %lld: %lld, %lld", limit, a, b);
    while ((next = a + b) <= limit) {
        printf(", %lld", next);
        a = b;
        b = next;
    }
    printf("\n");
    return 0;
}

 

Output (if user enters 100):

Enter upper limit for Fibonacci sequence: 100
Fibonacci numbers up to 100: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89

 

Explanation: The while loop generates the next Fibonacci number (a + b) and checks if it’s within the limit. If true, it prints the number and updates a and b for the next iteration. The use of long long handles larger numbers. The loop stops when the next number exceeds the limit.

 

3. The do-while Loop

The do-while loop executes at least once, then continues if the condition is true. It’s great for scenarios requiring at least one iteration, like menus or input validation.

Syntax:

do {
    // Code to repeat
} while (condition);

 

Basic Example: Validate Positive Input

This example ensures the user enters a positive number.

#include <stdio.h>
int main() {
    int num;
    do {
        printf("Enter a positive number: ");
        scanf("%d", &num);
    } while (num <= 0);
    printf("You entered: %d\n", num);
    return 0;
}

 

Output (if user enters -3, then 7):

Enter a positive number: -3
Enter a positive number: 7
You entered: 7

 

Explanation: The do block runs at least once, prompting for input. The while (num <= 0) condition checks if the input is non-positive, looping until a positive number is entered.

 

Advanced Example: Menu-Driven Unit Converter

This program offers a menu to convert between Celsius and Fahrenheit, looping until the user exits.

#include <stdio.h>
int main() {
    int choice;
    float temp, result;
    do {
        printf("\nUnit Converter Menu:\n");
        printf("1. Celsius to Fahrenheit\n");
        printf("2. Fahrenheit to Celsius\n");
        printf("3. Exit\n");
        printf("Enter your choice (1-3): ");
        scanf("%d", &choice);
        
        if (choice == 1) {
            printf("Enter temperature in Celsius: ");
            scanf("%f", &temp);
            result = (temp * 9.0 / 5.0) + 32;
            printf("%.2f°C = %.2f°F\n", temp, result);
        } else if (choice == 2) {
            printf("Enter temperature in Fahrenheit: ");
            scanf("%f", &temp);
            result = (temp - 32) * 5.0 / 9.0;
            printf("%.2f°F = %.2f°C\n", temp, result);
        } else if (choice != 3) {
            printf("Invalid choice. Try again.\n");
        }
    } while (choice != 3);
    printf("Thank you for using the converter!\n");
    return 0;
}

 

Output (example interaction):

Unit Converter Menu:
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
3. Exit
Enter your choice (1-3): 1
Enter temperature in Celsius: 25
25.00°C = 77.00°F

Unit Converter Menu:
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
3. Exit
Enter your choice (1-3): 2
Enter temperature in Fahrenheit: 77
77.00°F = 25.00°C

Unit Converter Menu:
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
3. Exit
Enter your choice (1-3): 3
Thank you for using the converter!

 

Explanation: The do-while loop displays a menu and processes the user’s choice. It handles conversions for Celsius to Fahrenheit (temp * 9.0 / 5.0 + 32) or Fahrenheit to Celsius ((temp - 32) * 5.0 / 9.0). If the choice is invalid, it prompts again. The loop exits when the user selects 3. The %.2f format ensures two decimal places in output.

 

Main Difference Between for, while, and do...while Loops

 

Loop Type Entry/Exit Condition Checked        Runs at Least Once? When to Use
for loop Entry Before loop body ×  No When you know exact number of iterations
while loop Entry Before loop body × No When you don't know how many times, but want to repeat while a condition is true
do...while Exit After loop body  Yes When you want the loop to run at least once, even if the condition is false

 

When to Use Which Loop 

 

Scenario Recommended Loop
    You need to run a block N times (e.g., print 1 to 100) for loop
    Keep running as long as the user enters valid input while loop
    Run at least once, then check condition (e.g., menu-based programs) do...while loop
    Reading from a file until EOF (end of file) while loop
    Menu/Retry system that should run at least once do...while loop

 

Summary

  • for: Use when iteration count is known.

  •  while: Use when loop depends on a condition that may become false.

  •  do...while: Use when the loop must execute at least once.

 


Online - Chat Now
Let’s Connect

Inquiry Sent!

Your message has been successfully sent. We'll get back to you soon!

iKeySkills Logo