0

This is my code:

for (int i = 4; i >= 1; i--) {              
    for (int j = 1; j < i; j++) {
        System.out.print(" ");
    }
    for (int k = i; k <= 4; k++) {                    
        System.out.print(k+"");
    }                                  
    System.out.println();            
}

Current output:

   4
  34
 234
1234

Desired output:

   1
  21
 321
4321

What changes are necessary in order for me to get the desired output as shown above?

5 Answers 5

1

Let the first loop (i) run from 1 to 4 and the second (j) from 4 to i. This reverses your output.

Sign up to request clarification or add additional context in comments.

Comments

1

You did every thing right, just the last for should have a very minor change:

for (int k = 5-i; k >= 1; k--){

Comments

0

Here you go:

public static void main(String[] args) {
    for (int i = 1; i <= 4; i++) {
        for (int j = 4; j > i; j--) {
            System.out.print(" ");
        }
        for (int k = i; k >= 1; k--){
            System.out.print(k + "");
        }
        System.out.println();
    }
}

Comments

0

Your loops are incorrect, you can refer the below code with inline comments:

for (int i = 1; i <= 4; i++) { //iterate from 1 to 4  
    //Loop from i+1 to insert spaces first
    for (int j = i+1; j <= 4; j++) {
        System.out.print(" ");
    }
    //Loop from i to insert the number next to each other
    for (int j = i; j >= 1; j--) {
        System.out.print(j);
    }
    System.out.println(); //insert a new line
}

Comments

0

for (int i = 1; i <= 4; i++) 
{   
  for (int k = i; k <= 4; k++)
   {                    
      System.out.print(" ");
   }  
  for (int j = 1; j < i; j++) 
   {
      System.out.print(j);
   }                                
    System.out.println();            
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.