C for loop

A for loop is a pre-tested loop. A for loop statement is used when a user knows how many times you want to execute the code. A for loop statement executes a block of statements repeatedly for the fixed number of times. A for loop is a most popular loop.

Syntax of for loop:

Following is a general syntax to write code using for loop –

NOTE: It is compulsory to give two semicolons in the pair of round braces () else compiler will give an error.
It is mandatory to give two semicolons(;) whether you write an initialization expression or increment or decrement expression.

Working of for loop:

  • The initialization is executed first. It initializes a loop counter only once.
  • Next, the condition is evaluated. If the condition is true then statements within the body of the loop are executed.
    If a condition is false, the body of the loop is not executed and flow of control jumps to next statement just after the ‘for’ loop.
  • After executing the body of the loop, flow of control jumps to increment/decrement statement.
  • Now the condition is evaluated again. If it is true, the loop executes and the process repeats.

Example:

Output:

Here also the output is same as while and do-while loop. Firstly, i is initialized by 1, then condition i < 5 is checked and print value of i. Then after i is incremented. Again condition will be check if true then execute printf() statement else it breaks the loop. In this way, a loop is repeated until the condition is false.

Flowchart of for loop:

The flowchart of for loop shown below would help you to understand the operation of for loop.

for loop
Forms of for loop:

Following are some valid syntax of for loop:


  • This loop is called as infinity for loop. Because it executes the number of time.
    There is no initialization, no condition, no increment/decrement.
    This loop print “infinity for loop” infinite times.

Ankit Wasankar

Senior Java Developer
Java 11 | Microservices | Reactjs | SQL

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.