The Sum of Digits

 

Modules - Structured Programming 1, Structured Programming 2

 

Teacher’s Notes:

========================================================================

Breaking a number into it's constituent digits is a skill I've needed to use a surprising number of times.  There are many ways to do this.  My solutions here will show two different ways.

The JAVA solution shows how you can use the modulus to isolate individual digits and then add them to the sum.  You can then pare off the digit from the number by dividing it by 10.

The C++ solution shows how you can take the input as a string and then look at each char individually.  Each char has an ASCII value.  The ASCII value of 0 is 48 so we can substract 48 from the individual values to attain the numeric equivalent to the ASCII character.

 

Assignment:

========================================================================

 

Write a program that prompts the user for an integer number.  The program will then print the sum of the digits within that number to the screen.  If the user enters a number that is negative, the program will ignore the negative sign and still sum the digits.

 

Sample Input 1: 

Please enter a number: 12345

Sample Output 1:

15

 

Sample Input 2: 

Please enter a number: 246810

Sample Output 2:

21

 

Solution (JAVA):

========================================================================

 
import java.util.Scanner;
public class SumOfDigits {
    
    public static void main(String[] args) {
        
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter a number: ");
        int number = input.nextInt();
        
        if(number < 0)
            number *= -1;
        
        int sum = 0;
        while(number > 0) {
            sum += number %10;
            number /= 10;
        }
        
        System.out.println(sum);        
    }
}

 

Solution (C++):

========================================================================

 
#include <iostream>
using namespace std;
 
int main()
{
    string number;
    int sum = 0;

    cout << "Please enter a number: ";
    cin >> number;
 
    if(number[0] == '-')
        number = number.substr(1);
 
    for(int x = 0 ; x < number.size(); x++)
        sum += number[x]-48;
 
    cout << sum << endl;
 
    return 0;
}