C for Loop

Summary: in this tutorial, you will learn about C for loop statement to execute a block of code repeatedly.

Introduction to C for loop statement

The C for loop statement is used to execute a block of code repeatedly. It is often used when the number of iterations is predetermined. If the number of iterations is not predetermined, we often use while loop or do while loop statement.

The following illustrates the syntax of the for loop statement:

There are three expressions separated by the semicolons ( ;) in the control block of the C for loop statement.

  • The initialization_expression expression executes when the loop first starts. It is typically used to initialize a loop counter variable.
  • The loop_condition expression is evaluated at the beginning of each iteration. The execution of the loop continues until the loop_condition evaluates to false.
  • The increment_expression expression is evaluated at the end of each iteration. It is used to increase or decrease the loop counter variable.

The following flowchart illustrates the C for loop statement:

c for loop flowchart

C for loop Flowchart

The following example demonstrates how to use C for loop statement to display numbers from 0 to 4:

And the output is:

Variations of the C for loop statement

C for loop is very flexible based on combination of the three expressions. You can increase or decrease the loop counter. You can count by not only one but also two, three and so on. You can count by a character. Let’s take a look at the following program:

Because all expressions in the for loop statement are optional, you can omit any expression or all of them. When you omit all expressions, the for loop behaves slightly similar to the while loop or do while loop.

The following program demonstrates the flexibility of C for loop:

Nested for loop in C

You can put a for loop inside another for loop, which is called a nested for loop. The following example demonstrates how to use a nested for loop to display a pyramid of stars based on the number of levels.

For example, if you want to display a pyramid with 10 levels, you can see the following output:

Another example of using for loop statement to develop a program for displaying the Pascal’s triangle. Simply put, in the Pascal’s triangle, each number is the sum of the two numbers directly above it.

When you enter the number of rows for the Pascal’s triangle: 8, you get the following output:

In this tutorial, you have learned how to use various forms of the C for loop statement to execute a block of code repeatedly when the number of iterations is predetermined.