Nest Loops, can't figure out how to encode this

Hi, I have a question that I tried to figure out in a couple of hours, I need to use nested loops to print the following

    -----1-----
    ----333----
    ---55555---
    --7777777--
    -999999999-

This is what I still have.

    public static void Problem6 () {
        System.out.println("Problem 6:");
        for (int i = 1; i <= 5; i++) {
            for (int j = 5; j >= i; j--) {
                System.out.print("-");
            }
            for (int j = 1; j <= 9; j += 2) {
                System.out.print(j);
            }
            for (int j = 5; j >= i; j--) {
                System.out.print("-");
            }
            System.out.println();
        }
    }

This is what it prints.

    -----13579-----
    ----13579----
    ---13579---
    --13579--
    -13579-
+5
source share
2 answers

You have the right number of dashes, you just do not print the number correctly. Let's look at why this is:

Which loop prints the numbers? The second nested loop.

What is he doing? It prints jwhere it jchanges from 1to 9, and jincreases by 2 each iteration of the cycle. In other words, 1, 3, 5, 7, 9that is confirmed at your exit

? . , 1 first. , 3 . , 5 . .

? , , , (1, 3, 5,... i) (1, 3, 5,... i).

edit. . - , , . 3 , 5 , . - , ... . .

, . , , , .

+8
public    class    pattern
{
    public    static    void    main   (    )
    {
        for    (int   i =  1;i<=9;i+=2)
        {
            for(int b = 9;b>=i;b-=2)
            {
                System.out.print(" ");
            }
            for(int j =1;j<=i;j++)
            {
                System.out.print(i);
            }
            System.out.println();
        }
    }
}
-1

All Articles