Java While Loop with Example

A programming language uses control statements to control the flow of execution of a program. In Java programming, we can control the flow of execution of a program based on some conditions. Java control statements can be put into the following three categories: selection, iteration, and jump. Java iteration statements allow program execution to repeat one or more statements. Java's iteration statements are while loop, do-while loop, and for loop. These statements are commonly called loops. A loop repeatedly executes the same set of instructions until a particular condition is true.





While Loop in java:

The while loop in java is the most fundamental looping statement. Java while loop repeats a statement or a block while a particular condition is true. You can use a while loop if the number of iteration is not fixed. 


Syntax of Java while loop:


while(boolean condition){
//body of the loop.
}


The condition of a while loop can be any boolean expression. The body of the while statement will be executed if the expression evaluates to true. When the condition of while loop becomes false, control passes to the next line of the code immediately following the loop.


Flowchart of Java while loop:

Java while loop



Java While loop Example:

Here is a while statement that prints the values from 1 to 10. See the example below.

class WhileLoop{
	public static void main(String args[]){
        System.out.println("The values from 1 to 10 is: ");
		int num = 1; // initialization.
		
		// condition checking.
		while(num <= 10){
			
			System.out.println(num);
			num++; // updation.
		}
	}
}


Output:
Java while loop



You may also like these related posts:


Java While Loop with Example Java While Loop with Example Reviewed by Prashant Srivastava on December 19, 2019 Rating: 5

No comments:

Powered by Blogger.