Syntax For Loop :
for (initialization; condition ; increment/decrement(iteration)) { Statement1 Statement2 . . . StatementN
}
Example:
public class JavaApplication16Java {/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int n;
for( n=10; n> 0; n-- ){
System.out.println(n);
}
}
}
-----------------------------output--------------------------
Here this is decrement.
10
9
8
7
6
5
4
3
2
1
BUILD SUCCESSFUL (total time: 0 seconds)
this is the example of increment:
public class JavaApplication16Java {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int n;
for( n=10; n> 0; n++ ){
System.out.println(n);
}
}
output:
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
-------
------
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
You can also see 'break' to exit a loop:
public static void main(String[] args) {
int n;
for( n=0; n< 10; n++ ){
if(n==5)break;
System.out.println("n:"+n);
}
}
}
output--------------------
n:0
n:1
n:2
n:3
n:4
BUILD SUCCESSFUL (total time: 0 seconds)
Continue Loop:
public static void main(String[] args) {
int n;
for( n=0; n<10; n++ ){
System.out.print(n+"");
if(n%2==0) continue;
System.out.println("");
}
}
}
--------------output--------------------
01
23
45
67
89
BUILD SUCCESSFUL (total time: 5 seconds)
No comments:
Post a Comment