Table of Contents
while loop programs in java
introduction of this article
In this topic, We will discuss some concept of while loops such as the introduction of the while loop, Syntex of while loop flow diagram of while loop and example programs for while loop
what is while loop
It executes a block of statements repeatedly until the condition (Boolean expression) is satisfied. it is similar for loop
The usage of while loop in Java have been explained using Given some programs
Syntax of while loop
while(test_Expression){ //codes inside body of while loop }
Flow diagram of while loop
Example programs in while loop
program1
class while_Loop1{ public static void main(String args[]){ int x=1; //variable declaration and initialization while(x<=10){ System.out.print(x);//display value of x x++; } } }
When the above code is compiled and executed, it produces the following result:
program2
When the above code is compiled and executed, it produces the following result:
class while_Loop1{ public static void main(String args[]){ int x=1; //variable declaration and initialization while(x<=10){ System.out.println(x);//display value of x x++; } } }
When the above code is compiled and executed, it produces the following result:
1
2
3
4
5
6
8
9
10
Program 4
Sum of the numbers using while loop
class sumofnumwhile{ public static void main(String args[]){ int sum=0,i=100; while(i != 0){ sum+=i; //sum=sum+int i--; } System.out.println("Sum of 1 to 100 is:"+sum); } }
When the above code is compiled and executed, it produces the following result:
Sum of 1 to 100 is:5050
nested while loop
program 1
1111
2222
3333
4444
How to print above pattern using while in java?
class starregtangle { public static void main(String arg[]){ int x=1; while (x<5){ // outer while loop int y=4; while(y>=1){ // inner while loop System.out.print(x); y--; // Decrement value by 1 } System.out.println(""); x++; } } }
When the above code is compiled and executed, it produces the following result:
output
while loop pattern 1
1
21
321
4321
54321
654321
How to print above pattern using while in java?
class whilepat1{ public static void main(String args[]){ int i = 1; int j = 1; int k = 1; int max = 7; while (i < max) { k = 1; while (k < max - i) { System.out.print(' '); ++k; } while (j > 0) { System.out.print(max - (max - j)); --j; } ++i; j+=i; System.out.println(""); } System.out.println(""); } }
When the above code is compiled and executed, it produces the following result:
output
while loop pattern 2
123456
12345
1234
123
12
1
How to print above pattern using while loop in Java
public class whilepat2 { public static void main(String[] args){ int i = 1; int j = 1; int k = 1; int max = 7; int max2 = 8; int tmp = 0; while (i < max) { k = 1; while (k < max - (max - i)) { System.out.print(' '); ++k; } tmp = max2 - i; j = 1; while (j < tmp) { System.out.print(max - (max - j)); ++j; } ++i; System.out.println(""); } } }
When the above code is compiled and executed, it produces the following result: