while loop-C programming with example

What is a loop?

Loops are used to execute the block of code several times according to the condition given in the loops. Every loop required initialization, condition, increment/decrement in the C programming language.

while loop in C

while loop in C can be used when you need to investigate a situation. The loop tests its position before executing the contents of the loop. If the test condition is false while the loop is entered into a block of code, it is never executed. Sometimes a loop can never be executed if the condition is not initially met. This is known as an entry control structure.

In simple words, A while loop repeats as long as a certain condition is true.

Syntax of while loop:

  while(condition is true)
{
       // Statements to be executed repeatedly 
      // Increment (++) or Decrement (--) Operation
      action1;
}
     action 2;

Flowchart of while loop in C:

Flowchart of while loop

The while loop is used when we are not certain that the loop will be executed after checking the weather the initial conditions are true or false and finding it to be true only then, the while loop will enter the loop operations.

Example of while loop:

#include <stdio.h>
#include <stdlib.h>
int main()
{
   int i=1;
   while(i<=10)
   {
 printf("%d ", i);
 i++;
   }
   return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10

Here, i=1; is the starting point that starts at 1, and (i<=10) means less than or equal to 10. This loop will repeat until it gets i=10. The test condition after the value 10 is false, while the loop is entered into a block of code, and is never executed.

Previous Lecture:

Loops in C
Data Types in C
Switch Case Statement
Conditional Statements if,if-else

If you have any problem in solving your questions, then join our Telegram group or search @Learnsimply, we will help you.

Please write comments if you find anything incorrect in the while loop in C lecture.

Leave a Comment

en English
X