I’m trying to learn c++ on my own and I’ve hit a bit of a road block. The problem is I need to take an integer,split it into its digits and get the sum of the digits and display them.
Example:
input number: 123456
digits in the integer: 1 2 3 4 5 6
sum: 21
I have it all done, but when I rip the integer, into digits I can’t display it correctly. It displays in reverse order.
So in the program below I enter 1234 and it spits out 4 3 2 1. I know why, I just don’t know how to fix it.
Here is my code so far:
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <math.h>
int countDigitsInInteger(int n)
{
int count =0;
while(n>0)
{
count++;
n=n/10;
}
return count;
}
using namespace std;
int main(int argc, char *argv[])
{
int intLength =0;
int number;
int digit;
int sum = 0;
string s;
cout << "Please enter an integer ";
cin >>number;
cout << "Orginal Number = "<<number <<endl;
//make the number positive
if (number<0)
number = -number;
intLength = countDigitsInInteger(number);
//break apart the integer into digits
while(number>0)
{
digit = number % 10;
number = number / 10;
cout <<digit << " ";
sum = sum+digit;
}
cout <<endl <<"Sum of the digits is: "<<sum<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Here is my solution
can’t see 🙂
Your problem comes from the fact that you are reading the digits backwards, thus you need to print them out backwards. A stack will help you tremendously.
Oh, and BTW, keep your indentation clean. Its important.
EDIT: In response to Steve Townsend, this method is not necessarily overkill, it is just different from yours. The code can be slimmed down so that it seems less like overkill: