简体   繁体   中英

Pattern formation using Java

I am trying to print a pattern of numbers in inverted triangle using Java. I have tried many times by using different conditions but couldn't get exactly the same type of pattern. Sometimes the order of number gets changed or sometimes the number of spaces before the numbers gets changed. This is the basic structure of my code:

import java.io.*;
import java.util.*;

class S
{
    public static void main (String args [])
    {
        int no = (int)(Math.random() * 10);
        for (int x = no; x >= 1; x--)
        {
            for (int y = no; y >= 1; y--)
            {
                if ()
                    System.out.print(y) ;
                else ()
                    System.out.print (" ");
            }
            System.out.println();
        }
    }
}

The expected result is:

5 4 3 2 1
  5 4 3 2
    5 4 3
      5 4
        5

I can't get the proper condition that should come in if and else . I tried many but can't get the following pattern as it is.

How can we print pattern like this in Java

Can someone suggest what should come under the if and else coditions to get this pattern.

You don't actually need any special conditions, you can answer your question just by using your loops.

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

This should give you the correct output, all you need to do now is your formatting.

check this::: just add a special integer i:

import java.io.*;
import java.util.*;

class S
{
public static void main (String args [])
{
    int no = (int)(Math.random() * 10);
    int i = 0;
    for (int x = no; x >= 1; x--)
    {
        for (int y = no; y >= 1; y--)
        {
            if (x > y){
                System.out.print((y+i)+" ") ;
            }
            else{
                System.out.print ("  ");
        }}
        System.out.println();
    i++;
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM