C while loop
Loops in C language
This lesson is about C while loops. Another main component of programming languages is the loop. Loops execute one or more statements multiple times under certain conditions. For example, if we want to read 100 numbers from the input and add them together, We must repeat the act of reading the number 100 times.
The statement(s) inside a loop is repeated until the condition of the loop is satisfied, and as long as the loop is running, the program stays in the loop. Repetition structures are used in different programming languages. Now we want to examine loops in C language. C language has three types of loops:
- while loop
- do while loop
- for loop
While loop
One of the loops in C language is the while loop. The purpose of the while keyword is to repeat commands several times. As long as the condition of the loop has a logical value (true). When the condition of the while loop does not have a logical value (true), the loop stops, and the execution of the program resumes from the next statement after the loop. The general structure of a while loop is as follows:
while(condition)
{
//statements
}
The flowchart of this loop is shown in the following image:

If you look carefully at the flowchart, you will notice that if the condition is not true, the commands inside the loop will not be executed even once. Look at a simple example of a while loop:
#include <stdio.h>
int main(){
int a = 1
while(a < 16){
printf("%d\n", a);
a++;
}
return 0;
}
- The above loop will be executed until a is less than 16.
- Inside the loop, a is incremented by one in each while loop iteration.
- The value of a is printed onto the screen using printf() function.
Nested while loop
#include <stdio.h>
int main(){
int x = 0;
int y = 0;
while(x < 8){
while(y < 5){
printf("%d-%d\n", x, y);
y++;
}
y = 0;
x++;
}
return 0;
}
- The outer while loop repeats 8 times, and for its every iteration, the inner loop repeats five times.
- The inner loop prints the x and y’s values and increase y by one.
- The outer loop resets the value of y, increases x by one, and executes the inner loop.
Loops need two statements called “break and continue” to exit the loop and jump to the next iteration, which we cover later.