C language

C Language Loops Tutorial – For, While, Do-While with 30+ Examples & Exercises

C Language Loops – Part 1

In programming, loops are structures that allow a block of code to execute repeatedly until a certain condition is met. Loops are crucial for automating repetitive tasks, reducing code duplication, and improving efficiency.

In C programming, there are three primary types of loops:

  • for loop
  • while loop
  • do-while loop

Each loop type has its own syntax, use cases, and advantages.

✅ The for Loop

The for loop is commonly used when the number of iterations is known before entering the loop.

Syntax:


for(initialization; condition; increment/decrement) {
    // statements to execute
}
  

Explanation:

  • Initialization: Sets a loop counter variable before the loop starts.
  • Condition: Checked before each iteration. If true, the loop continues; if false, it stops.
  • Increment/Decrement: Updates the loop counter after each iteration.

Example 1: Printing numbers from 1 to 10


#include <stdio.h>

int main() {
    int i;
    for(i = 1; i <= 10; i++) {
        printf("%d ", i);
    }
    return 0;
}
  

Output: 1 2 3 4 5 6 7 8 9 10

Explanation:

  • i starts at 1
  • Condition i <= 10 ensures the loop runs until 10
  • i++ increases the counter by 1 each time

Example 2: Sum of first N natural numbers


#include <stdio.h>

int main() {
    int n, sum = 0;
    printf("Enter a number: ");
    scanf("%d", &n);

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

    printf("Sum of first %d natural numbers is %d", n, sum);
    return 0;
}
  

✅ The while Loop

The while loop executes a block of code as long as a specified condition remains true. It is used when the number of iterations is not known in advance.

Syntax:


while(condition) {
    // statements to execute
}
  

Example 3: Print numbers 1 to 5 using while loop


#include <stdio.h>

int main() {
    int i = 1;
    while(i <= 5) {
        printf("%d ", i);
        i++;
    }
    return 0;
}
  

✅ The do-while Loop

The do-while loop executes a block of code at least once and then repeats it as long as the condition is true.

Syntax:


do {
    // statements to execute
} while(condition);
  

Example 4: Print numbers 1 to 5 using do-while loop


#include <stdio.h>

int main() {
    int i = 1;
    do {
        printf("%d ", i);
        i++;
    } while(i <= 5);
    return 0;
}
  

C Language Loops – Part 2

✅ Nested Loops

Sometimes you need a loop inside another loop. This is called a nested loop. Nested loops are often used for multi-dimensional data, like matrices or tables, and for printing patterns.

Syntax:


for(initialization; condition; increment) {
    for(inner_initialization; inner_condition; inner_increment) {
        // inner loop statements
    }
    // outer loop statements
}
  

Example 1: Print a 5×5 star pattern


#include <stdio.h>

