0
package myfirstproject;

import java.util.Scanner;
public class whileloop {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
      long n,sum=0;
      System.out.println("Enter a number:");
      Scanner sc=new Scanner(System.in);
      n=sc.nextLong();
      while(n!=0)
          {
          n/=10;
          sum+=n%10;
      }
      System.out.println("The sum of digits of number is " +sum);
      
      }
    }

output:

enter a number:

For example if I input 745, it adds the first 2 digits and gives the result as 11. But it is not adding the 3rd digit.

John Kugelman
  • 330,190
  • 66
  • 504
  • 555
karthick
  • 21
  • 4

3 Answers3

1

Your order is wrong. First n mod ten, then n div 10:

 while(n != 0){
   sum+=n%10;
   n/=10;
 }

It is because you want to get the every single digit of number so you need to modulo it by ten to achieve this.

viverte
  • 43
  • 7
1

You should interchange the below lines.

  n/=10; 
  sum+=n%10;

The reason is that when you are dividing it by 10, you are losing the last digit before adding it to your sum.

0

you need to module and then divide

public static void main(String[] args) {
        long n, sum = 0;
        System.out.println("Enter a number:");
        Scanner sc = new Scanner(System.in);
        n = sc.nextLong();
        while (n != 0) {
            sum+=n%10;
            n/=10;
        }
        System.out.println("The sum of digits of number is " + sum);

    }
Pandit Biradar
  • 1,609
  • 1
  • 15
  • 27