Curriculum
The while
loop in C is a fundamental control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop will continue to execute as long as the condition evaluates to true. This tutorial will guide you through understanding and using while
loops in C programming.
while
LoopThe basic syntax of a while
loop in C is as follows:
while (condition) { // Code to execute while the condition is true }
condition: This is a Boolean expression. If the condition evaluates to true (non-zero
), the code inside the loop’s body is executed. After each iteration, the condition is evaluated again. When the condition becomes false (0
), the loop stops executing.
Let’s start with a simple example that prints numbers from 1 to 5.
#include <stdio.h> int main() { int counter = 1; while (counter <= 5) { printf("%dn", counter); counter++; // Increment the counter to avoid infinite loop } return 0; }
In this example, the while
loop checks if counter
is less than or equal to 5. If true, it prints the value of counter
and then increments counter
by 1. This process repeats until counter
exceeds 5, at which point the loop stops.
while
Loop for Input Validationwhile
loops are useful for repeating a task until a valid input is received. Here’s an example that asks the user for a positive number and repeats the prompt if the input is not valid.
#include <stdio.h> int main() { int number; printf("Enter a positive number: "); scanf("%d", &number); while (number <= 0) { printf("Invalid input. Please enter a positive number: "); scanf("%d", &number); } printf("Thank you for entering %d.n", number); return 0; }
This code will continue to prompt the user for a positive number until the entered number is greater than 0.
A while
loop can also be used to create an infinite loop by using 1
(or true
in C99 and later) as the condition. Infinite loops are useful when you want to keep a program running until an external event or condition breaks the loop.
#include <stdio.h> int main() { while (1) { // Perform tasks printf("This loop will run forever until manually stopped.n"); // Break the loop based on some condition (to avoid actual infinite looping in example) break; } return 0; }
The while
loop is a powerful tool in C for performing repetitive tasks. It’s particularly useful when the number of iterations is not known before the loop starts. Understanding and using while
loops effectively can help you write more efficient and concise C programs. Remember to carefully manage the loop condition to prevent infinite loops and ensure your program behaves as intended.