C Programming for Loop

Loops are used in programming to repeat a specific block of code. After reading this tutorial, you will learn how to create a for loop in C programming.
for loop in C programming

Loops are used in programming to repeat a specific block until some end condition is met. There are three loops in C programming:

  1. for loop
  2. while loop
  3. do...while loop

for Loop

 The syntax of a for loop is:

for (initializationStatement; testExpression; updateStatement)
{
       // codes 
}

How for loop works?

The initialization statement is executed only once.

Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated. But if the test expression is true (nonzero), codes inside the body of for loop is executed and update expression is updated. This process repeats until the test expression is false.

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

To learn more on test expression (when test expression is evaluated to nonzero (true) and 0 (false)), check out relational and logical operators.


for loop Flowchart

Flowchart of for loop in C programming language


Example: for loop

// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers

#include <stdio.h>
int main()
{
    int n, count, sum = 0;

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

    // for loop terminates when n is less than count
    for(count = 1; count <= n; ++count)
    {
        sum += count;
    }

    printf("Sum = %d", sum);

    return 0;
}

Output

Enter a positive integer: 10
Sum = 55

The value entered by the user is stored in variable n. Suppose the user entered 10.

The count is initialized to 1 and the test expression is evaluated. Since, the test expression count <= n (1 less than or equal to 10) is true, the body of for loop is executed and the value of sum will be equal to 1.

Then, the update statement ++count is executed and count will be equal to 2. Again, the test expression is evaluated. The test expression is evaluated to true and the body of for loop is executed and the sum will be equal to 3. And, this process goes on.

Eventually, the count is increased to 11. When the count is 11, the test expression is evaluated to 0 (false) and the loop terminates.