how to add digits separately

Hi i m just a beginner to C++.I only want to know that how can i add digits of a given number separately and get a single digit answer.e.g. User entered "5323" and the program will add them like 5+3+2+3=13, and program will again add 1 and 3 and will give the answer that is "4".I have done till the first step( adding numbers separately)but the answers is not single every time.In most cases it contains two digits.(like 13).Tell me should i use loop and which one
one approach would be to use recursion

something like this:

1
2
3
4
5
6
7
string squish( const string& orig ) {
  string newstr;
  // put your algorithm here and set it to newstr
  if ( newstr.size() > 1 )
    return squish( newstr );
  return newstr;
}


edit: correction - you should only call squish() again if strlen is greater than 1, not 0
Last edited on
it's unclear if you are using strings or long/int

the same approach will also work for long/int
Thanks. But you told me such a things that I haven't studied yet.I m limited till do-while loop.
here is a piece of code to separate the digits.(i made it by myself)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*A program that takes a four digit integer from user and shows the digits separately i.e. if user enters 
1234, it displays 4,3,2,1 separately.*/
#include<iostream.h>
main()
{
      //declare variables
      int number,digit;
      
      //prompt the user to enter the four digit number
      cout<<"Please enter a four digit number:";
      cin>>number;
      
      //get the first digit and displays it on the screen
      digit=number%10;
      cout<<"The numbers are:";
      cout<<digit<<",";
      
      //get the reamining three digits
      number=number/10;
      
      //get the next digit and displays it
      digit=number%10;
      cout<<digit<<",";
      
      //get the remaining two digits
      number=number/10;
      
      //get the next digit and displays it on screen
      digit=number%10;
      cout<<digit<<",";
      
      //get the remaining one digit
      number=number/10;
      
      //get the next digit and displays it
      digit=number%10;
      cout<<digit;
      
      
}

have you learned how to write a function yet?

if not, I would recommend that you wait until you learn that before tackling this project further.
if you have, then try to put your current algorithm in a function and call that function from main().
Topic archived. No new replies allowed.