using functions help

I need to call a separate function from main() that takes the inputed number and does the following: prints digits of this number; and returns/prints the sum of digits. and i cant figure out how to return each individual digit. Help please.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int sum=0, firstdig, secdig;
int digsum (int x) {
while (x>0) {
sum += x % 10;
x /= 10;}
firstdig=x/10; secdig=x%10;
cout << firstdig << secdig << "The sum of the digits of your number is " << sum << endl;
}

int main () {
int x;
cout << "Enter a positive number ";
cin >> x;
if (x<=0) return 0;
cout << digsum (x) << endl;
return 0;
}
Returning each digit and returning the sum is different.
if you wish to retrun sum it would simply be:
return sum; after your loop. Also your formatting...You should indent on each level of braces.

eg:

1
2
3
4
5
6
7
8
9
int main()
{
    //I am indented
    if(something)
    {
        //I am indented again
    }
    //stuff
}


Another thing to mention the normal way to have sub-functions is to prototype(declare) your functions before the main function and then define them (the body) after.
Topic archived. No new replies allowed.