In this post, we will discuss how to print n natural number using all three loops in java. We already discuss how loops work and their syntax you can check here.
Here is an example of how you can use all three loops (for loop, while loop, and do-while loop) in Java to print the natural numbers from 1 to 10:
For Loop:
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
While Loop:
int i = 1;
while (i <= 10) {
System.out.println(i);
i++;
}
Do While Loop
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 10);
In all the examples, the loop starts at the number 1, and continues to execute until the value of i is greater than 10, incrementing the value of i by 1 each time. Within the loop, the current value of i is printed to the console using the System.out.println(i) statement.
The for loop, while loop, and do-while loop are all types of looping structures in Java that allow you to execute a block of code multiple times.
The for loop is used when you know the number of iterations the loop will execute in advance. In the example, the for loop starts with an initialization statement int i = 1, which initializes the variable i with the value of 1. Then the condition i <= 10 is given and will check this condition before every iteration, if this condition is true the loop will execute and increment the value of i by 1, in this case, it will increment the i by 1 in every iteration. The increment statement is given in the for loop itself i++ which increments the value of i after every execution.
The while loop is used when you don't know the number of iterations the loop will execute in advance. In the example, the while loop starts with an initialization statement int i = 1, which initializes the variable i with the value of 1. Then the condition i <= 10 is given and will check this condition before every iteration, if this condition is true the loop will execute. The increment statement i++ is given after the execution of the loop.
The do-while loop is similar to the while loop, but it is guaranteed to execute at least once, even if the condition is false. In the example, the do-while loop starts with an initialization statement int i = 1, which initializes the variable i with the value of 1. Then the condition i <= 10 is given and will check this condition after every iteration, if this condition is true the loop will execute. The increment statement i++ is given after the execution of the loop.
In all the examples, the loop starts at the number 1, and continues to execute until the value of i is greater than 10, incrementing the value of i by 1 each time. Within the loop, the current value of i is printed to the console using the System.out.println(i) statement.
إرسال تعليق