Loops in C

In this tutorial, you will learn about loops in C, which repeat a block of code based on a condition. Loops improve efficiency and reduce redundancy. C includes three types: for, while, and do-while. Use for when you know the number of iterations. The while loop runs while a condition is true. The do-while loop always executes at least once. Let’s explore each one.

Contents:

  1. What are Loops in C?
  2. Types of Loops in C
  3. for Loop in C
  4. Variations of for Loop in C
  5. while Loop in C
  6. do-while Loop in C
  7. Nested Loops in C
  8. Difference between for Loop and while Loop in C
  9. Loop Control Statements in C
  10. Best Practices for Using Loops in C
  11. FAQs on Loops in C

What are Loops in C?

Loops in C are control structures that allow the execution of a block of code multiple times based on a condition. They help reduce code repetition and improve efficiency.

Syntax of a Loop

loop_type (initialization; condition; increment/decrement) {
    // Code to be executed
}

advertisement

Types of Loops in C

Loops in C allow executing a block of code multiple times based on a condition. There are three types of loops in C:

  • for Loop – Used when the number of iterations is known.
  • while Loop – Used when the number of iterations is unknown but depends on a condition.
  • do-while Loop – Similar to the while loop but executes at least once.

for Loop in C

The for loop in C is a control structure that allows a block of code to execute multiple times based on a condition. It is mainly used when the number of iterations is known beforehand.

Syntax:

Free 30-Day Java Certification Bootcamp is Live. Join Now!
for(initialization; condition; increment/decrement) {
    // Code to execute
}

Example:

#include <stdio.h>
 
int main()
{
    int scores[] = {85, 90, 78, 92, 88};
 
    printf("Sanfoundry Quiz Scores:\n");
 
    for(int i = 0; i < 5; i++) {
        printf("Participant %d: %d\n", i + 1, scores[i]);
    }
 
    return 0;
}

Output:

Sanfoundry Quiz Scores:
Participant 1: 85
Participant 2: 90
Participant 3: 78
Participant 4: 92
Participant 5: 88

This C program shows quiz scores for five participants. It first creates an array called scores with five numbers. Then, it prints a heading: “Sanfoundry Quiz Scores:”. A for loop runs five times to display each participant’s number and score. The program ends with return 0;, which means it ran successfully. This makes it easy to show scores using a loop.

Variations of for Loop in C

1. for Loop Without Initialization

#include <stdio.h>
 
int main() {
    int i = 1;
    for (; i <= 3; i++) {
        printf("Sanfoundry Test %d\n", i);
    }
    return 0;
}

Output:

advertisement
Sanfoundry Test 1  
Sanfoundry Test 2  
Sanfoundry Test 3

2. for Loop Without Condition (Infinite Loop)

#include <stdio.h>
 
int main()
{
    for (int i = 1;; i++) {  // No condition
        printf("Infinite Loop %d\n", i);
        if (i == 3) break;  // Stopping condition inside loop
    }
    return 0;
}

Output:

Infinite Loop 1  
Infinite Loop 2  
Infinite Loop 3

3. for Loop with Multiple Variables

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

Output:

i = 1, j = 5  
i = 2, j = 4  
i = 3, j = 3

These variations of for loops allow flexibility in writing different types of iterations in C.

while Loop in C

The while loop in C is a control structure that executes a block of code repeatedly as long as a specified condition remains true. It is useful when the number of iterations is not known beforehand.

Syntax of while Loop

while(condition) {
    // Code to execute
}

Example:

#include <stdio.h>
 
int main()
{
    int count = 1;
 
    while (count <= 5)
    {
        printf("Sanfoundry Quiz Question %d\n", count);
        count++;  // Increment count
    }
 
    return 0;
}

Output:

Sanfoundry Quiz Question 1  
Sanfoundry Quiz Question 2  
Sanfoundry Quiz Question 3  
Sanfoundry Quiz Question 4  
Sanfoundry Quiz Question 5

This C program prints quiz questions using a while loop. It starts by setting count to 1. The loop runs as long as count is 5 or less. Inside the loop, it prints “Sanfoundry Quiz Question” followed by the question number. After each print, count increases by 1. When count reaches 6, the loop stops. The program ends with return 0;, meaning it ran successfully. This method ensures questions are printed in order using a loop.

do-while Loop in C

The do-while loop in C is an exit-controlled loop that executes the loop body at least once, regardless of the condition. The condition is checked after the execution of the loop body.

Syntax:

do {
    // Loop body
} while (condition);

Example:

#include <stdio.h>
 
