While Loop in C

The while loop in C Programming is to repeat a block of statements for a given number of times until the given condition is False. A while loop starts with a condition, and on each iteration, it will check this condition. If the condition is True, then statements inside it will execute. If the given condition is false, the iteration won’t be performed at least once. It means while loop in C language may run zero or more times.

In real-time, there are situations where a task needs to be repeated N times until a specific condition is met. For instance, traverse an array, characters in a string, etc. In these situations, we use a C while loop to iterate over them to perform various operations.

Syntax of While Loop C Programming

The syntax of the while loop to repeat the tasks is as follows:

while(condition)
{
statement 1;
statement 2;
………….
}
Outside statement;

From the above while loop syntax,

  • While is the reserved keyword that informs the compiler to enter into the C while loop.
  • Condition: It is the most crucial part in the while loop. It is a logical expression that determines whether the compiler should enter the while loop or not.
  • The statements within the {} is the while loop body. On each iteration, the code (statements) inside these curly braces executes.
  • Outside Statement: This is the statement outside the block but inside the main() Function.

First, the compiler checks for the condition inside the C while loop. If the condition is True, the statement or group of statements under the block will execute. If the condition is False, the compiler will exit from the body and execute other statements outside the while loop.

For a single statement inside a while loop, curly braces are not needed. However, if we omit them for multiple statements, the compiler will only execute the first statement. It is always good practice to use braces with a while loop.

Apart from the above mentioned C while loop syntax, in most situations, there are two things that we must include.

  • Initialization: There are some situations where we set the while condition to always be true. Except for these situations, we must initialize the value before using it inside a while loop.
  • Update: On each iteration, the counter value must be either incremented or decremented. So, we must use operators to increase or decrease the initial loop value.

TIP: There are two more loops, so please refer to the For Loop and Do While Loop articles.

Flow Chart of While loop in C

The following screenshot shows the flow chart of the while loop in C programming language.

While loop Flow Chart

At the beginning, the while loop checks for the condition. The following steps explain the working flow of a while loop.

  • Step 1: Initialize the required variables that can be used inside the while loop condition or in the body.
  • Step 2: When the compiler finds the while keyword, the first step is to evaluate the condition or expression of the while loop in C.
  • Step 2A: If the expression is evaluated as False, the compiler will exit from the While loop.
  • Step 2B: If the condition is True, then it will execute the statements inside the while loop (body). Within the body, use Increment & Decrement Operators to increment and decrement the value. Please refer to the C Increment and Decrement Operators article to understand the functionality.
  • Again, it will check for the condition after the value is incremented (Step 2).  The while loop iteration process continues as long as the condition is True.

Let us see an example of a while loop for a better understanding.

Examples of the while loop in C programming

As we mentioned earlier, the while loop repeatedly executes the code inside it for n number of times until the condition is true. To demonstrate the basic usage of the while loop, in the example program, we declared an integer with the value 1.

Next, the while loop iterates until I become 5. Inside the C while loop, we placed a printf() statement to display the Hello message. It means that each iteration of the while loop prints the Hello message as output (a total of 4 times).

#include <stdio.h>
int main()
{
int i = 1;
while(i < 5)
{
printf("Hello\n");
i++;
}
}
Hello
Hello
Hello
Hello

Print Numbers from 1 to 10

The following example shows how to use a while loop in C to print the natural numbers from 1 to 10. In the example below, we declared an integer variable and initialized it to 1. The condition inside the while loop (n <= 10) is for the loop termination.

  1. First, the compiler checks whether n is less than or equal to 10. As 1 is less than 10, the condition is True, so it enter inside the while loop.
  2. The printf() statement prints the number, which is one for the current iteration.
  3. The n++ statement increments the n value by 1.
  4. Next, the compiler moves to the top of the while loop to check the condition for the incremented value, which is 2. The above-mentioned process (1, 2, and 3) continues until n becomes 11.
  5. Once n becomes 11, the while loop condition fails, and as there is no code to execute after the while loop block, the program ends.
#include <stdio.h>
int main()
{
int n = 1;
while(n <= 10)
{
printf("%d ", n);
n++;
}
}
1 2 3 4 5 6 7 8 9 10

TIP: I suggest referring to the C Program to print the first 10 natural numbers and print natural numbers from 1 to N articles for better understanding.

Sum of first N natural numbers using a while Loop in C

This program allows the user to enter an integer value below 10. By using this value, the compiler will add those values up to 10.

  1. In this while loop example, the User will enter any value below 10, and the total variable is initialized to 0.
  2. Next, the user-entered value will be assigned to the number variable. Then, the given number will test against the condition.
  3. If the condition results in true, the number is added to the total. Otherwise, it will exit from the iteration.
  4. We used the ++ operator in the next line to increment the number value. After incrementing, the process repeats until the expression evaluates to False.
