Recursive C++... Please Help

I am very new to this and I'm really having a hard time trying to code and stuff. We have an exercise tomorrow about recursive function and I've been practicing with one of the questions that our teacher gave us a week ago. I've tried to make my own code but it seems that I can't understand why my program wont show the solution. This is what the program is supposed to do.

Write a function that computes for the sum of each of the digits of a given number. The function takes an integer argument and returns an integer sum. If a number is a negative number, get its absolute value.

#include<iostream.h>

int sumofDigits(int);

void main()
{
int x;

cout<< "please enter a number ";
cin>> x;

cout<<sumofDigits(x);
}

int sumofDigits(int x)
{

int m,t=x;
int c=0;

if (t!=0)
{
m=t%10;
c=c+m;
t=x/10;

cout<<sumofDigits(t);
}
return c;


}
Well, almost:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int sumofDigits(int x)
{

int m,t=x;
int c=0;

if (t!=0)
{
  if(t  < 0)
    t = -t;

m=t%10;
t /= 10;

c = m + sumofDigits(t);
}
return c;
}
not tested
it works thank you very much.
i see there was really a problem with my coding, I thought it was just a common error
Topic archived. No new replies allowed.