int main()
{
    int count = 1;
 
    do {
        printf("Sanfoundry Quiz Attempt %d\n", count);
        count++;  // Increment count
    } while (count <= 3);
 
    return 0;
}

Output:

Sanfoundry Quiz Attempt 1  
Sanfoundry Quiz Attempt 2  
Sanfoundry Quiz Attempt 3

This C program prints quiz attempts using a do-while loop. It starts with count set to 1. The loop runs at least once, printing “Sanfoundry Quiz Attempt” followed by the attempt number. After printing, count increases by 1. The loop continues while count is 3 or less. When count reaches 4, the loop stops. The program ends with return 0;, meaning it ran successfully. This approach ensures the message prints at least once, even if the condition is false initially.

Nested Loops in C

A nested loop is a loop inside another loop. In C, any loop (for, while, or do-while) can be nested within another loop.

Syntax:

for(initialization; condition; update) {  
    for(initialization; condition; update) {  
        // Inner loop body
    }  
    // Outer loop body
}

1. Nested for Loop in C

A for loop inside another for loop.

#include <stdio.h>
 
int main() {
    int i, j;
 
    for(i = 1; i <= 3; i++) {  // Outer loop
        for(j = 1; j <= 3; j++) {  // Inner loop
            printf("%d x %d = %d\n", i, j, i * j);
        }
        printf("\n");
    }
 
    return 0;
}

Output:

1 x 1 = 1  
1 x 2 = 2  
1 x 3 = 3  
 
2 x 1 = 2  
2 x 2 = 4  
2 x 3 = 6  
 
3 x 1 = 3  
3 x 2 = 6  
3 x 3 = 9

2. Nested while Loops in C

A while loop inside another while loop.

Example: (Printing a Number Pyramid)

#include <stdio.h>
 
int main() {
    int i = 1, j;
 
    while(i <= 3) {  // Outer loop
        j = 1;
        while(j <= i) {  // Inner loop
            printf("%d ", j);
            j++;
        }
        printf("\n");
        i++;
    }
 
    return 0;
}

Output:

1  
1 2  
1 2 3

3. Nested do-while Loops in C

A do-while loop inside another do-while loop.

Example: (Displaying a Simple Grid)

#include <stdio.h>
 
int main() {
    int i = 1, j;
 
    do {
        j = 1;
        do {
            printf("(%d,%d) ", i, j);
            j++;
        } while(j <= 3);
 
        printf("\n");
        i++;
    } while(i <= 3);
 
    return 0;
}

Output:

(1,1) (1,2) (1,3)  
(2,1) (2,2) (2,3)  
(3,1) (3,2) (3,3)

Difference between for Loop and while Loop in C

Here is a comparison table highlighting the differences between for and while loops in C:

Feature for Loop while Loop
Usage Used when the number of iterations is known beforehand. Used when the number of iterations is not known beforehand.
Syntax for(initialization; condition; update) { … } while(condition) { … }
Initialization Done inside the loop header. Done before entering the loop.
Condition Checked before each iteration. Checked before each iteration.
Updation Done inside the loop header. Done inside the loop body (manually).
Readability More compact and suitable for counting loops. More flexible but can be less readable in some cases.
Best Used For When a loop runs a fixed number of times. When a loop runs based on a condition without a fixed number of iterations.
Example for(int i = 0; i < 5; i++) { printf("%d ", i); } int i = 0; while(i < 5) { printf("%d ", i); i++; }
Execution Flow Initialization → Condition Check → Execution → Update → Repeat Condition Check → Execution → Update (if applicable) → Repeat

Loop Control Statements in C

Loop control statements are used to alter the normal flow of loops. These statements help to break, skip, or exit loops based on specific conditions.

1. break Statement in C

The break statement is used to terminate a loop prematurely when a specific condition is met.

Example: (Stopping Loop at 5)

#include <stdio.h>
 
int main() {
    for(int i = 1; i <= 10; i++) {
        if(i == 5) {
            break; // Exit loop when i reaches 5
        }
        printf("%d ", i);
    }
    return 0;
}

Output:

1 2 3 4

This C program prints numbers from 1 to 10 but stops at 5 using break. A for loop starts from 1 and increases. When i reaches 5, the loop ends early. The program finishes with return 0;, meaning it ran successfully. This helps exit loops when needed.

2. continue Statement in C

The continue statement is used to skip the current iteration and proceed to the next iteration of the loop.

Example: (Skipping 5)

#include <stdio.h>
 
int main() {
    for(int i = 1; i <= 10; i++) {
        if(i == 5) {
            continue; // Skip 5 and move to the next iteration
        }
        printf("%d ", i);
    }
    return 0;
}

