Sum the Digits in an Integer

less than 1 minute read

The code has been modified slightly and now uploaded to the site.

Question

<— Return Home

26.cpp

#include <iostream>
using namespace std;

int main(){
    int input;
    int sum;
    int lastDigit = 0;
    int middleDigit = 0;
    int firstDigit = 0;
    int cutLast = 0;
    int cutMiddle = 0;

    std::cout << "Enter a number between 0 and 1000: \n";
    std::cin >> input;

    try{
        if (input > 999 || input < 1){
            throw 000;
        }
        lastDigit = input % 10;
        cutLast = input / 10;
        middleDigit = cutLast % 10;
        cutMiddle = cutLast / 10;
        firstDigit = cutMiddle % 10;
        
        sum = lastDigit + middleDigit + firstDigit;

        std::cout << "The sum of the digits is " << sum;
    }
    catch(...){
        std::cout << "YOU MUST ENTER A NUMBER BETWEEN 0 and 1000!!!";
    }
    // if (input >= 0 && input <= 9){
    //     sum = input;
    // }
    // else if (input >= 10 && input <= 99){
    //     sum = ()
    // }

}

<— Return Home