How to use while loop in C

About C 'while' Loop

Like other programming languages, the C 'while' loop is a control flow statement that is used to repeatedly execute a block of code as long as the specified condition of 'while' is true.

The condition is evaluated before each iteration. If it is true, the code block inside the loop is executed. If the condition is false, the loop will stop to execute the block of code.

It's important to ensure that the condition in a while loop will eventually become false. Otherwise, the loop will continue indefinitely. Infinite loops can cause a program to become unresponsive or consume excessive CPU resources.

Syntax of 'while' loop

  • while (condition): In the line, the 'while' loop begins with the 'while' keyword. The 'while' is followed by a condition enclosed in parentheses '()'.
  • //block of code to be executed : The line will be replaced by a block of code which will be executed at each iteration. The block of code needs to be placed inside curly braces '{}' under 'while' condition. The code will be executed as long as the condition of 'while' is true.
  • //updating condition: The line will be replaced by a block of code to update the 'while' condition. It is important to ensure that some change has been made to the variable of loop condition. Otherwise, the loop may run indefinitely and the program becomes unresponsive.

Create a 'while' loop statement

A 'while' loop statement has been created in the following example that will print number from 1 to 5:

Examples of 'while' loop
Output of the above example
1
2
3
4
5

Explanation of code:

  • int i = 1;: The line declares an integer variable named 'i' and assigns value 1. It will be used in the 'while' condition.
  • while (i <= 5): The line begins the 'while' loop with 'while' keyword. 'i <= 5' is the condition of 'while' loop. As long as the value of 'i' is less than or equal to 5, the code block inside the loop will be executed repeatedly.
  • printf("%d\n", i);: The line prints the value of 'i' variable. '%d' is the format specifier for integer data and '\n' creates a newline.
  • i++;: The line increments the value of the 'i' variable by 1. When the value of the 'i' variable becomes 6, the 'while' condition will be false and the loop will terminate.

Live Code Playground

In the following C code editor, you can practice by creating more 'while' loop statements. Click the 'Execute Code' button to execute the code; the executed output will be displayed in the following C Code Output frame. Practice until you become comfortable and proficient with your code.

C logo C Online Editor
C Code Output