nested while loop in C
Sure! Here is an example of a nested while loop in C, along with explanations for each step:
#include <stdio.h>
int main() {
int i = 1;
int j = 1;
while (i <= 3) {
while (j <= 3) {
printf("i: %d, j: %d\n", i, j);
j++;
}
i++;
j = 1;
}
return 0;
}
Step 1: Initialization
In this step, we declare and initialize two variables i
and j
to 1. These variables will be used as loop counters.
int i = 1;
int j = 1;
Step 2: Outer while loop
In this step, we have an outer while loop that checks the condition i <= 3
. If the condition is true, the code inside the loop will be executed; otherwise, the loop will terminate.
while (i <= 3) {
...
}
Step 3: Inner while loop
Inside the outer while loop, we have an inner while loop that checks the condition j <= 3
. If the condition is true, the code inside the loop will be executed; otherwise, the loop will terminate.
while (j <= 3) {
...
}
Step 4: Print statement
Inside the inner while loop, we have a printf
statement that prints the values of i
and j
.
printf("i: %d, j: %d\n", i, j);
Step 5: Incrementing j
After executing the code inside the inner while loop, we increment the value of j
by 1.
j++;
Step 6: Incrementing i
and resetting j
After the inner while loop terminates, we increment the value of i
by 1 and reset the value of j
to 1.
i++;
j = 1;
Step 7: Loop continuation or termination
After executing the code inside the outer while loop, we check the condition i <= 3
. If the condition is true, the loop continues to the next iteration; otherwise, the loop terminates.
while (i <= 3) {
...
}
Step 8: Program termination
After the outer while loop terminates, we reach the end of the program and return 0, indicating successful execution.
return 0;
I hope this helps! Let me know if you have any further questions.