for loop in Java
There are 3 basic loops in Java :
1) for loop
2) while loop
3) do-while loop
1) for loop :
Syntax :
for(initialization ,condition,increment){
group of statements
}
Here is the program for printing a line 5 times using for loop :
package Hello;
public class ForLoopDemo {
public static void main(String[] args) {
for(int i=0;i<5;i++){
System.out.println("Hello Himanshu");
}
}
}
output :
Hello Himanshu
Hello Himanshu
Hello Himanshu
Hello Himanshu
Hello Himanshu
let's see the description of the program :
As we have seen in output Hello Himanshu print 5 times. first time condition is checked as i=0 and i<5, the condition fulfills and the loop operates and print Hello Himanshu one time. the second-time condition will be i=1 and i<5. the second condition also gets satisfied and the loop operates again and prints Hello Himanshu a second time. now, i=2 and i<5, the condition is ok and prints Hello Himanshu third time. similarly, i=3 and i<5 condition is ok for printing Hello Himanshu, then i=4 and i<5 condition is ok and again it prints Hello Himanshu than i=5 and i<5, here condition fails and the loop terminates.
thus this loop prints Hello Himanshu 5 times.
we can increase or decrease the printing counts by varying the condition of for loop.
for-loop plays a very important role in java programming. so it's really important to understand the concept of for loop.
Here is another program for printing numbers 1 to 10 by using for loop :
package hello;
public class ForLoopTest {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Output :
1
2
3
4
5
6
7
8
9
10
Here is a program for printing numbers 10 to 1 by using for loop :
public class ReverseFor {
public static void main(String[] args) {
for(int i=10;i>=1;i--){
System.out.println(i);
}
}
}
Output:
10
9
8
7
6
5
4
3
2
1
Program to read String by using for loop :
public class ReadString {
public static void main(String[] args) {
String s = "himanshu";
char[] c= s.toCharArray();
for(int i=0;i<c.length;i++){
System.out.println(c[i]);
}
}
}
Output :
h
i
m
a
n
s
h
u
Infinite for loop example :
public class InfiniteForLoop {
public static void main(String[] args) {
for(;;){
System.out.println("Himanshu");
}
}
}
Output :
Himanshu
Himanshu
Himanshu
................
................
We can also iterate arrays by using 'enhanced for loop'.Basically, this loop is used for iterate Collections.
public class EnhancedFor {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
for(int num : arr){
System.out.println(num);
}
}
}
Output :
1
2
3
4
5
Another enhanced for loop example for String array.
public class EnhancedForString {
public static void main(String[] args) {
String[] arr = {"h","i","m","a","n","s","h","u"};
for(String str : arr){
System.out.println(str);
}
}
}
Output:
h
i
m
a
n
s
h
u
No comments:
Post a Comment