Search code examples
javawhile-loopnested-loops

How can I stack up the number patterns with while loop in java?


Dear Professionals! I'm a super beginner of programming java. I'm just learning a basic stuff in school. While I'm doing my homework, I'm stuck in one problem.

The question is Using nested loops to make this stack-up number pattern:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10

I can only use while loop (because we haven't learned for or do loops yet), and the outer loop body should execute 10 times. I can use print and println for making this pattern.

I tried many different methods with while loop, but I can't figure it out.

Please, please give me some hint.

This is the code that I'm working on it so far:

class C4h8
{
    public static void main(String[] args)
    {
        int i, j;

        i = 1;
        while(i <= 10)
        {
            j = 1;
            while (j <= 10)
            {

                System.out.print(j);
                j++;

            }


            System.out.println();
            i++;

        }

    }
}

but it only displays:

12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910

My question may look like a silly one, but I'm really struggling with it because like I mentioned, I'm a super beginner.. Please help me, so that I can learn and move on!

Thank you so much!


Solution

  • Use the following: You need to limit the variable j by variable i to achieve your output

    class C4h8
    {
        public static void main(String[] args)
        {
            int i, j;
    
            i = 1;
            while(i <= 10)
            {
                j = 1;
                while (j <= i) // limit the variable j by i 
                {
    
                    System.out.print(j+" ");
                    j++;
    
                }
    
                System.out.println();
                i++;
    
            }
        }
    }