Loops help to execute the set of code blocks repeatedly many times till the condition is met. Let’s understand While Loop in C.
Why do we need loops?
Let’s say we want to add 2 numbers which can be easily done by number1+number2
But what if there is a requirement to add 100 numbers? Well, here loops play an important role
As mentioned in the definition, the code block in the loop will run 100 times hence we’ll get the desired output, So loops are very efficient to execute the same instructions again and again.
C Programming language has three types of loops:
- For loop
- While loop
- Do while loop
In this, we will learn about the while loop.
While loop:
While loop executes a code block as far as the condition specified is true.
Syntax:
How while loop works:
- The while loop evaluates the condition which is inside the parentheses after “while” keyword
2. If the condition is found to be true it will execute the block of code inside the loop
3. step 2 will occur again and again till the condition is false
4. If the condition is false control will come out of the loop
Refer below flow chart to understand more clearly
Flow chart:
Let’s see an example of how while loop works internally:
Printing numbers from n to 1
Code:
C Program
#include <stdio.h>
int main() {
int n = 10;
while (n>0) {
printf("%d\n", n);
n--;
}
return 0;
}
Output:
10
9
8
7
6
5
4
3
2
1
Special thanks to Sai bargav Nellepalli for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article