Evan
Evan

Reputation: 17

How do I loop in Vertical Position?

I’m a newbie at programming. I was ask to do a code where it prints a number in descending and in vertical position. Below is my code:

import java.util.Scanner;
class Main{
    public static void main (String args []){
        Scanner input = new Scanner (System.in);
        int r=0,ascend=0;

        int number=input.nextInt();
        while(number>0) {
            r= number%10;
            number= number/10;
            ascend= (ascend*10)+r;
        }
        System.out.println(ascend + "\n");
        ascend++;
    }
}

However, when I put an input of: 214

The output would be:

412

What can I do to turn the output like below?

4
1
2

Upvotes: 1

Views: 277

Answers (2)

Woodchuck
Woodchuck

Reputation: 4414

You could try this.

It's basically the same as yours, with the print moved into the loop and printing each digit:

import java.util.Scanner;

class Main {
    public static void main (String args []) {
        Scanner input = new Scanner(System.in);
        int r = 0;

        int number = input.nextInt();
        while(number > 0) {
            r = number % 10;
            number /= 10; // assignment operator shorthand for number = number / 10;
            System.out.println(r);
        }
    }
}

Upvotes: 1

Yoni
Yoni

Reputation: 1430

You need to place your println within the loop. With this, you can remove the ascend variable. With println, you also get the new line character for free

    Scanner input = new Scanner(System.in);
    int r = 0;

    int number = input.nextInt();
    while (number > 0) {
        r = number % 10;
        number = number / 10;
        System.out.println(r);
    }

Upvotes: 0

Related Questions