In this tutorial, we will learn about while loop in Java. We will cover the basics of iterative execution using while loops.
A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop runs as long as the condition evaluates to true.
The syntax for the while loop in Java is:
while (condition) {
// Code block to be executed
}
The while loop evaluates the condition before executing the loop's body. If the condition is true, the code block inside the loop is executed. This process repeats until the condition becomes false.
i
.i
to 1.public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.print(i + " ");
i++;
}
}
}
1 2 3 4 5
n
and sum
.n
.sum
to 0.n
natural numbers.public class Main {
public static void main(String[] args) {
int n = 10;
int sum = 0;
int i = 1;
while (i <= n) {
sum += i;
i++;
}
System.out.println("Sum of first " + n + " natural numbers is " + sum);
}
}
Sum of first 10 natural numbers is 55
num
.num
.rev
to 0.num
.public class Main {
public static void main(String[] args) {
int num = 12345;
int rev = 0;
while (num != 0) {
int digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
System.out.println("Reversed number is " + rev);
}
}
Reversed number is 54321