While Loop in C Programming
While Loop in C Programming
Introduction to While Loop in C Programming
The while loop in C programming is used to execute a block of code repeatedly as long as a given condition is true. It is useful when the number of iterations is not fixed in advance.
The while loop helps in creating dynamic and condition-based programs.
Syntax of While Loop in C Programming
// code block
}
How While Loop Works
- The condition is checked before execution
- If the condition is true, the loop body runs
- After execution, the condition is checked again
- The loop continues until the condition becomes false
Basic Example of While Loop
int main() {
int i = 1;
while(i <= 5) {
printf(“%d\n”, i);
i++;
}
return 0;
}
Example: Sum of Numbers Using While Loop
int main() {
int i = 1, sum = 0;
while(i <= 5) {
sum += i;
i++;
}
printf(“Sum = %d”, sum);
return 0;
}
Infinite While Loop
If the condition never becomes false, the loop runs forever.
printf(“Infinite Loop”);
}
Use infinite loops carefully to avoid program errors.
While Loop with User Input
int main() {
int number;
printf(“Enter a number (0 to stop): “);
scanf(“%d”, &number);
while(number != 0) {
printf(“You entered: %d\n”, number);
scanf(“%d”, &number);
}
return 0;
}
Common Use Cases of While Loop
Where While Loop is Used
- When number of iterations is unknown
- Taking user input repeatedly
- Running programs based on conditions
- Menu-driven applications
Advantages of While Loop
Key Benefits
- Simple and easy to use
- Works well with dynamic conditions
- Useful for input-based programs
- Flexible looping structure
Start Learning C Programming
Practice while loop programs to build strong logic in C programming.
Summary
The while loop in C programming executes code as long as a condition is true. It is best used when the number of iterations is not known beforehand.
FAQs
What is while loop in C programming?
It is a loop that executes code repeatedly while a condition is true.
When should we use while loop?
When the number of iterations is not known.
What is an infinite loop?
A loop that never stops because the condition is always true.
What is the difference between for and while loop?
For loop is used when iterations are known, while loop is used when they are not.



