while loop in Java
Syntax :
while(condition) {
group of statements;
}
Here is the program for printing a line 5 times.
package Hello;
public class WhileLoopDemo {
public static void main(String[] args) {
int i=0;
while(i<5){
System.out.println("Hello Himanshu");
i++;
}
}
}
Output :
Hello Himanshu
Hello Himanshu
Hello Himanshu
Hello Himanshu
Hello Himanshu
while loop is also used to print values no. of times until condition gets satisfied.
In the above example, int i is initialized to 0.condition is i must be less than 5 and i will increment by 1 after each cycle. in the first iteration,i=0 and i<5, the condition fulfills and print Hello Himanshu, second time i=1 and i<5, again condition fulfills and print Hello Himanshu.next i=2 and i<5 condition is ok again for printing Hello Himanshu.in the fourth iteration i=3 and i<5 condition is ok and prints Hello Himanshu, now i=4 and i<5, it also prints Hello Himanshu.but when i=5 and i<5 this condition does not match and the loop terminates.
Hence, loop prints Hello Himanshu 5 times.
Here is another program for printing numbers 1 to 10 by using while loop :
package hello;
public class WhileLoopTest {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Output :
1
2
3
4
5
6
7
8
9
10
Here is another program for printing numbers 10 to 1 by using while loop :
public class ReverseWhile {
public static void main(String[] args) {
int i =10;
while(i>0){
System.out.println(i);
i--;
}
}
}
Output :
10
9
8
7
6
5
4
3
2
1
Infinite while loop :
public class InfiniteWhile {
public static void main(String[] args) {
int i = 0;
while(true){
System.out.println(i);
}
}
}
Output :
0
0
0
0
..
..
Program for printing String by iterating through while loop :
public class StringWhile {
public static void main(String[] args) {
String str = "himanshu";
char[] chr = str.toCharArray();
int i =0;
while(i<chr.length){
System.out.println(chr[i]);
i++;
}
}
}
Output :
h
i
m
a
n
s
h
u
No comments:
Post a Comment