Back to C Programming
2026-07-125 min read

Example 1: while loop (C Programming)

Learn Example 1: while loop (C Programming) step by step with clear examples and exercises.

Why This Matters

Welcome to this full guide on the while loop in C programming! This tutorial is designed to help you understand how to use the while loop effectively, with practical examples and common mistakes that beginners often encounter.

The while loop is a fundamental control structure in C programming used for repetition. It allows you to execute a block of code repeatedly as long as a certain condition remains true. Understanding the while loop is crucial for solving problems, writing efficient programs, and preparing for interviews or exams that require C programming knowledge.

Prerequisites

Before diving into the while loop, you should have a basic understanding of:

  1. C syntax, including variables, operators, and expressions
  2. Control structures like if-else statements
  3. Basic input/output operations using printf() and scanf() functions
  4. Understanding the concept of arrays and pointers (as they will be useful in some examples)

Core Concept

The while loop in C programming works by repeatedly executing a block of code as long as a specified condition is true. The general syntax for a while loop is:

while (condition) {
// Code to be executed while the condition is true
}

The loop continues until the condition becomes false, at which point the program execution resumes after the loop. It's essential to ensure that the loop terminates eventually to avoid infinite loops.

Example: Printing Numbers 1-5

Here's an example of a simple while loop that prints numbers from 1 to 5:

#include <stdio.h>

int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++; // Increment the counter variable
}
return 0;
}

In this example, the loop continues as long as i is less than or equal to 5. The printf() function prints the current value of i, and then i++ increments the counter variable for the next iteration.

Example: Summing an Array's Elements

Here's a more complex example that demonstrates using a while loop to sum the elements of an array:

#include <stdio.h>

int main() {
int arr[] = {1, 2, 3, 4, 5};
int sum = 0;
int i = 0;
while (i < sizeof(arr) / sizeof(arr[0])) {
sum += arr[i]; // Add the current element to the sum
i++; // Increment the counter variable
}
printf("The sum of elements in the array is: %d\n", sum);
return 0;
}

In this example, we use a while loop to iterate through an array and sum its elements. The loop continues as long as the index i is less than the size of the array. We access each element using the array notation arr[i].

Worked Example

Let's explore a more complex example: writing a program that calculates the factorial of a given number using a while loop.

#include <stdio.h>

int main() {
int num, fact = 1;
printf("Enter a non-negative integer: ");
scanf("%d", &num);

if (num < 0) {
printf("Error! Factorial is not defined for negative numbers.\n");
return 1;
}

while (num > 1) {
fact *= num--; // Multiply the current value of `fact` by the current value of `num`, then decrement `num`
}

printf("The factorial of %d is %d\n", num, fact);
return 0;
}

In this example, the program asks for a non-negative integer and calculates its factorial using a while loop. The loop continues as long as the input number is greater than 1, multiplying the current value of fact by the current value of num and decrementing num.

Common Mistakes

  1. Forgetting to initialize the counter variable: If you don't initialize the counter variable before the loop, it will contain an indeterminate value that may lead to incorrect results or infinite loops.
  1. Not updating the counter variable inside the loop: Remember to increment or decrement the counter variable inside the loop to ensure that the condition eventually becomes false and the loop terminates.
  1. Using == instead of = for assignment: Be careful not to confuse the equality operator (==) with the assignment operator (=). Using the wrong one can lead to unexpected behavior.
  1. Infinite loops due to incorrect conditions: Ensure that your loop condition eventually becomes false to avoid infinite loops, which can cause your program to freeze or consume excessive resources.
  1. Forgetting to handle edge cases: Always consider edge cases when writing programs, such as handling zero or negative numbers in the factorial example above.

Practice Questions

  1. Write a while loop that prints the even numbers between 2 and 20.
  1. Write a program that finds the smallest prime number greater than 50 using a while loop.
  1. Implement a while loop that calculates the sum of all the numbers from 1 to n, where n is input by the user.
  1. Modify the factorial example to handle negative numbers gracefully, either by returning an error message or by defining factorials for negative numbers (if applicable).

FAQ

What happens if I forget to initialize the counter variable in a while loop?

If you don't initialize the counter variable before the loop, it will contain an indeterminate value that may lead to incorrect results or infinite loops. To avoid this, always initialize your counter variables before using them in a while loop.

How can I break out of a while loop prematurely?

You can use the break statement to exit a while loop early. When you encounter a situation where breaking from the loop is necessary, place the break statement inside your loop at an appropriate location.

Can I use a while loop for iterating through arrays in C?

While it's possible to use a while loop for iterating through arrays, the for loop is generally preferred due to its simplicity and readability when dealing with arrays. However, if you prefer using a while loop, you can do so by keeping track of the array index manually.

What are some common edge cases to consider when writing programs involving loops?

Some common edge cases to consider include handling zero or negative numbers, empty collections (such as an empty array or list), and exceptional conditions that might cause the loop to behave unexpectedly (e.g., dividing by zero). Always test your code with various inputs to ensure it handles all relevant edge cases.