to make my point clearer
I pasted my source code here
I atually got run-time error when inputing 2-digit number.
I suspected that the first while-loop is imperfect.
Code:
#include <iostream>
using namespace std;
int main()
{
int number1,number2, firstDigit;
int part_number, digit, lastDigit, digitTotalSum;
int counter=1;
int digitSum = 0;
int digit_count=0;
//Ask for number;
cout << "Please enter a number: ";
cin >> number1;
//number2 will be used for later steps
number2=number1;
cout << endl;
//First, we need to know how many digit it has
//The loop keeps checking until number1 get to ZERO (false)
//This loop will also calculate the power of base 10
//in order to extract the 1st digit.
int firstPower=1;
while (number1)
{
number1 /= 10;
firstPower *= 10;
digit_count++;
}
//------------------------------------------------------
//The first digit
firstDigit=number2/(firstPower/10);
//This loop will take care of the middle digits
while(counter < (digit_count - 1))
{
//Need to calcuate power of base 10
int power=1;
int counter_power=1;
while (counter_power<= (digit_count-counter))
{
power = power*10;
counter_power++;
}
//Ending power calculation
part_number = number2 % power;
digit = part_number / (power/10);
digitSum = digitSum + digit;
counter++;
}
//------------------------------------------------------
//This will calculate the last digit and the sum
lastDigit=part_number % 10;
digitTotalSum=digitSum + lastDigit+firstDigit;
cout << "The sum is: " << digitTotalSum << endl;