Home > OS >  Loop that writes a number vertically
Loop that writes a number vertically

Time:10-26

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;
      }
}

CodePudding user response:

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));
    }

CodePudding user response:

The very trivial way would be to reverse the number and then do the same thing you are currently doing.

  •  Tags:  
  • java
  • Related