#include <stdio.h >

int main()
{
  int number, total=0;

  printf("\n Please Enter any integer below 10 \n ");
  scanf("%d", &number);

  while (number <= 10)
   {
     total = total+number;
     number++;
   }

  printf("\n Value of Total From the While  Loop is: %d \n", total); 
  return 0;
}

We are going to enter the number = 6. It means, total = 6+7+8+9+10 = 40

While Loop in C Programming Output

TIP: Please change the while condition by replacing 10 with any number to find the sum of natural numbers from 1 to N. I suggest referring to the C Program to find the sum of N numbers article for better understanding.

Print Even Numbers below 10

In the example below, the n value is 2, so the loop starts at 2. Next, the C while loop stops the iterations when n becomes 11. Within the while loop, on each iteration, we are printing the n value. The next line inside the while loop increments the number by 2. So, the number becomes 4.

#include <stdio.h>
int main()
{
int n = 2;
while(n <= 10)
{
printf("%d ", n);
n+= 2;
}
}

TIP: Please change the n value to 1 (int n = 1) to print the first 10 odd numbers. Please refer to the C Program to Print Even Numbers and Odd Natural Numbers articles for a better understanding.

C While loop backward iteration

A while loop can traverse both forward and backwards. Based on the increment and decrement operator value, the movement backwards and forward is decided. For instance, printing numbers from 1 to 10, the while loop moves forward starting from 1 and travels towards 10.

Similar to the first example, we can use the while loop to print the numbers in reverse order from 10 to 1 (moving backwards). To do so, we must change the initial value to 10 and the while condition.

Here, we declared a variable and assigned 10 to it, the maximum value. The while loop in C starts at 10 and checks whether the number on each iteration is greater than 0. If true, print the number and the decrement operation minus 1 from the original. So, the number becomes 9 and goes until it becomes 0.

#include <stdio.h>
int main()
{
int n = 10;
while(n > 0)
{
printf("%d ", n);
n--;
}
}
10 9 8 7 6 5 4 3 2 1

TIP: I suggest referring to the print 10 numbers in reverse order and print natural numbers in reverse order articles for better understanding.

Use a C while loop to find the factorial of a number

In the example below, the while loop starts at 5, and the iteration moves backwards (5 -> 4 -> 3 -> 2 -> 1) until it reaches 0. On each iteration, we multiply the value to find the factorial.

#include <stdio.h>
int main()
{
int n = 5;
long fact = 1;
while (n > 0)
{
fact = fact * n;
n--;
}
printf("%d ", fact);
}
120

TIP: There are multiple ways to find the factorial (moving forward). I suggest referring to the C Program to Find the Factorial of a Number article for a better understanding.

Reverse a Number using a While loop in C

The following example uses the while loop to iterate over the digits in a given number and reverse them. Here, the while loop condition checks whether the number becomes 0; if true, the iteration process exists.

#include <stdio.h>
int main()
{
int n = 23456, rev = 0;

while (n != 0)
{
rev = rev * 10 + (n % 10);
n /= 10;
}
printf("%d ", rev);
}
65432

TIP: For a better understanding, please refer to the C Program to reverse a number and Palindrome number articles.

C While loop to calculate the sum of digits

In the example below, we used the while loop to iterate over the individual digits in a given number and find the sum of those digits.

On each while loop iteration, n % 10 extracts the last digit and adds it to the sum variable. Next, n /10 removes the last digit from the original number. For instance, after the first iteration, 23456 becomes 2345 and sum = 6.

#include <stdio.h>
int main()
{
int n = 23456, sum = 0;
while (n != 0)
{
sum += n % 10;
n /= 10;
}
printf("%d ", sum);
}
20

TIP: Refer to the C Program to find the sum of Digits in a number article.

Print Lowercase Alphabets

The following example uses a C while loop to iterate over the lowercase alphabetical characters from ‘a’ to ‘z’ and print them.

#include <stdio.h>
int main()
{
char ch = 'a';
while (ch <= 'z')
{
printf("%c ", ch);
ch++;
}
}
a b c d e f g h i j k l m n o p q r s t u v w x y z

TIP: Please refer to the C Program to print the lowercase and Uppercase alphabet articles.

Check Prime Number using a while loop in C

The following example uses the while loop to iterate over the numbers and checks whether the given number is prime or not.

#include <stdio.h>
int main()
{
int n = 61, i = 2, flag = 1;
while(i <= n / 2)
{
if(n % i == 0) {
flag = 0;
break;
}
i++;
}
if(flag && n > 1)
{
printf("Prime Number");
}
else {
printf("Not Prime");
}
}
Prime Number

