AlgoCademy
Lesson
Code

For Loop - Execution Flow in {lang}


{lang} uses the brackets ({}) to indicate which lines of code are part of a for loop and which are not.

Take this code for example:

String[] languages = {"Python", "Java", "JavaScript"};

for (String language : languages) {
  System.out.println("I love " + language);
  System.out.println("I want to get better at it");
}

Both System.out.println statements are part of the loop since they are written inside the brackets.

This means that both messages will be printed for every language in the languages list. The output of that code would be:

I love Python
I want to get better at it
I love Java
I want to get better at it
I love JavaScript
I want to get better at it

As for this code:

String[] languages = {"Python", "Java", "JavaScript"};

for (String language : languages) {
  System.out.println("I love " + language);
}
System.out.println("I want to get better at them");

The System.out.println("I want to get better at them"); is not part of the loop.

This means that only System.out.println("I love " + language); will be executed for every language in the languages list.

Then, when the for loop is over, the System.out.println("I want to get better at them"); will be executed only once.

The output of this program would be:

I love Python
I love Java
I love JavaScript
I want to get better at them

Execution flow

Lastly, note that the execution of a program always begins on the first line. The code is then executed one line at a time from top to bottom. This is known as execution flow and is the order a program in {lang} executes code.

For example, this program:

String[] fruits = {"banana", "apple", "kiwi"};

System.out.println("I'm hungry!");

for (String fruit : fruits) {
  System.out.println("I'm gonna eat:");
  System.out.println(fruit);
}
  

System.out.println("I love my life!");

prints:

I'm hungry!
I'm gonna eat:
banana
I'm gonna eat:
apple
I'm gonna eat:
kiwi
I love my life!


Assignment:

Add a for loop inside our code in the editor such that the final program would print:

Today we'll learn about:
Python
Java
JavaScript
Let's code!