While Loop in C
For Complete YouTube Video: Click Here
Here we will try to understand While Loop in C.
We have already covered Operators and Selection Statements in C.
Before understanding the While loop, we will try to understand Iterative Statements.
Table of Contents
What are iterative statements?
For example, if we want to write a program to print numbers from 1 to 10, how can we write it.
As per our discussion in our previous classes, we have to use ten printf() functions.
But this kind of approach is repetitive use of the same job of printing.
To avoid such kind of repetitiveness, C provides three types of Iterative Statements or Loops.
- while Loop
- do-while Loop
- for Loop
while Loop in C
The image below is the syntax for a while loop.
In the above image, while is a keyword followed by open and closed parentheses.
Within those parentheses, we have to provide controlling expression.
The controlling expression decides whether to execute the statements of the loop body again or not.
Below the while statement, we have open and closed flower braces.
In those braces, we can provide the statements to be repeated for execution.
While Loop Syntax
The image below is an syntax of a while loop.
In the above image, while is a keyword followed by open and closed parentheses.
Within those parentheses, we have to provide controlling expression.
The controlling expression decides whether to execute the statements of the loop body again or not.
Below the while statement, we have open and closed flower braces.
In those braces, we can provide the statements to be repeated for execution.
While Loop Example
The image below is an example of a while loop.
The above example uses a while loop to print the numbers from 1 to n.
In the above example, we have two variables, i and n.
Variable i is to print the number, and n is for the number of iterations to be done.
The controlling statement used is (i<n), and i is initialized to 1.
The user provides the value of n.
If the user has provided n as ten, then the loop will iterate ten times.
In every iteration, the loop body will be executed.
The printf() function will print the value of i.
The step-by-step explanation is provided in the video above.