TIP: Please refer to the C Program to find Prime Number article.

C while loop to validate user input

In a simple program, we allow the user to enter a number. If the user enters the wrong number, we display a message and the program exits. However, using a while loop, we allow the user to enter the correct value.

The following program allows the user to enter a positive number greater than 0. If the user enters a negative value or zero, it displays an invalid entry message and asks the user to re-enter the value. The process continues until the user enters a positive number.

#include <stdio.h>
int main()
{
int n = 0;
while (n <= 0)
{
printf("Enter a Positive Number = ");
scanf("%d", &n);

if (n <= 0)
{
printf("Invalid Input.\n");
}
}
printf("%d is a Valid Input", n);
}

Result

Enter a Positive Number = -22
Invalid Input.
Enter a Positive Number = 0
Invalid Input.
Enter a Positive Number = 100
100 is a Valid Input

C while loop for password validation

We use the above approach to validate the user-entered password. Here, we use the strcmp() function to compare the user-entered string with the existing password. If they match, print the success message. Otherwise, inform the user about the wrong entry and allow them to re-enter the password.

#include <stdio.h>
#include <string.h>
int main()
{
char password[] = "sample12345";
char str[50];

while (1)
{
printf("Enter Password = ");
scanf("%s", str);
if (strcmp(password, str) == 0)
{
break;
}
printf("Wrong Password entered.\n");
}
printf("Successful Login");
}
Enter Password = 1234
Wrong Password entered.
Enter Password = admin
Wrong Password entered.
Enter Password = sample12345
Successful Login

Infinite While Loop in C Programming

A while loop falls into an infinite loop when the given condition never becomes false. There are multiple reasons for an infinite while loop. For instance, if you forget to increment or decrement the value inside the while loop, it will execute infinite times, also called an infinite loop.

#include<stdio.h> 

int main()
{
int x = 1;

while(x < 10)
{
printf("Value = %d\n", x);

}
return 0;
}
Infinite While Loop Output

Here x is always 1, and x is always less than 10. So, the statement will execute infinite times (infinity). Now, let us add an increment operator (x++) inside the C while loop to the above example.

#include<stdio.h> 

int main()
{
int x = 1;

while(x < 10)
{
printf("Number = %d \n ", x);
x++;
}
return 0;
}

Now, when it reaches 10, the expression will fail. Let us see the C Programming output.

Solution to Infinite While loop in C

Using 1 as the condition

In the example below, the while loop condition is 1, which means it executes forever. It is a classic example of an infinite while loop in C because there is no exit condition.

#include <stdio.h>
int main()
{
int i = 1;
while(1)
{
printf("Hello\n");
}
}

In these situations, we must use the break statement. It helps to avoid the infinite loop when the condition is met. In the example below, the while loop iterates infinitely. However, when I become 3, the if statement inside the while loop executes the break statement, and it exits the loop.

#include <stdio.h>
int main()
{
int i = 1;
while (1)
{
printf("Hello\n");
if (i == 3)
{
break;
}
i++;
}
}
Hello
Hello
Hello

NOTE: Check the Validate User Input and Password Validation examples. Those two are the classic examples of an infinite while loop. If we miss the break statement, both enter an infinite while loop.

Nested While loop in C

A nested while loop is to place one while loop inside another to perform row and column-based iterations. When working with the multi-dimensional data, we need these nested while loops.

The syntax of the nested while loop is shown below.

while (condition1)
{
while (condition2)
{
// Inner loop statements
}
// Outer loop statements
}

From the above syntax, you can see there are two while loops and one is nested inside the other.

  • The outer C while loop is the entry point to iterations, and if it is True, the compiler enters the inner while loop. This process is repeated for each iteration.
  • For each outer loop iteration, the inner loop executes completely. It means the inner loop must complete all iterations for each outer loop iteration.
  • Once all the inner loop iterations are complete, the compiler moves to the outer loop condition to check whether the condition is true. If true, repeat the process.
  • We must increment or decrement the values of both the inner and outer while loops. Otherwise, they may execute infinitely.

Multiplication Table using a nested while loop in C

The following example uses the nested while loop concept to print the multiplication tables from 1 to 5. In the program below, the first while loop keeps the i value below 6. It means the program will print multiplication tables from 1 to 5.

The inner while loop iterates from 1 to 10. On each inner while loop iteration, it multiplies i by j. Once the inner loop reaches 11, it exits the loop and moves to the outer loop with the second value.

#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
int j = 1;
while (j <= 10)
{
printf("%d ", i * j);
j++;
}
printf("\n");
i++;
}
}

Result

1 2 3 4 5 6 7 8 9 10 
2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 

