Table of Contents
In this article, we will discuss the While loop in Java programming language.
In this post, we are going to learn how to use while loop in Java programming language
loops are used to execute a block of code as long as a specified condition is satisfied.
Java program has three types of basic loops
}
In while loop, the test condition is evaluated first and if it returns true then executes inside the body of the statement. if condition returns false, The flow of control goes out of loop body.
class Whiledemo{
public static void main(String args[]){
int x;
x=1;
while(x<=10)
{
System.out.println("x is " + x);
x++;
}
}
} When the above code is executed, it produces the following result
import java.util.Scanner;
class Sum_Of_Num{
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;
while(i<=num){
sum+=i; //sum=sum+i;
i++;
}
System.out.println("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 sum of 1 to 100 is:5050
Example 3
import java.util.Scanner;
class While_Display{
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;
while(i<=num){
System.out.println("This while loop displays "+i+" times");
i++;
}
}
} When the above code is executed, it produces the following result
Enter the number as you wish: 12 This while loop displays 1 time This while loop displays 2 time This while loop displays 3 time This while loop displays 4 time This while loop displays 5 time This while loop displays 6 time This while loop displays 7 time This while loop displays 8 time This while loop displays 9 time This while loop displays 10 time This while loop displays 11 time This while loop displays 12 time
Output
1
2
3
4
5
6
7
8
……..
………
never end;
Above is the infinite while loop in Java. Test condition is never satisfied. So program flow never ends.
Related Articles
Multiply two numbers in Java using scanner| 5 different ways In this article, we will…
5 Different ways to Divide two numbers in Java using scanner In this article, we…
Learn 8 Ways to Subtract Two Numbers Using Methods in Java In this article, we…
10 ways to subtract two numbers in Java In this article, we will discuss the…
Java Code Examples – Multiply Two Numbers in 5 Easy Ways In this article, we…
How to Divide two numbers in Java| 5 different ways In this article, we will…
This website uses cookies.