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
  • 349,597
  • 67
  • 533
  • 578
karthick
  • 21
  • 4
  • 3
    get the remainder first and do division later. – karan Nov 06 '20 at 08:46
  • Just take input as String, and iterate over each character, get its numeric value and reduce them... – Animesh Sahu Nov 06 '20 at 08:53
  • 1
    Does this answer your question? [How to sum digits of an integer in java?](https://stackoverflow.com/questions/27096670/how-to-sum-digits-of-an-integer-in-java) – pradeexsu Nov 06 '20 at 11:07

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,777
  • 3
  • 20
  • 35