Omitting Expressions in a for Loop
For Complete YouTube Video: Click Here
In this class, we will understand Omitting Expressions in a ‘for loop.
We already had a basic understanding of for loop in c.
The for loop in C has three different expressions.
- Initialization Expression
- Control Expression
- Incrementing/Decrementing Expression
Table of Contents
Omitting Expressions in a for Loop
Is it mandatory to use all the expressions in every ‘for loop?
No, it is NOT mandatory.
We can omit some of the expressions or all the expressions in some programming practice.
Based on our programming requirement, we can omit some expressions in a ‘for’ loop.
Omitting the Initialization Expression in a ‘for’ loop
For example, consider the program in the image below.
The above program is the program to print the integers from one to n.
In the above program, the value is initialized at the declaration of the variable itself.
In that case, there is no need to initialize the variable in the ‘for’ loop.
Even though the expression is not used, it is mandatory to specify the semicolon for the expression.
Omitting the Incrementing/Decrementing Expression in a ‘for’ loop
The image below is the program that omitted the Incrementing expression.
In the above program, the incrementing operator has been omitted.
But that omitted expression has to be used in the loop’s body because the loop has to be iterated.
In such cases, the incrementing expression is used at the end loop’s body.
In most cases, the control statement is not omitted.
Infinite loops
In programming, it is frequently required to create infinite loops.
The image below is the use of an infinite loop.
Infinite loops will NOT stop their iteration.
As there is no control expression, the loop will iterate infinitely.
In infinite loops, we have to use jump statements to come out of the loop.
We should be careful while using infinite loops.
In our next classes, we will have a clear understanding of infinite loops.