Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

for-loop
java

How do you execute a for-loop in Java?

Educative Answers Team

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.

svg viewer
for-loop

Syntax in Java

svg viewer

Flow Diagram

svg viewer
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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring