For Loop
Lesson 7 of 11 in Coddy's Control Statements in Java course.
From the introduction lesson, you might have understood What is a loop? It is executing a particular code repeatedly.
Sometimes we need to execute the block of code repeatedly while some conditions evaluate to true.
The for loop is used to iterate a part of the program several times.
If the number of iterations (repetition times) is fixed, then use for loop
It consists of four parts:
- Initialization: The initial condition is where the loop starts from.
- Condition: second condition, which is executed each time to test the condition of the loop.
- Increment/Decrement: It increases or decreases the variable's value.
- Statement: The statement is to be executed each time until the condition is false.
Syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
} Challenge
EasyWrite a program that uses for loop and prints the string "Hello " 5 times. Make sure you have a space after each Hello and you do not need to print it on new line every time.
Try it yourself
class PrintHello {
public static void printHello() {
// Write code here
}
}All lessons in Control Statements in Java
1What are Control Statements?
Introduction2Decision Making Statments
Simple if Statementif-else Statementif-else-if StatementNested if-StatementSwitch Case Statement