I'm working on an assignment for Computer Science 121. The assignment is to write a program that prompts a user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, it should output the individual digits of 3456 as 3 4 5 6 and the sum as 18. I can't seem to get it working properly; I think my algorithm is wrong. I tried rewriting the algorithm, but I keep getting stuck in it. Can someone help me out? Here's what I have so far:

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
	int num, num2, sum = 0, dig;
	
	cout << "Please enter a number" << endl;
	cin >> num;
	
	if(num < 0)
		num = -num;
	num2 = num;
	dig = num;
	do
	{
		do
		{
			dig = dig / 10;
		}
		while (dig >= 10);

		cout << dig << " ";

		if (num > 100)
			num = num - (100*(num/100));
		else
			num = num - (10*(num/10));

		sum = sum + num2 % 10;

		num2 = num2 / 10;

		dig = num;

	}
	while (num2 > 0);
	cout << endl;
	cout << "The sum of the digits is " << sum << endl;

	return 0;
}

Thank you for the help :)

A combination of modulus division and normal division will do this nicely for you.

You have way to many steps, you can retreive each number in 1 line of code using both normal and modulus division.

its all to do with 10^x in a way xD

Chris

Start with the summation, because that's easy. You already seem to know about taking the remainder of ten to get the least significant digit and dividing by ten to slice it off. Remember to keep it as simple as possible. When you do this with more than one loop, you're not keeping it simple:

#include <iostream>

int main()
{
  std::cout<<"Enter a number: ";

  int num;

  if ( std::cin>> num ) {
    int sum = 0;

    if ( num < 0 )
      num = -num;

    while ( num != 0 ) {
      sum += num % 10;
      num /= 10;
    }

    std::cout<<"The sum is "<< sum <<'\n';
  }
}

The fun part is getting the digits to print out from most significant to least significant, as per your example using 3456. If you just print num % 10 in the while loop, you can get the digits in reverse. To print in the right order, you need to store the digits somewhere (the simpler solution, IMO), or extract the digits from most significant to least significant.

The fun part is getting the digits to print out from most significant to least significant, as per your example using 3456. If you just print num % 10 in the while loop, you can get the digits in reverse. To print in the right order, you need to store the digits somewhere (the simpler solution, IMO), or extract the digits from most significant to least significant.

This is what i was thinking about from the go was to get them in the correct order, so maybe my post may give you a small clue

Thanks for the help, but I still can't seem to grasp how to output the digits in order. I can get them to output in reverse just fine, but when I try to get them to output in order I can't seem to figure it out. I just started learning c++ and just learned loops, so I don't know much code. Can I get some more clues? My Computer Science class starts in 15 minutes (last minute, I know >< Thought I could figure it out on my own).

You could store all the numbers in an array as suggested and then print them out, or you can do something like this...

num = 546

mostsigdigit = (546 % 10^3)/10^2


probably gave too much away there but oh well

But what if the user enters a number with more than 3 digits?

Oh, and I haven't learned arrays yet :\

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

void print_int(int number){
	stringstream tmp_stream;
	tmp_stream << number;
	string str_num(tmp_stream.str());
	int sum = 0;
	for (size_t i = 0; i < str_num.size(); ++i){
		cout << str_num[i] << ' ';
		sum+=str_num[i]-'0';
	}
	cout << sum;
}

int main(int argc, char **argv) {
	int number;
	cin >> number;
	print_int(number);
	return 0;
}

Thanks again. One of the problems I did counted as a bonus and was actually worth more than this problem. I understand the solution now, and even though I didn't answer correctly I still scored a 100 because of the bonus question :)

Thanks! :D

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

void print_int(int number){
	stringstream tmp_stream;
	tmp_stream << number;
	string str_num(tmp_stream.str());
	int sum = 0;
	for (size_t i = 0; i < str_num.size(); ++i){
		cout << str_num[i] << ' ';
		sum+=str_num[i]-'0';
	}
	cout << sum;
}

int main(int argc, char **argv) {
	int number;
	cin >> number;
	print_int(number);
	return 0;
}

Interesting to see the different solution..heres the one i used, note this is just function not main program to call it