Output:

1 2 3 4 6 7 8 9 10

This C program prints numbers from 1 to 10 but skips 5 using continue. A for loop starts from 1 and increases. When i is 5, continue skips that iteration and moves to the next number. The program ends with return 0;, meaning it ran successfully. This method helps skip specific values in a loop.

3. goto Statement in C

The goto statement is used to jump to a labeled statement anywhere in the program.

Example: (Jumping to Label)

#include <stdio.h>
 
int main() {
    int i = 1;
 
    loop:  
        if(i > 5) {
            return 0;
        }
        printf("%d ", i);
        i++;
        goto loop; // Jump back to label
 
    return 0;
}

Output:

1 2 3 4 5

This C program prints numbers from 1 to 5 using goto. It starts with i = 1 and a label loop. The program checks if i is greater than 5; if so, it stops. Otherwise, it prints i, increases it, and jumps back to loop. The program ends with return 0;, ensuring successful execution. This method demonstrates using goto for looping, though loops like for or while are preferred.

Best Practices for Using Loops in C

Using loops efficiently ensures better performance, readability, and maintainability in C programs. Here are some best practices:

  1. Use the appropriate loop type
    • Use a for loop when the number of iterations is known.
    • Use a while loop when the number of iterations is uncertain.
    • Use a do-while loop when at least one iteration is required.
  2. Avoid infinite loops: Ensure the loop has a proper exit condition to prevent infinite execution.
    while(1) { // No exit condition
        printf("This will run forever!");
    }
  3. Minimize unnecessary computations inside loops: Perform constant calculations outside the loop to improve efficiency.
    int n = 10;
    int square = n * n; // Move outside the loop if it doesn't change
  4. Use break and continue wisely: Overuse of break and continue can make loops hard to read and debug.
    for(int i = 0; i < 10; i++) {
        if(i % 2 == 0) continue;
        printf("%d ", i);
    }
  5. Use loop counters effectively: Avoid modifying loop variables inside the loop unexpectedly.
    for(int i = 0; i < 10; i++) {
        i += 2; // Modifying loop counter incorrectly
    }
  6. Optimize nested loops: Minimize the number of nested loops to reduce time complexity.
    for(int i = 0; i < 10; i++) {
        for(int j = 0; j < 10; j++) { // Avoid deep nesting
            printf("%d %d\n", i, j);
        }
    }
  7. Prefer ++i over i++ in loops when possible: Pre-increment (++i) is slightly more efficient than post-increment (i++) because it avoids extra temporary storage.
    for(int i = 0; i < 10; ++i) { // Better than i++
        printf("%d ", i);
    }

FAQs on Loops in C

1. What are loops in C?
Loops in C are control structures that repeatedly execute a block of code until a specified condition is met.

2. What are the different types of loops in C?
C provides three types of loops: for loop, while loop, and do-while loop.

3. What is the purpose of a while loop?
A while loop is used when the number of iterations is unknown and depends on a condition that is evaluated before each iteration.

4. How is a do-while loop different from a while loop?
A do-while loop ensures that the loop body executes at least once before checking the condition, unlike a while loop that checks the condition first.

5. What is a nested loop?
A nested loop occurs when one loop runs inside another, commonly used for multi-dimensional data processing.

6. How can infinite loops be prevented?
Infinite loops can be avoided by ensuring a proper exit condition and updating loop control variables correctly.

7. What are some best practices for using loops in C?
Use the appropriate loop type, keep conditions simple, avoid unnecessary computations inside loops, and prevent excessive nesting for better readability.

8. How does a for loop differ from a while loop?
A for loop is best for a known number of iterations, while a while loop is better for cases where the loop should continue until a condition changes dynamically.

Key Points to Remember

Here is the list of key points we need to remember about “Loops in C”.

  • Loops in C allow repeated execution of code blocks based on a condition, improving efficiency and reducing redundancy.
  • The three types of loops in C are for, while, and do-while, each serving different use cases based on iteration needs.
  • The for loop is best when the number of iterations is known, while the while loop is ideal for unknown iteration counts.
  • The do-while loop ensures at least one execution before checking the condition, unlike the while loop.
  • Nested loops allow loops inside other loops, useful for handling multidimensional data and complex iterations.
  • Loop control statements like break, continue, and goto alter normal loop execution by stopping, skipping, or jumping.
  • Infinite loops occur when an exit condition is missing, which can cause unintended program hangs or crashes.
  • Best practices include choosing the right loop, avoiding deep nesting, optimizing calculations, and using efficient increments.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.