For loops without a body

For Complete YouTube Video: Click Here

In this class, we will look For loops without a body.

We have covered examples on ‘for’ loops where we have a body of the ‘for’ loop.

We can write the C Programs so that we will not provide the loop’s body.

To understand this concept, we will first consider the program for factorial with loop’s body.

Next, we will write the same program without the loop’s body.

Factorial of a number with loop body

Program

The image below is the program of the factorial of a number with the loop’s body.

For loops without a body Example 1
For loops without a body Example 1

In the above example, we have taken three variables n, fact, i.

We will store the for which the factorial has to be calculated in n.

If the end-user has given the value as 5, the for loop will calculate the factorial of 5, 120.

In the for loop, the value of i is assigned to 1, and the loop will iterate for 5 times.

Iteration 1

i = 1;

fact = fact * 1;

The fact is initialized to 1.

fact = 1 * 1;

fact = 1;

Iteration 2

i = 2;

fact = fact * 1;

The fact-value is 1 in the previous iteration.

fact = 1 * 2;

fact = 2;

Iteration 3

i = 3;

fact = fact * 1;

The fact-value is 2 in the previous iteration.

fact = 2 * 3;

fact = 6;

Iteration 4

i = 4;

fact = fact * 1;

The fact-value is 6 in the previous iteration.

fact = 6 * 4;

fact = 24;

Iteration 5

i = 5;

fact = fact * 1;

The fact-value is 24 in the previous iteration.

fact = 24 * 5;

fact = 120;

In iteration 6, we will come out of the loop’s body.

As the ‘i<=5’ is false.

Factorial of a number without a loop’s body

Program

The image below is the program of the factorial of a number without the loop’s body.

For loops without a body Example 2
For loops without a body Example 2

In the above example, the for loop does not have the body.

The calculation fact *= 1 is provided in the incrementation part of the ‘for’ loop.

The loop will iterate for 5 as the above example, and calculations are done in the iteration part of the loop itself.

The important point to note is the loops without the body will end with a semicolon.

If the semicolon is provided, the next statement below the loop will be considered as loops body.