DevAcademia
C++C#CPythonJava
  • C Basics

  • Introduction to C
  • Getting Started with C
  • C Syntax
  • C Output
  • C Comments
  • C Variables
  • C Data Types
  • C Constants
  • C Operators
  • C Booleans
  • C If...Else Statements
  • C Switch Statement
  • C While Loops
  • C For Loops
  • C Break and Continue
  • C Strings
  • C User Input
  • C Memory Address
  • C Pointers
  • C Files
  • C Functions

  • C Functions
  • C Function Parameters
  • C Scope
  • C Function Declaration
  • C Recursion
  • C Math Functions
  • C Structures

  • C Structures
  • C Structs & Pointers
  • C Unions
  • C Enums

  • C Enums
  • C Memory

  • C Allocate Memory
  • C Access Memory
  • C Reallocate Memory
  • C Deallocate Memory
  • C Structs and Memory
  • C Memory Example
  • C Quiz

  • C Quiz
  • C Basics

  • Introduction to C
  • Getting Started with C
  • C Syntax
  • C Output
  • C Comments
  • C Variables
  • C Data Types
  • C Constants
  • C Operators
  • C Booleans
  • C If...Else Statements
  • C Switch Statement
  • C While Loops
  • C For Loops
  • C Break and Continue
  • C Strings
  • C User Input
  • C Memory Address
  • C Pointers
  • C Files
  • C Functions

  • C Functions
  • C Function Parameters
  • C Scope
  • C Function Declaration
  • C Recursion
  • C Math Functions
  • C Structures

  • C Structures
  • C Structs & Pointers
  • C Unions
  • C Enums

  • C Enums
  • C Memory

  • C Allocate Memory
  • C Access Memory
  • C Reallocate Memory
  • C Deallocate Memory
  • C Structs and Memory
  • C Memory Example
  • C Quiz

  • C Quiz

Loading C tutorial…

Loading content
C BasicsTopic 34 of 64
←PreviousPrevNextNext→

C For Loop

Introduction to For Loop

The for loop in C is a control flow statement that allows code to be executed repeatedly based on a specified condition. It's particularly useful when you know in advance how many times you want to execute a statement or a block of statements.

The for loop is often called a 'definite loop' because it typically executes a specific number of times, unlike while loops which are often 'indefinite loops'.

Syntax and Structure

A for loop has three parts—initialization, condition, and increment/decrement—executed in that order on each iteration. The semicolons are required; any of the three expressions may be omitted, but the semicolons must remain.

Example
for (initialization; condition; increment_or_decrement) {
    // code to be executed
}
ℹ️ Note: Declaring the loop variable inside the initialization (e.g., for (int i = 0; ...)) requires C99 or later; that variable's scope is limited to the loop.

How For Loop Works

1. The initialization expression is executed once

2. The condition is evaluated

3. If the condition is true, the loop body is executed

4. The increment/decrement expression is executed

5. Steps 2-4 repeat until the condition becomes false

6. Control passes to the statement following the loop

Basic Example

Example
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 5; i++) {
        printf("%d ", i);
    }
    printf("\nLoop ended.\n");
    return 0;
}
Output
1 2 3 4 5 
Loop ended.

Loop Control Variable

The loop control variable (often 'i', 'j', 'k') is typically:

• Initialized before the loop starts

• Tested before each iteration

• Modified at the end of each iteration

It's good practice to use meaningful variable names when appropriate, especially in nested loops or complex algorithms.

Example
#include <stdio.h>

int main(void) {
    for (int count = 10; count >= 1; count--) {
        printf("%d ", count);
    }
    printf("\nLiftoff!\n");
    return 0;
}
Output
10 9 8 7 6 5 4 3 2 1 
Liftoff!

Multiple Expressions

You can use multiple expressions in the initialization and increment/decrement sections by separating them with commas. This can be useful for managing multiple loop variables simultaneously.

Note: Only the initialization and increment/decrement fields support comma-separated expressions. The middle expression is a single condition; combine checks with logical operators (&&, ||) rather than commas.

Example
#include <stdio.h>

int main(void) {
    for (int i = 0, j = 10; i < j; i++, j--) {
        printf("i=%d, j=%d\n", i, j);
    }
    return 0;
}
Output
i=0, j=10
i=1, j=9
i=2, j=8
i=3, j=7
i=4, j=6

Optional Expressions

Any of the three expressions in a for loop can be omitted, but the semicolons must remain.

This flexibility allows for various loop patterns, but should be used judiciously for readability.

Example
#include <stdio.h>

int main(void) {
    int i = 0;
    for (; i < 5; i++) {
        printf("%d ", i);
    }
    printf("\n");

    for (int j = 0; j < 5;) {
        printf("%d ", j);
        j++;
    }
    printf("\n");

    int k = 0;
    for (;;) {
        printf("%d ", k);
        k++;
        if (k >= 3) break; // ensure termination
    }
    printf("\n");
    return 0;
}
Output
0 1 2 3 4 
0 1 2 3 4 
0 1 2

Loop Control Statements

C provides two important statements for controlling loop execution:

• break: Immediately terminates the loop

• continue: Skips the current iteration and proceeds to the next iteration

Example
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 10; i++) {
        if (i == 3) {
            continue;
        }
        if (i == 8) {
            break;
        }
        printf("%d ", i);
    }
    printf("\nLoop ended.\n");
    return 0;
}
Output
1 2 4 5 6 7 
Loop ended.

Common Patterns

For loops are commonly used for:

• Iterating through arrays

• Processing sequences of numbers

• Repeating operations a specific number of times

• Implementing various algorithms

Example
#include <stdio.h>

int main(void) {
    int sum = 0;
    for (int i = 1; i <= 10; i++) {
        sum += i;
    }
    printf("Sum of first 10 numbers: %d\n", sum);

    int factorial = 1;
    for (int i = 1; i <= 5; i++) {
        factorial *= i;
    }
    printf("Factorial of 5: %d\n", factorial);
    return 0;
}
Output
Sum of first 10 numbers: 55
Factorial of 5: 120

Best Practices

1. Use meaningful variable names for loop counters when appropriate

2. Keep loop bodies concise; consider moving complex logic to functions

3. Avoid modifying the loop counter within the loop body unless necessary

4. Use the most appropriate loop type for your specific use case

5. Be cautious with floating-point numbers as loop counters due to precision issues

6. Consider performance implications for very large loops

7. Prefer declaring the loop variable in the for header (C99+) to limit its scope to the loop

Test your knowledge: C For Loop
Quiz Configuration
8 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 10 min
C BasicsTopic 34 of 64
←PreviousPrevNextNext→