M.Amir
M.Amir

Reputation: 5

Print the series of numbers in java by user input

I need to display the below series based on user input

Example: If user input number 5 then expected output will be

54321
5432
543
54
5
public static void main(String args[]) throws Exception {
    int n;
    boolean quit = false;
    BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a number :");
    n = sc.nextInt();
    System.out.println("The Series is:");
    for(int i=n;i>=1;i--){
        for(int j=n; j<=i; j++){
            System.out.print(j);
        }
    } 
    System.out.println("");
}

Upvotes: 0

Views: 1754

Answers (2)

Selva
Selva

Reputation: 338

Please try the below code:

System.out.println("The Series is:");
System.out.println("");
for(int i=1;i<=n;i++){
    for(int j=n; j>=i; j--){
       System.out.print(j);
    }
    System.out.println("");
}

Upvotes: 1

Lets say you get the integer you need without a problem, then the algorithm for the sequence could be something like this:

    int f = 5;
    int k = f;

    while (k > 0) {

        for (int i = 0; i < k; i++) {
            System.out.println(f - i);
        }
        k--;
        System.out.println("....");
    }

which is printing you desired sequence: 5 4 3 2 1 .... 5 4 3 2 .... 5 4 3 .... 5 4 .... 5 ....

Upvotes: 1

Related Questions