while loop in c programming
Mastering While Loops in C
The "while" loop in C programming is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true. Its syntax is as follows:
while loop is nothing but, it is iterative control statement, while loop includes two-part only condition & body of while loop
Syntax:
The "while" loop works in the following way:
- The condition is evaluated. If it is true, the code inside the loop is executed. If it is false, the loop is terminated, and control is transferred to the next statement after the loop.
- After executing the code inside the loop, the condition is checked again.
- If the condition is still true, the code inside the loop is executed again. This process repeats until the condition becomes false.
Example that prints the numbers from 1 to 5 using a "while" loop:
#include
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Output: 1 2 3 4 5
In this example, the loop starts with the initialization of i as 1. The condition i <= 5 is checked, and if it is true, the code inside the loop is executed. After each iteration, i is incremented by 1 (i++).
You can modify the condition and the code inside the "while" loop to suit your specific requirements. Be cautious to ensure the condition eventually becomes false; otherwise, you might end up with an infinite loop.
What is do while in c programming
Difference between for and while loop
Related program
write a c program to print available prime numbers between 50 to 100 using a while loop
write a c program to print available Palindrome numbers between 50 to 100 using a while loop