Search code examples
javaalgorithmfor-loopbluej

bluej program for displaying following pattern for a school project


I have a fairly decent knowledge of Java in BlueJ programming environment. But I am at a loss to write a looping function to create this pattern. Any help or pointers would be very helpful.

    1
    3 1
    5 3 1
    7 5 3 1
    9 7 5 3 1

My code thus far...

import java.util.*;
public class scanner {
    public static void main(){
        Scanner sc = new Scanner(System.in);
        int val = 1;
        for( int i=1; i < 5; i++){
            for(int j = 1; j > i; j--){
                System.out.print(j+" ");
                if(val != 1) {
                   System.out.print(1);
                }
                val +=1;
            }
            System.out.println();
        }
    }
}

Solution

  • Your approach is too complicated. I suggest you define the key variables and use them for the algorithm. By the way, you don't need to use java.util.Scanner since you don't receive any input value from a console.

    int end = 1;
    int step = 2;
    int rows = 5;
    
    for (int i=0; i<rows; i++) {
        for (int j=0; j<i+1; j++) {
            int number = end + i*step - j*step;
            System.out.print(number + " ");
        }
        System.out.println();
    } 
    

    Output (make sure):

    1 
    3 1 
    5 3 1 
    7 5 3 1 
    9 7 5 3 1 
    

    Moreover, in your code you have the following line:

    for (int j = 1; j > i; j--) { ...
    

    This loop never allows entering its body because of the condition j > i and the j subtracting. I recommend you to debug your program and track the i and j values to understand what is going on.