Trusted answers to developer questions

How do you execute a for-loop in Java?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

What is a for-loop?

Imagine a situation where you have to print something a hundred times. How would you do that?

You could type the command a hundred times, or maybe copy-paste it repeatedly – but you probably wouldn’t want to.

This is where loops come into use. When using a for-loop, those hundred lines of code can be written in as few as three to four statements.

A for-loop allows a particular set of statements, written inside the loop, to be executed repeatedly until a specified condition is satisfied.

for-loop
for-loop

Syntax in Java

svg viewer

Flow Diagram

Flow Diagram
Flow Diagram

Code

This code will print out the first ten natural numbers using a for-loop in Java.

class Sample{
public static void main(String args[]) {
int start = 1; // starting condition
int end = 10; // ending condition
for (int index = start; index <= end; index++) {
System.out.println("Value of index: "+ index);
}
}
}

The loop will run ten times, printing the first ten natural numbers, until the terminating condition is met, i.e.,​ when the index is equal to ten.

RELATED TAGS

for-loop
java
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?