Menu
Coddy logo textTech

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:

  1. Initialization: The initial condition is where the loop starts from. 
  2. Condition: second condition, which is executed each time to test the condition of the loop.
  3. Increment/Decrement: It increases or decreases the variable's value.
  4. 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 icon

Challenge

Easy

Write 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