Coding Practice

Write a Java program to calculate sum of digits of a number

Calculate sum of digits of a number
Sample Output
Calculate sum of digits of a number.

Enter a number: 192
Sum: 12
Java-Source Code
//package loopinjava;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        int n, digit, number, sum = 0;

        Scanner input = new Scanner(System.in);

        System.out.println("Calculate sum of digits of a number.\n");

        System.out.print("Enter a number: ");
        number = input.nextInt();

        while (number != 0) {
            
            digit = (number % 10);
            sum = sum + digit;
            number = (number / 10);
        }
        System.out.println("Sum: " + sum);
    }
}
Sample Output
Calculate sum of digits of a number.

Enter a number: 2021
Sum: 5

No comments:

Post a Comment

Change Theme
X