TIP: Please refer to the C Program to Print Multiplication Table article.

Square Star Pattern using a nested while loop in C

A nested while loop is the most required approach to print the patterns. If you observe any pattern, it is a combination of a row and a column. So, we need the while loop to iterate over the rows and columns and print the pattern.

The following example uses a nested while loop to print a square pattern of stars. For more examples, please refer to the Star Pattern, Alphabet Pattern, and Number Pattern programs.

#include <stdio.h>
int main()
{
int i = 1, n = 5;
while (i <= n)
{
int j = 1;
while (j <= n)
{
printf("* ");
j++;
}
printf("\n");
i++;
}
}
* * * * * 
* * * * * 
* * * * * 
* * * * * 
* * * * * 

C While loop with break and continue

As we already know, the while loop iterates and executes the code inside it until the condition inside the while loop becomes true. However, when we combine the while loop with break and continue statements, we can change the natural flow.

C while loop with break statement

The break statement is an instruction to the compiler to terminate the loop immediately. We use the break statement inside a while loop to exit the loop based on a condition. It requires an if statement to provide a condition. When the condition is met, the compiler will exit the loop without checking the while loop condition.

In the following example, we used the first example that prints the natural numbers from 1 to 10 using a while loop. However, we use the break statement with a condition (n == 3). It means the program below prints 1 and 2 because when n becomes 3, the if statement inside a while loop becomes true. So, the break statement in the if block is executed, and the compiler exits the loop iteration.

#include <stdio.h>
int main()
{
int n = 1;
while(n <= 10)
{
if(n == 3) {
break;
}
printf("%d ", n);
n++;
}
}
1 2

Using a break inside a nested while loop

When working with a nested while loop in C, the break statement exits the inner loop and continues the outer while loop. In the example below, when j becomes 3, the break statement exists the inner while loop, and the compiler moves to the outer while loop to check the condition.

#include <stdio.h>
int main()
{
int i = 1;
while (i <= 2)
{
int j = 1;
while (j <= 5)
{
if (j == 3)
{
break;
}
printf("i = %d and j = %d\n", i, j);
j++;
}
i++;
}
}
i = 1 and j = 1
i = 1 and j = 2
i = 2 and j = 1
i = 2 and j = 2

TIP: To exit the outer loop, use the break statement in the outer loop (not inside the nested one).

C while loop with continue statement

The continue statement inside a while loop skips the current iteration and moves to the next iteration. In the following example, the while loop has to print the natural numbers from 1 to 5. However, we use the continue statement inside the while loop to skip number 3.

It means, when n becomes 3, the if condition becomes true and the continue statement skips that iteration and moves to the next iteration. Remember, we must update the value (n++) before the continue statement.

#include <stdio.h>
int main()
{
int n = 1;
while(n <= 5)
{
if(n == 3) {
n++;
continue;
}
printf("%d ", n);
n++;
}
}
1 2 4 5

Using break and continue inside a while loop

In the above mentioned two programs, we used the C while loop with either the break statement or the continue statement. However, we can use the combination of break and continue inside a while loop.

The following example prints the natural numbers from 10 to 1 in reverse order. However, the continue skips number 9, and the break statement exits the loop when the number becomes 5. It means the program below prints numbers from 10 to 5 and skips 9.

#include <stdio.h>
int main()
{
int n = 11;
while(1)
{
n--;
if(n == 9) {
continue;
}
if(n == 5) {
break;
}
printf("%d ", n);
}
}
10 8 7 6

How to use logical operators in a While loop in C?

In all our previous examples, we used a while loop with a single condition. However, with the help of logical operators, we can combine multiple conditions and utilize them as the while loop condition.

To demonstrate the logical operators in a while loop, we use the validate user-entered password example. However, instead of an if statement with a break condition, we use a while loop with a logical condition.

Here, the C while loop has two conditions. One checks whether the total number of attempts is less than two. The next condition checks whether the user-entered password does not match the correct one. If both are true, the compiler moves inside the while loop. If any condition fails, the compiler won’t execute a single statement inside the while block.

#include <stdio.h>
#include <string.h>
int main()
{
char password[] = "sample12345";
char str[50];
int attempts = 0;

while (attempts < 2 && strcmp(password, str) != 0)
{
printf("Enter Password = ");
scanf("%s", str);
attempts++;
}
if (strcmp(password, str) == 0)
{
printf("Successful Login");
}
else
{
printf("Wrong Password. Account Locked\n");
}
}

Result

Enter Password = admin
Enter Password = newadmin
Wrong Password. Account Locked

Let me try one more time; this time, we will enter the correct password on the second attempt.

Enter Password = ready
Enter Password = sample12345
Successful Login