#include <iostream>
#include <cmath>
#include <limits.h>
#include "DigitSeparator.h"

void DigitSeparator::Separator( long int x ){
     int z;
     int q = 1;
     int sum = 0;
     
     if(x <= ULONG_MAX){
         while(1){
             if(x < pow(10.0, q++)){
                 z = q-1;
                 break;
                 }
             }            
         while (z != 0) sum += (int)((x%(int)(pow(10.0, z)+0.5))/pow(10.0, --z));
         std::cout << sum;
     }
     std::cin.clear();
     std::cout << "\n\n";
}

Since we're now giving out alternative solutions, here's mine:

#include <iostream>
#include <iterator>

template <typename OutIt>
int sum_digits ( int value, int radix, OutIt *it = 0 )
{
  if ( value == 0 )
    return 0;

  int digit = value % radix;
  int sum = sum_digits ( value / radix, radix, it ) + digit;

  if ( it != 0 )
    *it++ = digit;

  return sum;
}

int main()
{
  std::cout<<"Enter an integer: ";

  int value;

  if ( std::cin>> value ) {
    int sum = sum_digits ( value, 10, 
      &std::ostream_iterator<int> ( std::cout, " " ) );

    std::cout<<"\nThe sum is "<< sum <<'\n';
  }
}

Here is my code :):)

#include <iostream>
#include <cmath>
using namespace std;
void main()
{
	int number , num ;
	double count;

	cout<<"Please enter an integer."<<endl;
	cin>>number;

if(number < 0) // Convert negative integers to positive integers
number = -number;

num = number;

if(number < 10) //Case1: Integers less than 10
cout<<number<<endl;


while(num > 10)//Case2: Integers greater than 10
{
  for(count = 0 ; num > 10 ; count++)
  {
  num = num / 10;
  }
cout<<num<<" ";
number = number - ( num * pow(10 ,count) );
num = number;
}
cout<<num<<" "; //Prints the last digit

}

and another one :

#include <iostream>
#include <string>
#include <algorithm>
#include <numeric>
#include <iterator>

using namespace std;

int main(){
 string num;
 cin >> num;
 //print each digit
 std::copy( num.begin(), num.end(), std::ostream_iterator<char>(cout," "));
 //get sum
 int sum = std::accumulate(num.begin(),num.end(),0) - '0' * num.size();

 cout << "sum is = " << sum << endl;

 return 0;
}

Yes I know, no error checking. Thats because the user knows better, than to mess with me or my program.

Edited 6 Years Ago by firstPerson: n/a

Another method using cin.get

#include <iostream>
using namespace std;
void main()
{
int sum=0;
char ch;
cout<<"Please enter an integer."<<endl;

for (int index=0; ;index++)
{
cin.get(ch);

  if(ch==' ' ||ch =='\n' || ch=='\t') //To end the loop when all the input is read.
   {
   cout<<endl;
   break;
   }

if (index==0) //To print "Number: " before printing the input
cout<<"Number: ";

if(ch=='-')
continue;

sum = sum + (ch-48); //Minus 48 (See ASCCI table http://www.cpptutor.com/ascii.htm)
cout<<ch<<" ";
}
cout<<"Sum = "<<sum<<endl; 
}

Edited 6 Years Ago by andro23: n/a

Another method using string (Sorry I wasn't able to get the sum of the numbers. It could use atoi() to convert from string type to int type but i wasn;t able to understand this atoi() :(:()

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

cout<<"Please enter an integer."<<endl;
cin>>number;

for(int index=0 ; ; index++)
{
string b(number,index, 1);

if(b=="-")
continue;

if(b =="")//To end the loop when all the input is printed.
break;

cout<<b<<" ";
}
cout<<endl;
}

Edited 6 Years Ago by andro23: n/a

I have modified my solution to a challenge question given by firstPerson to reverse number and add without trailing zeros. The new solution is now adding digits of number only:

int main(){unsigned d=0,n,s=0;cin>>n;for(;n;d=n%10,s+=d,n/=10);cout<<s;return s;}

Ok, I must apologize because this code is not well readable. My idea was finding very short program code.

Edited 6 Years Ago by 1stDAN: n/a

This article has been dead for over six months. Start a new discussion instead.