Slider

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.
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
0

No comments

Post a Comment

both, mystorymag

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by templateszoo