Table of Contents
In this article, we will discuss the Do-while loop in the Java programming language
Loops are an important concept in java language. It is used to multiple circulations(more than one)
in the Java, three types of basic loops available in Java
the do-while loop is like to a while loop but it is guaranteed to execute at least one time before the test expression is checked
It contains two-part
At the do-while loop, Boolean expression includes at while part – end of the loop, so the statements in the loop execute once before the boolean is checked
When control of loop checks boolean expression in the while part, if the boolean expression is true, the loop goes to do part and executed again. , this process continues until the boolean is false
Syntex
this is the syntax of the loop
do{
// statement(s);
// increments
} while (check Boolean_expression);
flow diagram of the loop
class DoWhileDemo{
public static void main(String args[]){
int x=1;
do{
System.out.println(“x is – “+x);
x++;
}while (x<11); //condition is true
}
}
When the above code is executed, it produces the following result
The following program is the same but another situation – the Test expression is false
class DoWhileDemo{
public static void main(String args[]){
int x=1;
do{
System.out.println(“x is – “+x);
x++;
}while (x>11); //condition is false
}
}
When the above code is executed, it produces the following result
do-while loop is guaranteed to execute at least one time before checking the test expression
Program 3
Calculate the sum of natural numbers using do-while loop
import java.util.Scanner; class Sum_Of_Num1{ public static void main(String args[]){ int sum=0; Scanner scan=new Scanner(System.in); //create a scanner object for input System.out.print("Enter the number as you wish: "); int num=scan.nextInt();//get input from the user for num int i=1; do{ sum+=i;//sum=sum+i; i++; }while(i<=num); System.out.println("the sum of 1 to "+num+"is: "+sum); } }
When the above code is executed, it produces the following result
Enter the number as you wish:100 the sum of 1 to 100 is:5050
Subtract two numbers using method overriding Program 1
PHP Star triangle Pattern program Here's a simple Java program that demonstrates how to print…
Using Function or Method to Write to temperature conversion: Fahrenheit into Celsius In this article,…
Function or method of temperature conversion from Fahrenheit into Celsius In this article, we will…
Write temperature conversion program: from Fahrenheit to Celsius In this article, we will discuss the…
How to write a program to convert Fahrenheit into Celsius In this article, we will…
This website uses cookies.