In java, for loop is a type of control statement which iterates the particular portion or part of the program multiple times. for loop contains the initialization, condition, and increment/decrement which make it small and easy to debug.
Syntax
Parts of for loop
1. Initialization: Expression which initializes the loop counter.
Example:
int i = 1;
2. Test: This expression is responsible for the test condition. if the condition is true then we will execute the body of the loop and move to update the expression. else we will exit from the loop.
Example:
i<=10
3. Update Expression: After executing the loop body, this expression increment/decrement the loop variable.
Flow chart for loop (For Control Flow):
Example 1: This program will try to print “Hello World” 6 times.
// Java program to illustrate for loopclass forLoopDemo {public static void main(String args[]){// Writing a for loop// to print Hello World 5 timesfor (int i = 1; i <= 6; i++)System.out.println("Heelo World");}}
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Example 2: The following program prints the sum of x ranging from 1 to 10.
Code
public class sumofnumbers {
public static void main(String args[]){
int sum = 0;
for (int i=1;i<=10;i++){
sum = sum+i;
}
System.out.println("Sum "+sum);
}
}
Output
Sum 55
Enhanced For Loop or Java For - Each Loop
Another version of for loop introduced n Java 5. Enhanced for loop gives an easy way to iterate through the elements of a collection or array. It is flexible and should be used only with the array.
Syntax
for (T element:Collection obj/array){// loop body// statement(s)}
Example
public class enhancedforloop {public static void main(String args[]){String array[] = { "Sam", "Henry", "Kick" };// enhanced for loopfor (String x : array) {System.out.println(x);}/* for loop for same functionfor (int i = 0; i < array.length; i++){System.out.println(array[i]);}*/}}
Output
Sam
Henry
Kick
0 Comments