5 Minutes of Java (9. Write a For loop for a given output)

One common question we often encounter is to write a for loop for a given output.

Output example:

number 1
number 2
number 3
number 4
number 5
number 6

We will follow a 5-step process to come out with a For loop.

Step 1: write a program without using while/for loop

System.out.println(“number 1”);
System.out.println(“number 2”);
System.out.println(“number 3”);
System.out.println(“number 4”);
System.out.println(“number 5”);
System.out.println(“number 6”);

Step 2: Identify the constant part and the variable part

constant and variable

System.out.println(“number 1”);
System.out.println(“number 2”);
System.out.println(“number 3”);
System.out.println(“number 4”);
System.out.println(“number 5”);
System.out.println(“number 6”);

 

Step 3:  Use a variable to replace the variable part

System.out.println("number "+n);

Step 4: Identify the starting number, the ending number and the step/update

  • start: 1
  • end: 6
  • step/update: +1 (add 1 every time)

Step 5:  Construct a for loop

for(int n=1; n <= 6; n++)
{
   System.out.println(“number “+n);
}

Let’s recap the 5-step process again:

  • Write a program without using for loop
  • Identify the constant part and the variable part
  • Use a variable to replace the variable part
  • Identify the starting number, the ending number and the step/update
  • Construct a for loop