while loop in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance.Here's the syntax for a while
loop in C:
cwhile (condition) { // Code to be executed}
Here's how a while loop works:
1. The condition inside the while is evaluated.
2. If the condition is true, the code block inside the while is executed.
3. After executing the code block, the condition is evaluated again.
4. If the condition is still true, the code block is executed again, and this process continues until the condition becomes false.
5. Once the condition becomes false, the loop terminates, and program control moves to the next statement after the while loop.
2. If the condition is true, the code block inside the while is executed.
3. After executing the code block, the condition is evaluated again.
4. If the condition is still true, the code block is executed again, and this process continues until the condition becomes false.
5. Once the condition becomes false, the loop terminates, and program control moves to the next statement after the while loop.
- Flowchart of while loop in CExample of the while loop in C language:c#include <stdio.h>int main() {int i = 1; // Initialize a variablewhile (i <= 5) { // The conditionprintf("This is iteration %d\n", i);i++; // Increment the variable}return 0;}
Output:
csharpThis is iteration 1This is iteration 2This is iteration 3This is iteration 4This is iteration 5Here's an example of a
while
loop in C that counts from 1 to 5:c#include <stdio.h>int main() {int count = 1;while (count <= 5) {printf("%d\n", count);count++;}return 0;} - Output:12345
0 Comments