A programming language uses control statements to control the flow of execution of a program. In Java programming, we can control the flow of execution of a program based on some conditions. Java control statements can be put into the following three categories: selection, iteration, and jump. Java iteration statements allow program execution to repeat one or more statements. Java's iteration statements are while loop, do-while loop, and for loop. These statements are commonly called loops. A loop repeatedly executes the same set of instructions until a particular condition is true.
Java For Loop:
The for loop in java is used to iterate a part of the program several times. The java for loop is a compact way to iterate over a range of values. The Java for loop consumes initialization, condition, and increment/decrement in one line. If the number of iteration is fixed, then it is recommended to use for loop.
Syntax of Java for loop:
for(initialization; condition; incr/decr){
//body of the loop.
}
initialization: The initialization expression initializes the loop; it's executed once, as the loop begins. Here, you can initialize the variable or you can use an already initialized variable.
condition: In this step, we can check the condition. If the condition is true, then the body of the loop is executed otherwise not. If the termination expression evaluates to false, the loop terminates.
increment/decrement: In this step, we can increment or decrement the value of a variable.
Flowchart of Java for loop:
Java for loop example:
Here is a for statement that prints the values from 1 to 10. See the example below:
class ForLoop{
public static void main(String args[]){
System.out.println("The values from 1 to 10 is: ");
// initialization; condition; incr/decr.
for(int i = 1; i<=10; i++){
System.out.println(i);
}
}
}
Output:
You may also like these related posts:
Java For Loop with Example
Reviewed by Prashant Srivastava
on
December 19, 2019
Rating:
No comments: