Help in Recursion

I'm having difficulties in understanding the logic regarding the recursion? Can someone help me explain how do I get an output of 7 in it?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;
int recursion_sample(int x) { 
    return (x)? x%10 + recursion_sample(x/10): 0; 
}
int main()
{
    cout << recursion_sample(2500);

    return 0;
}
Last edited on
It actually adds the digits. In this example 0 + 0 + 5 + 2 = 7

This x%10 isolates the lowest digit. And this x/10 removes the lowest digit for the next recursion. Note the x/10 is an integer division. See:

https://press.rebus.community/programmingfundamentals/chapter/integer-division-and-modulus/
Last edited on
Topic archived. No new replies allowed.