The simplest form of the for
loop is shown here:
for(initialization; condition; iteration) statement;
initialization
sets a loop control variable to an initial value.
condition
is a Boolean expression that tests the loop control variable. condition
is true, the for loop continues to iterate. condition
is false, the loop terminates. iteration
determines how the loop control variable is changed each time the loop iterates. Here is a short program that illustrates the for loop:
public class Main {
public static void main(String args[]) {
int i;
for (i = 0; i < 10; i = i + 1)
System.out.println("This is i: " + i);
}
}
This program generates the following output:
This is i: 0
This is i: 1
This is i: 2
This is i: 3
This is i: 4
This is i: 5
This is i: 6
This is i: 7
This is i: 8
This is i: 9
i
is the loop control variable.
i
is initialized to zero in the initialization. This process continues until the conditional test is false.
The following code loops reversively:
public class Main {
public static void main(String args[]) {
for (int n = 10; n > 0; n--)
System.out.println("n:" + n);
}
}
The output:
n:10
n:9
n:8
n:7
n:6
n:5
n:4
n:3
n:2
n:1
It is possible to declare the variable inside the initialization portion of the for.
public class Main {
public static void main(String args[]) {
for (int n = 10; n > 0; n--){
System.out.println("tick " + n);
}
}
}
The output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
The scope n ends when the for statement ends. Here is a program that tests for prime numbers using for loop statement.
public class Main {
public static void main(String args[]) {
int num;
boolean isPrime = true;
num = 50;
for (int i = 2; i <= num / 2; i++) {
if ((num % i) == 0) {
isPrime = false;
break;
}
}
if (isPrime)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}
The output:
Not Prime
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |