View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
    View All
    View All
    View All
    View All
    View All
    View All
    View All

    All About For Loop in C Programming - Syntax & Examples

    Updated on 06/05/20253,237 Views

    The for loop in C is one of the most essential control structures used for iteration. It allows programmers to execute a block of code repeatedly, with a well-defined start and end point. Whether you want to print a sequence of numbers, iterate through an array, or perform complex calculations, the for loop in C is often the best tool for the job.

    In this article, we will explore everything you need to know about the for loop in C programming. We will cover its syntax, working mechanism, and practical use cases. You will also see basic, intermediate, and advanced examples, along with detailed explanations and outputs. Besides all this, we will discuss nested and infinite for loops, common mistakes to avoid, and frequently asked questions to clear your doubts.

    You should explore our software development courses to understand programming concepts in a more efficient way. 

    What is For Loop in C Programming?

    In C programming, a for loop is a control structure used to execute a block of code repeatedly. It works best when the number of iterations is already known. The loop relies on a loop control variable that changes with each iteration until a certain condition is met.

    The for loop in C is especially useful when you want to run a block of code a fixed number of times. Unlike the while loop, which is condition-based, the for loop is ideal for count-controlled repetition. Programmers often use it for tasks like printing sequences, iterating through arrays, or performing repetitive calculations.

    Boost your career journey with the following online courses: 

    Let’s now look at the basic syntax of the for loop in C, which shows how it is structured and how each part works together.

    Syntax of For Loop in C

    Here is the standard syntax of a for loop in C:

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

    Explanation of Syntax:

    • Initialization: This step sets up the loop control variable. It is executed only once at the beginning of the loop.
    • Condition: The loop runs as long as this condition is true. If the condition becomes false, the loop stops.
    • Increment/Decrement: After each iteration, the loop control variable is updated (incremented or decremented).
    • Code Block: The statements inside the curly braces {} are executed on each loop run.

    Let’s understand the for loop in c with a simple example.

    Simple For Loop Example

    Task: We want to print numbers from 1 to 5 using a for loop.

    Before writing the code:  We will create a loop that starts with i = 1 and runs until i becomes 5. After printing each number, we will increase the value of i by 1.

    #include <stdio.h>

    int main() {
    // Loop from 1 to 5
    for (int i = 1; i <= 5; i++) {
    printf("%d\n", i); // Print the current value of i
    }
    return 0;
    }

    Output:

    1
    2
    3
    4
    5

    Explanation:

    • Initialization: int i = 1; - The loop starts with i set to 1.
    • Condition: i <= 5; - The loop continues running as long as i is less than or equal to 5.
    • Code Block: printf("%d\n", i); - This prints the current value of i on each iteration.
    • Increment: i++ - After printing, the loop increases i by 1.
    • Loop End - When i becomes 6, the condition i <= 5 fails, and the loop stops.

    Interested in learning about Do While Loop in C? If so, read the Understanding Do While Loop in C article!

    How Does the For Loop Work in C?

    The for loop in C works by repeating a set of instructions based on a specific condition. It has three main parts: initialization, condition checking, and increment or decrement. These parts work together to control the flow of the loop.

    When a for loop starts, it first sets the initial value of the loop variable. Then it checks whether the loop condition is true. If the condition is true, the code inside the loop runs. After each loop iteration, the loop variable updates. This process repeats until the condition becomes false.

    Let’s now see a simple example that shows the full working process of the for loop in C step by step.

    Before writing the code: We will write a loop that prints numbers from 1 to 3. This example will help you understand how initialization, condition checking, and increment work in each loop cycle.

    #include <stdio.h>

    int main() {
    // Start the loop with i = 1, run till i <= 3, and increment i by 1 each time
    for (int i = 1; i <= 3; i++) {
    printf("Current number: %d\n", i); // Print the current number
    }
    return 0;
    }

    Output:

    Current number: 1
    Current number: 2
    Current number: 3

    Explanation: 

    • Step 1: Initialization (int i = 1;) - The loop starts by setting i to 1. This step runs only once at the beginning.
    • Step 2: Condition Check - The condition i <= 3 is checked.
      • If true, the loop body runs.
      • If false, the loop ends.
    • Step 3: Loop Body Execution - The statement printf("Current number: %d\n", i); runs and prints the current value of i.
    • Step 4: Increment - The loop updates i using i++. This increases the value of i by 1 after each iteration.
    • Repeat - The loop goes back to Step 2 and checks the condition again. This continues until the condition becomes false.

    Flow Recap:

    Iteration

    i Value Before Loop

    Condition (i <= 3)

    Output Printed

    i After Increment

    1

    1

    True

    Current number: 1

    2

    2

    2

    True

    Current number: 2

    3

    3

    3

    True

    Current number: 3

    4

    4

    4

    False

    (No output, loop ends)

    -

    When to Use the For Loop in C?

    The for loop in C is ideal when you need to execute a block of code a specific number of times. It is preferred in situations where the number of iterations is known in advance.

    Below are the key cases where using a for loop in C programming is the best choice:

    • Fixed Repetitions: Use a for loop when you need to run a loop for a known number of times, such as printing numbers from 1 to 100.
    • Array Traversal: It is perfect for accessing each element of an array or a collection using an index.
    • Counting Loops: When you need to increment or decrement a variable systematically, the for loop makes your code clean and efficient.
    • Pattern Printing: For loops are widely used in C for printing patterns like triangles, pyramids, or grids.
    • Table Generation: You can use a for loop to generate multiplication tables quickly and easily.
    • Batch Processing: When processing a batch of items or records where the size is fixed, a for loop handles it smoothly.
    • Running Timed Operations: It’s useful when running a task a set number of times, such as performing a test 10 times to check consistency.
    • Iterating Over Ranges: A for loop works well when looping over a numerical range with a specific start and end point.
    • Nested Loops: For loops are commonly used in nested structures, especially in matrix-related operations.

    Must Explore: Python’s do-while Loop

    For Loop in C Examples

    Let’s now explore practical examples of the for loop in C, divided into basic, intermediate, and advanced levels. Each example will help you understand how the for loop works in different scenarios, from simple counting to more complex logic.

    Basic Level Example: Print the Multiplication Table of 2

    In this example, we will print the multiplication table of 2 up to 10 using a simple for loop. This helps beginners understand how to work with loops that involve calculations.

    Before writing the code: We will run a loop from 1 to 10. In each iteration, we will multiply 2 by the current number and print the result.

    #include <stdio.h>

    int main() {
    // Loop to print the multiplication table of 2
    for (int i = 1; i <= 10; i++) {
    printf("2 x %d = %d\n", i, 2 * i); // Print the result
    }
    return 0;
    }

    Output:

    2 x 1 = 2
    2 x 2 = 4
    2 x 3 = 6
    2 x 4 = 8
    2 x 5 = 10
    2 x 6 = 12
    2 x 7 = 14
    2 x 8 = 16
    2 x 9 = 18
    2 x 10 = 20

    Explanation:

    • The loop starts at i = 1 and runs until i <= 10.
    • In each loop, 2 * i calculates the result for the current step of the table.
    • The output prints both the multiplication step and its result using printf.
    • The loop automatically increases i by 1 after each iteration, covering all numbers from 1 to 10.

    Intermediate Level Example: Sum of First 10 Natural Numbers

    In this intermediate example, we will calculate the sum of the first 10 natural numbers using a for loop. This will help you understand how to accumulate values inside the loop.

    Before writing the code: We will declare a sum variable and run a loop from 1 to 10. In each loop, we will add the current number to the sum.

    #include <stdio.h>

    int main() {
    int sum = 0; // Variable to store the total sum

    // Loop to add numbers from 1 to 10
    for (int i = 1; i <= 10; i++) {
    sum += i; // Add the current value of i to sum
    }

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

    Output:

    Sum of first 10 natural numbers is: 55

    Explanation:

    • The sum variable is initialized to 0.
    • The loop starts at 1 and runs until 10.
    • Each time, the value of i is added to sum using sum += i.
    • After the loop ends, the total sum is printed.

    Advanced Level Example: Print a Right-Angled Triangle of Stars

    In this advanced example, we will print a right-angled triangle pattern using a nested for loop in C. This demonstrates how nested loops work together to create patterns.

    Before writing the code: We will use two for loops. The outer loop controls the rows, and the inner loop prints stars in each row.

    #include <stdio.h>

    int main() {
    int sum = 0; // Variable to store the total sum

    // Loop to add numbers from 1 to 10
    for (int i = 1; i <= 10; i++) {
    sum += i; // Add the current value of i to sum
    }

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

    Output:

    * * 

    * * * 

    * * * * 

    * * * * * 

    Explanation:

    • Outer Loop (rows): Runs from 1 to 5 to handle each row.
    • Inner Loop (stars): For each row i, it prints i stars.
    • After printing stars in one row, printf("\n"); moves the cursor to the next line.
    • This forms a triangle where each row adds one more star than the previous.

    Nested For Loop in C

    A nested for loop in C is a loop inside another loop. It allows you to perform repetitive tasks in a multi-dimensional space. In most cases, nested loops are used for working with multi-dimensional arrays, printing patterns, or other complex tasks where you need to loop through multiple dimensions.

    Explanation of Nested For Loop:

    • The outer loop runs first and controls how many times the inner loop will execute.
    • The inner loop runs fully for each iteration of the outer loop.
    • For each iteration of the outer loop, the inner loop runs completely from start to finish.

    In the following example, we will print a pattern of stars to better understand how nested for loops work.

    Example: Printing a Square Pattern of Stars

    #include <stdio.h>

    int main() {
    int rows = 5; // Define the number of rows

    // Outer loop for rows
    for (int i = 1; i <= rows; i++) {
    // Inner loop for columns (printing stars)
    for (int j = 1; j <= rows; j++) {
    printf("* "); // Print a star
    }
    printf("\n"); // Move to the next line after each row
    }

    return 0;
    }

    Output:

    * * * * * 

    * * * * * 

    * * * * * 

    * * * * * 

    * * * * * 

    Explanation:

    • Outer loop:
      • The outer loop runs from i = 1 to i = 5, controlling the number of rows.
      • After each iteration, it moves to the next row using printf("\n");.
    • Inner loop:
      • The inner loop runs for each value of i (from 1 to 5) and prints 5 stars in each row.
      • Each time the inner loop runs, it prints a star (*) followed by a space.
    • Loop Interaction:
      • The outer loop controls how many rows are printed.
      • The inner loop prints the stars for each row, with the number of stars equal to the number of rows (in this case, 5).

    Also read: Looping Statements in Java: Types, Syntax, Examples & Best Practices article.

    When to Use Nested For Loops?

    Nested for loops are useful when:

    • Working with 2D arrays or matrices.
    • You need to print patterns, such as in this example, or when dealing with multi-level iteration.
    • Performing operations on all elements of a grid-like structure.

    Infinite For Loop in C

    An infinite for loop in C is a loop that runs endlessly without stopping. It occurs when the loop’s termination condition is never met. In most cases, this happens when the loop's condition is set in such a way that it always evaluates to true.

    Explanation of Infinite For Loop

    • Condition: In a typical for loop, there’s a condition that controls when the loop stops. If this condition is always true, the loop runs forever.
    • Use Cases: Infinite loops are useful in scenarios like waiting for user input, maintaining a process running continuously (such as in game engines or servers), or monitoring system states.

    In the following example, we’ll demonstrate an infinite for loop.

    Before writing the code: We will set up a loop where the condition always evaluates to true. This ensures that the loop never exits.

    Example: Infinite For Loop to Print "Hello, World!"

    #include <stdio.h>

    int main() {
    // Infinite loop
    for (;;) {
    printf("Hello, World!\n"); // This will keep printing forever
    }
    return 0;
    }

    Output:

    Hello, World!
    Hello, World!
    Hello, World!
    ...

    Note: The program will keep printing "Hello, World!" indefinitely until you stop the program manually (e.g., using Ctrl+C in the terminal).

    Explanation:

    • For Loop Structure: The loop is written as for(;;). This means that there are no conditions set for when the loop should stop. Hence, the loop will run infinitely.
    • Printing "Hello, World!": In each iteration of the loop, the program prints the message "Hello, World!". Since there is no condition to break the loop, the message keeps printing endlessly.
    • Loop Control: The absence of conditions in the for statement (for(;;)) makes the loop infinite. The program continues running until it is manually interrupted.

    Use of Infinite Loops:

    • This kind of loop is common in systems that need to keep running tasks continuously, such as operating systems, servers, or real-time systems.
    • For example, a server might use an infinite loop to keep checking for incoming client requests.

    Note: Infinite loops should be used cautiously. They can cause a program to hang or consume excessive system resources. It is important to ensure that an infinite loop is necessary for the task and that there is a way to terminate or exit the loop if needed.

    Common Errors While Using For Loop in C

    When using for loops in C, beginners and even experienced programmers can sometimes make common mistakes. These errors can lead to unexpected behavior or inefficient code. 

    Let’s look at some of these errors and how to avoid them.

    • Incorrect Loop Condition:
      • Using a condition that always evaluates to true can lead to an infinite loop.
      • Example: for (int i = 0; i >= 0; i++) (The condition i >= 0 is always true.)
    • Wrong Initialization:
      • If the loop variable is initialized incorrectly, it can cause the loop to either not run or run incorrectly.
      • Example: Initializing int i = 10; when you want to loop from 1 to 10.
    • Off-by-One Error:
      • This happens when the loop runs one iteration too many or too few due to an incorrect loop range.
      • Example: for (int i = 0; i < 10; i++) should be used for printing 10 numbers starting from 0.
    • Improper Update in Loop:
      • Forgetting to update the loop variable or updating it incorrectly may lead to infinite loops or skipped iterations.
      • Example: for (int i = 0; i < 10; ) will result in an infinite loop as the loop variable i is never incremented.
    • Using Incorrect Data Types:
      • Using incompatible data types for the loop variable or condition can lead to errors or undefined behavior.
      • Example: Using a float in a loop counter when it should be an integer.
    • Unnecessary Semicolon After the Loop:
      • Adding a semicolon after the loop condition causes the loop to execute with no body. This can lead to confusion and logical errors.
      • Example: for (int i = 0; i < 10; i++); is incorrect and will result in no output.
    • Missing Break Condition:
      • Sometimes, a break condition is not properly set within the loop, causing unnecessary iterations.
      • Example: Using a for loop with no exit condition when you expect it to stop at some point.

    Conclusion

    The for loop in C is one of the most powerful and flexible tools for controlling repetitive tasks. It allows programmers to run a block of code a specific number of times, making it ideal for scenarios where the number of iterations is known in advance. By understanding its syntax, working mechanism, and practical use cases, you can write efficient and clean code.

    Always remember to test your code carefully and watch out for common errors like incorrect conditions or off-by-one mistakes. With practice, using the for loop in C will become second nature, helping you build more robust programs.

    FAQs

    What is a for loop in C used for?

    The for loop in C is used to execute a block of code repeatedly for a fixed number of times. It is ideal when you know beforehand how many times the loop should run, making it efficient for tasks like counting or iterating over arrays.

    Can we use multiple variables in a for loop in C?

    Yes, you can use multiple variables in a for loop in C by separating them with commas in the initialization and update sections. However, the loop condition can only include one condition that determines when the loop should stop.

    What happens if the condition in a for loop is always true?

    If the condition in a for loop is always true, the loop becomes infinite. This means it keeps running endlessly unless a break statement is used inside the loop to stop it manually when a certain condition is met.

    Can the for loop in C be replaced by a while loop?

    Yes, any for loop in C can technically be rewritten using a while loop. However, the for loop is more compact and readable when you know the exact number of iterations needed, whereas the while loop suits unknown iteration counts.

    What is the syntax of a for loop in C?

    The basic syntax of a for loop in C is:

     for (initialization; condition; update) { // code block }

    It starts with initialization, checks the condition before each iteration, and updates the loop variable after each loop cycle.

    What is an off-by-one error in a for loop?

    An off-by-one error occurs when your loop runs one time too many or too few. This usually happens due to incorrect use of comparison operators in the condition. Careful planning of loop bounds helps avoid this mistake.

    Can we omit any part of the for loop syntax in C?

    Yes, in C, the initialization, condition, and update parts of a for loop are optional. If you omit the condition, it becomes an infinite loop. However, leaving out sections should be done cautiously to maintain readability.

    How does a nested for loop work in C?

    A nested for loop in C means placing one for loop inside another. The inner loop completes all its iterations for every single iteration of the outer loop. This is useful for working with multi-dimensional arrays or complex pattern printing.

    What is the difference between a for loop and a do-while loop in C?

    The key difference is that a for loop checks the condition before executing the code block, while a do-while loop runs the code block at least once before checking the condition. This makes do-while loops useful when one execution is guaranteed.

    How do you stop a for loop in C before it finishes?

    You can stop a for loop before it completes by using the break statement. When break is encountered inside the loop, it immediately exits the loop, skipping any remaining iterations, and continues with the next part of the program.

    Is it possible to create an infinite for loop in C intentionally?

    Yes, you can create an infinite for loop in C by writing the loop without a condition or by setting the condition to always be true. This is often used in embedded systems or programs that need to run continuously until manually stopped.

    image

    Take a Free C Programming Quiz

    Answer quick questions and assess your C programming knowledge

    right-top-arrow
    image
    Join 10M+ Learners & Transform Your Career
    Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
    advertise-arrow

    Free Courses

    Start Learning For Free

    Explore Our Free Software Tutorials and Elevate your Career.

    upGrad Learner Support

    Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

    text

    Indian Nationals

    1800 210 2020

    text

    Foreign Nationals

    +918068792934

    Disclaimer

    1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

    2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.