While loop in Java.

Java while loop is a control flow statement used to iterate a block of code repeatedly until the boolean condition present in the while loop is true. It is mainly used when we don't know the number of iteration in advance. The loop gets automatically stops when the boolean condition returns false. 
while loop in Java

Example: Write a Java Program to sum all numbers from 1 to 10 using a while loop.

public class Main
{
	public static void main(String[] args) {
		
		int i = 1, sum = 0;
		
		while(i <= 10) {
		    sum = sum + i;
		    //increment value of i for next iteration
		    i++;
		}
		System.out.println("Sum: "+sum);
	}
}
Output:
Sum: 55


Example: Write a Java Program to print all-natural numbers from 1 to 10 using a while loop. 

public class Main
{
	public static void main(String[] args) {
		
		int i = 1;
		
		while(i <= 10) {
		    System.out.print(i+" ");
		    i++;
		}
	}
}
Output:
1 2 3 4 5 6 7 8 9 10

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS