Skip to content
Advertisement

How do I fix it to output what I want to output?

I recently started coding in Java, I just started a week ago. The previous post was deleted because I did not specify it enough, I am sorry for that. I’ve been having troubles with for, do and while statements, and how do I output the same results in the expected outputs that I have typed in? With the use of while or do or for only.

Current code:

public class Main {
    public static void main(String[] args) {
        for(int row = 3;row <= 7;row++) {
            String spc = "  ";
            for(int column = 1; column <;= 3; column++) {
                System.out.print(column * row + spc);
            }
            System.out.println();
        }
    }
}

Current outputs:

3  6  9  
4  8  12  
5  10  15  
6  12  18  
7  14  21  

Expected outputs:

Set 1

3
4 6
5 8 11
6 10 14 18
7 12 17 22 27

Set 2

3 8 13 18 22
2 6 10 14 
1 4 7
0 2
-1

I’m really having a hard time in solving this problem, any help will be very appreciated! Thank you 🙂

Advertisement

Answer

Here’s a solution to your problem. I started with a row number, 1..5. Then, I figured out from that value how many times I needed to perform the inner loop based on the row number. Once I’m iterating the right number of times in the inner loop, then it’s just a matter of making the math come out right to give the numbers you desire:

public static void main(String argv[]) {
    for (int row = 1 ; row <= 5 ; row++) {
        String str = "";
        for (int term = 0 ; term < row ; term++) {
            str += ((row + 2) + row * term) + " ";
        }
        System.out.println(str);
    }

    System.out.println();

    for (int row = 5 ; row >= 1 ; row--) {
        String str = "";
        for (int term = 0 ; term < row ; term++) {
            str += ((row - 2) + row * term) + " ";
        }
        System.out.println(str);
    }
}

Result:

3 
4 6 
5 8 11 
6 10 14 18 
7 12 17 22 27 

3 8 13 18 23 
2 6 10 14 
1 4 7 
0 2 
-1 

NOTE: I’m confident that the first line of the second set should end in 23, not 22 as you show as the desired output.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement