Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

For Loop Additional Notes and Activities

Flow of Execution of the for Loop

First step: In for loop, initialization happens first and only one time, which
means that the initialization part of for loop only executes once.

Second step: Condition in for loop is evaluated on each iteration, if the


condition is true then the statements inside for loop body gets executed. Once
the condition returns false, the statements in for loop does not execute and the
control gets transferred to the next statement in the program after for loop.

Third step: After every execution of for loop’s body, the increment/decrement
part of for loop executes that updates the loop counter.

Fourth step: After third step, the control jumps to second step and condition
is re-evaluated.

Example:

public class ForLoopExample {

public static void main(String args[]){

for(int i=10; i>1; i--){

System.out.println("The value of i is: "+i);

Output:

The value of i is: 10

The value of i is: 9

The value of i is: 8

The value of i is: 7


The value of i is: 6

The value of i is: 5

The value of i is: 4

The value of i is: 3

The value of i is: 2

Explanation of the code:

int i=1 is initialization expression


i>1 is condition(Boolean expression)
i– Decrement operation

Activity 1: For Loop Syntax. Fill in the blanks to make the block of code work.
Save the file as LastnameFirstnameForLoop.pdf.

1.

public (1)___________ ForLoopActivity1 {

(2)__________ static void main(String[] args) {

for((3)_________ i=1; i<= 5 ;i++){

(4)__________(int j=0; j < i; (5)________){

System.out.print("*");

System.out.println("");

}
Expected Output:

**

***

****

*****

2.

(1)______ class ForLoopActivity2 {

public static void main(String[] args) {

(2)_________(int i=5; (3)________ ;i--){

(4)________(int j=0; j < i; j++){

(5)_________("*");

System.out.println("");

Expected Output:

*****

****

***
**

Activity 2. The previous activity shows the generation of two star pyramids. In
this activity, create two pyramids consisting of numbers with the use of For
Loop. Place both codes in one file.

1. Using For Loop, create a program to generate a pyramid consisting of


numbers. Use the class name(file name) LastnameForLoop1

Expected Output:

12

123

1234

12345

2. Using For Loop, create a program to generate an inverted pyramid consisting


of numbers. Use the class name(file name) LastnameForLoop2

Expected Output:

12345

1234

123

12

You might also like