Hi there! This next lesson will be on understanding for loop in Java Programming.
The for loop statement
This type of loop will repeat Java statements for a specific number of times.
Structure:
for (initStatement; condition; updateVar) {
loopBody // yourJavaStatements
}
Where:
initStatement is used to initialize a loop variable, it is where you set the initial value of the variable.
condition it is an expression to be tested if true, once the condition is still true the loop will continue, the loop will end when the condition returns false.
updateVar this part of the for loop will execute after the loop body is done. It is where you can update the value of your variable by incrementing(++) or decrementing(–) it.
loopBody this is where you put your Java statements that you want to execute. Your Java statements will run as long the condition is true.
Example:
import java.util.*;
class forLoop{
static Scanner console = new Scanner(System.in);
public static void main(String[] args){
int num;
System.out.print("Enter a number from 1 to 10:");
num = console.nextInt();
for(int x=num; x < 10; x++) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
Explanation:
- We have declared an integer type variable which we named it as num.
- This example of for loop program will ask the user to enter a number from 1 to 10.
- We have started the for loop statement; we have initialize variable x in which its value will depend on the value entered by the user that is stored on our num variable.
- We have stated a condition that x < 10, as long as the condition is true it will execute the Java statement that will print the current value of x.
- The loop will end if the value of x is 9 which is less than 10.