0% found this document useful (0 votes)
15 views1 page

PGM 14

The document contains a Java program that calculates the sum of the digits of a given integer. It prompts the user to input a number, handles negative values, and uses a loop to extract and sum each digit. Finally, it displays the result to the user.

Uploaded by

wasimrajaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views1 page

PGM 14

The document contains a Java program that calculates the sum of the digits of a given integer. It prompts the user to input a number, handles negative values, and uses a loop to extract and sum each digit. Finally, it displays the result to the user.

Uploaded by

wasimrajaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import java.util.

Scanner;

public class SumOfDigits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Ask the user to enter a number


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

int sum = 0;
int temp = Math.abs(number); // Handle negative numbers

// Loop to extract and add each digit


while (temp > 0) {
int digit = temp % 10;
sum += digit;
temp /= 10;
}

// Display the result


System.out.println("Sum of digits: " + sum);

scanner.close();
}
}

You might also like