Tyler Worley
Tyler Worley

Reputation: 1

Loop that writes a number vertically

I'm trying to take the number 1234 and write it as: 1 2 3 4 My code has it displayed as: 4 3 2 1 Here is my code:



   public static void verticalLoop(int num )
    {
      while(num != 0)
      {
         System.out.println(num % 10);
         num = num / 10;
      }
}

Upvotes: 0

Views: 585

Answers (2)

WJS
WJS

Reputation: 40034

You can do it recursively. Keep calling the method until a single digit is reached. Then, return, unwinding the stack and printing the last digit.

verticalLoop(num);

public static void  verticalLoop(int num) {
   if (num > 9) {
        verticalLoop(num/10);
   }
   System.out.println(num%10);
}

Here are two other solutions which one might consider less advanced.

Store the digits in an array and print them in reverse order

  • allocate an array of 10 (max digits for an int)
  • iterate saving the digits as before, placing them in the array
  • then using the one less than the value of i, iterate thru the array printing the digits.
public static void verticalLoop(int num) {
    // max digits for an int
    int[] digits = new int[10]; 
    int i = 0;
    while (num > 0) {
        digits[i++] = num%10;
        num/=10;
    }
    for (int k = i-1; k >=0 ; k--) {
        System.out.println(digits[k]);
    }
}

This requires a little math. A logarithm is just an exponent. So raising 10 to the log10(n) simply gives you n. But the int of log10(n) gives you the number of digits less 1 in n. So (int)Math.log10(n) gives you the largest power of 10 that won't yield 0 upon division.

  • divide by the largest power of 10
  • print the digit using %
  • adjust the power to the next lower one by dividing by 10.
  • continue until the divisor reaches 0.
public static void verticalLoop(int num) {
    int maxPower10 = (int)Math.pow(10,(int)Math.log10(num));
    while (maxPower10 > 0) {
        System.out.println((num/maxPower10) % 10);
        maxPower10/=10;
    }
}

Upvotes: 1

Convert the number to a string:

String s = Integer.toString(num);
    
    for (int i = 0; i < s.length(); i++) {
        System.out.println(s.charAt(i));
    }

Upvotes: 0

Related Questions