Introduction
In this article, I am going to print the numbers from 1 to 50 using a do-while loop in java. This is a very simple program. Before writing this program, you must know the use of the do-while loop. So, see the following syntax.
Also Read: Perfect Number in C Programming using All Loops
do
{
body of do loop
}
while(condition);
From the above syntax, you can see there is body of do loop followed by while keyword. Body of do loop is nothing but set of instructions that we need to repeat. So, first this body will be executed and then the while condition will be executed. If this condition is true, then control will transfer to the beginning of the do loop and again that body will be executed. This will be repeated until the condition of while become false.
Also read: Switch Case in C Program to Calculate Area of Circle and Triangle
Java Program to print 1 to 50 using do while loop
class MyLoop
{
public static void main(String args[])
{
int i=1;
do
{
System.out.println(i);
i++;
}
while(i<=50);
}
}
In the above program, we have declared and initialized the variable i=1. The value 1 is taken because we have to print from the number 1. In the body of do loop, we have written two statements: One statement is printing the current value of i and the another statement i.e. i++ is incrementing the value of i by 1 for every iteration. So, these two statements will be repeated until the value of i becomes 50.
Also Read: C Program to Display Numbers From 1 to n Except 6 and 9
We are checking whether the value of i is less than or equal to 50 in the while expression. This expression will decide whether the control will transfer to the beginning of the loop or go to the next statement.
The above java program is limited to print only numbers from 1 to 50 using do while loop. Now, I am going to change the above program. See the modified version of the above program where we can ask the user to enter the range to display the series of numbers. See the following expected output.
Expected Output

From the above output, I am writing a new program. It is just a modified version of the above program. We can print the same output using the following program.
Also read: C Program to Find the Sum of Cubes of Elements in an Array
Java Program to Print the number within a given range.
import java.util.*;
class MyLoop
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number");
int fnum=sc.nextInt();
System.out.println("Enter the last number");
int lnum=sc.nextInt();
int i=fnum;
do
{
System.out.print(i+" ");
i++;
}
while(i<=lnum);
}
}
In the above program, I am reading the values from the user using the Scanner class. I hope, you like this post.
Thank you.
Also Read: Java Program to Find Whether a Person is Eligible to Vote or Not