So basically I have this c++ assignment for school where I need to write a recursive function, called sumDigits, that takes an integer as a parameter and returns the sum of the digits of the integer, but this error keeps popping up for me: functions.cpp:9:5: error: expected initializer before ‘if’
if (num != 0)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//In my funtions.cpp file
#include <iostream>
usingnamespace std;
inlinevoid sumDigits(longlong& sum, longlong num)
{
int sum (int num)
if (num != 0)
{
return (num % 10 + sum (num / 10));
}
else
{
return 0;
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//In my main.cpp file
#include <iostream>
#include "functions.cpp"
usingnamespace std;
int main()
{
longlong num = 930567829100185;
longlong sum = 0;
sumDigits(sum, num);
cout << "The sum of the digits of " << num << " is: " << sum << endl;
return 0;
}
But line 9 looks like you're trying to define a function called sum, when you're already in the middle of defining a function called sumDigits.
1 2 3 4 5 6 7 8 9
inlinevoid sumDigits(longlong& sum, longlong num)
{
if (num != 0)
{
// The sum is in the reference parameter.
sum += num % 10;
sumDigits(sum,num / 10));
}
}