Java Simple for Loop Example demonstrates the usage of for loop in Java with an example.
Java for Loop Syntax
for (initialization; termination;
increment) {
statement(s)
}
- The initialization expression initializes the loop; it's executed once, as the loop begins.
- When the termination expression evaluates to false, the loop terminates.
- The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
Simple for Loop Example
package net.javaguides.corejava.controlstatements.loops;
public class ForLoopExample {
public static void main(String args[]) {
// here, n is declared inside of the for loop
for (int n = 10; n > 0; n--)
System.out.println("tick " + n);
}
}
Output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
Find prime number using for loop example
Here is a simple program that tests for prime numbers:
package net.javaguides.corejava.controlstatements.loops;
public class ForLoopFindPrime {
public static void main(String args[]) {
int num;
boolean isPrime;
num = 14;
if (num < 2)
isPrime = false;
else
isPrime = true;
for (int i = 2; i <= num / i; i++) {
if ((num % i) == 0) {
isPrime = false;
break;
}
}
if (isPrime)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}
Output:
Not Prime
Using the Comma
There will be times when we will want to include more than one statement in the initialization and iteration portions of the for loop.
For example, consider the loop in the following program:
package net.javaguides.corejava.controlstatements.loops;
public class ForLoopComma {
public static void main(String args[]) {
int a, b;
for (a = 1, b = 4; a < b; a++, b--) {
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}
Output:
a = 1
b = 4
a = 2
b = 3
Reference
Control Statements
Java
Java Tutorial
Comments
Post a Comment