int main() {
    int i, j;
    for(i = 1; i <= 5; i++) {
        for(j = 1; j <= 5; j++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}
  

Output:


* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
  

Explanation: The outer loop runs 5 times for rows, and the inner loop runs 5 times for columns.

✅ Using break and continue

The break statement is used to exit a loop prematurely, while continue skips the current iteration and moves to the next one.

Example 2: Using break


#include <stdio.h>

int main() {
    int i;
    for(i = 1; i <= 10; i++) {
        if(i == 6) {
            break; // exit loop when i is 6
        }
        printf("%d ", i);
    }
    return 0;
}
  

Output: 1 2 3 4 5

Example 3: Using continue


#include <stdio.h>

int main() {
    int i;
    for(i = 1; i <= 5; i++) {
        if(i == 3) {
            continue; // skip iteration when i is 3
        }
        printf("%d ", i);
    }
    return 0;
}
  

Output: 1 2 4 5

✅ Practical Example 1: Factorial of a number

The factorial of a number n is the product of all positive integers less than or equal to n.


#include <stdio.h>

int main() {
    int n, i;
    unsigned long long fact = 1;

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

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

    printf("Factorial of %d = %llu", n, fact);
    return 0;
}
  

✅ Practical Example 2: Fibonacci Series

The Fibonacci series is a sequence where each number is the sum of the two preceding ones. Loops are used to generate this series efficiently.


#include <stdio.h>

int main() {
    int n, i;
    int t1 = 0, t2 = 1, nextTerm;

    printf("Enter the number of terms: ");
    scanf("%d", &n);

    printf("Fibonacci Series: ");

    for(i = 1; i <= n; i++) {
        printf("%d ", t1);
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
    }

    return 0;
}
  

✅ Practical Example 3: Multiplication Table


#include <stdio.h>

int main() {
    int n, i;
    printf("Enter a number: ");
    scanf("%d", &n);

    printf("Multiplication Table of %d:\n", n);

    for(i = 1; i <= 10; i++) {
        printf("%d x %d = %d\n", n, i, n*i);
    }

    return 0;
}
  

✅ Tips for Using Loops Efficiently

  • Avoid infinite loops by ensuring the condition eventually becomes false.
  • Use break and continue wisely to control loop flow.
  • Nested loops can increase time complexity, so optimize when possible.
  • Use descriptive loop variables for readability.

C Language Loops – Part 3

✅ Advanced Example 1: Printing Number Patterns

Loops are widely used to create patterns. Here’s an example of printing a right-angled triangle of numbers:


#include <stdio.h>

int main() {
    int i, j, n = 5;

    for(i = 1; i <= n; i++) {
        for(j = 1; j <= i; j++) {
            printf("%d ", j);
        }
        printf("\n");
    }
    return 0;
}
  

Output:


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
  

✅ Advanced Example 2: Inverted Triangle Pattern


#include <stdio.h>

int main() {
    int i, j, n = 5;

    for(i = n; i >= 1; i--) {
        for(j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}
  

Output:


* * * * *
* * * *
* * *
* *
*
  

✅ Example 3: Prime Number Detection

Loops can efficiently check if a number is prime.


#include <stdio.h>

int main() {
    int n, i, isPrime = 1;

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

    if(n < 2) {
        isPrime = 0;
    } else {
        for(i = 2; i <= n/2; i++) {
            if(n % i == 0) {
                isPrime = 0;
                break;
            }
        }
    }

    if(isPrime)
        printf("%d is a prime number.", n);
    else
        printf("%d is not a prime number.", n);

    return 0;
}
  

✅ Example 4: Iterating Through Arrays

Loops are commonly used to process array elements.


#include <stdio.h>

int main() {
    int arr[] = {2, 4, 6, 8, 10};
    int n = sizeof(arr)/sizeof(arr[0]);

    printf("Array elements: ");
    for(int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}
  

✅ Example 5: Sum and Average of Array Elements


#include <stdio.h>

int main() {
    int arr[] = {5, 10, 15, 20, 25};
    int n = sizeof(arr)/sizeof(arr[0]);
    int sum = 0;
    float avg;

    for(int i = 0; i < n; i++) {
        sum += arr[i];
    }

    avg = (float)sum/n;

    printf("Sum = %d\n", sum);
    printf("Average = %.2f\n", avg);

    return 0;
}
  

✅ Example 6: Nested Loops for Multiplication Table

Using loops to print multiplication tables for numbers 1 to 5.


#include <stdio.h>

int main() {
    int i, j;

    for(i = 1; i <= 5; i++) {
        printf("Multiplication Table of %d:\n", i);
        for(j = 1; j <= 10; j++) {
            printf("%d x %d = %d\n", i, j, i*j);
        }
        printf("\n");
    }

    return 0;
}
  

✅ Real-World Applications of Loops

  • Automating repetitive tasks like printing reports.
  • Processing data arrays, strings, and matrices.
  • Generating patterns and user interface elements in console apps.
  • Performing calculations like factorial, Fibonacci series, prime checking.
  • Reading input until a specific condition is met, e.g., password verification or menu options.

✅ Best Practices for C Loops

  • Always ensure loop termination to avoid infinite loops.
  • Use meaningful variable names like i, j, row, col for nested loops.
  • Keep loops simple and avoid unnecessary nesting to maintain readability.
  • Optimize loop logic when dealing with large datasets.
  • Use break and continue carefully to control flow effectively.

By mastering loops in C, programmers can write efficient, readable, and reusable code. Loops form the backbone of many algorithms and applications, making them essential for every C developer.

 

✅ C Loops Exercise Questions

Test your understanding of C loops with these exercises. Try solving them without looking at the solutions first!

  1. Write a for loop to print all even numbers from 1 to 50.
  2. Write a while loop that takes a number input from the user and prints all numbers from that number down to 1.
  3. Using a do-while loop, ask the user to enter a positive number. Keep prompting until they enter a number greater than 0.
  4. Write a program using a for loop to calculate the sum of all odd numbers from 1 to 100.
  5. Write a program to print the following pattern using nested loops (triangle of stars):
    
    *
    * *
    * * *
    * * * *
    * * * * *
          
  6. Write a program using loops to find the factorial of a number entered by the user.
  7. Write a program to print the Fibonacci series up to n terms using a loop. (Take n as input from the user)
  8. Write a program using loops to check whether a number entered by the user is prime or not.
  9. Write a program to take 5 integers from the user, store them in an array, and calculate the sum and average using a loop.
  10. Using nested loops, print the multiplication tables from 1 to 5.

💡 Tip: Try solving each exercise first on paper, then implement in C. Experiment with for, while, and do-while loops to understand their behavior.

Leave a Reply

Your email address will not be published. Required fields are marked *