Click here to Skip to main content
15,443,281 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
this should be the output pattern

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

but my code outputs this

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

so would i use another inside for loop?
this is my code:


public class Mod1_Act1 
    
{ 
    public static void main(String[] args) 
    {
        int rows = 9;
          
        for (int x = 1; x <= rows; x++) 
        { 
            for (int y = x; y >= 1; y--)
            {
                System.out.print(y+" ");
            }
            System.out.println();
        }         
    }
}


What I have tried:

i tried changing i and j but it only messes things up
Posted
Updated 28-Apr-21 4:44am
v2
Comments
Richard MacCutchan 28-Apr-21 7:48am    
You just need to reverse the order of the digits each line. So on the odd lines you count up from 1, and on the even lines you count down from the previous high number.

Look at the pattern you need to print, and compare it to what your code produces.
It needs every second row printed in reverse: so the simplest way is to have a flag which toggles each time, and check it inside the outer loop. If it's set to "Forward" then print formwards (y runs from 1 to x). If it's set to "Reverse", then add a second loop which goes backwards (y runs from x to 1).

Give it a try - it's not complicated!
 
Share this answer
 
Comments
CPallini 28-Apr-21 7:49am    
5.Simpler is better.
You need a way to distinguish between odd rows (that should contain the numbers in their 'natural order') and even rows (that, should contain the number in their 'reverse order').
You can do that using (x % 2) which returns 1 for odd rows and 0 for even rows. Then, you might note that printing y is 'reverse order', while printing (rows+1-y) is 'natural order'.
 
Share this answer
 
Quote:
How do I do this pattern

you already done most of the job, now you need to alternate lines forward and backward.
Java
public class Mod1_Act1 
    
{ 
    public static void main(String[] args) 
    {
        int rows = 9;
          
        for (int x = 1; x <= rows; x++) 
        { 
            if (x % 2 == 1)
            {
                System.out.print("Forward");
            }
            else {
                System.out.print("Backward");
            }
            System.out.println();
        }         
    }
}

You should be able to complete the code.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900