recursion in cpp with reference

Solutions on MaxInterview for recursion in cpp with reference by the best coders in the world

showing results for - "recursion in cpp with reference"
Laura
16 Aug 2016
1#include <iostream>
2#include <cstdlib> //had to force it becasue my compiler (Code::Blocks) does not contain system.
3
4using namespace std;
5/*int n = 1, sum = 0;
6
7int sumDigits(int n, int sum)
8{
9    //
10	if (n == 0)
11    {
12        return sum;
13    }
14    else
15    {
16        // applying recursion and returning the value into the function
17        sum = sum + n%10;
18		n= n/10;
19        return sumDigits(n, sum);
20    }
21}
22
23int main(int argc, char* argv[])
24{
25	n = 1, sum = 0;
26
27        cout << "Enter a non-negative integer: ";
28        cin >> n;
29        sum = sumDigits (n, sum);
30        cout << "The sum of all digits "<< n << " is: " << sum << endl;
31
32	system ("PAUSE");
33
34        return 0;
35}
36*/
37
38int sumDigits(int &);
39
40int main()
41{
42	int n;
43	sumDigits(n);
44}
45
46int sumDigits(int &n)
47{
48    cout << "Enter a non-negative integer: ";
49    cin >> n;
50        if (n == 1)
51        {
52            return 1;
53        }
54        else
55        {
56            return (n - 1) + n;
57        }
58    cout << "The sum of all digits "<< n << " is: " << n << endl;
59
60
61	system ("PAUSE");
62
63        return 0;
64}
Dorian
22 May 2019
1void sum_digits(int & n, int & sum)
2{
3  if ( n == 0 ) return;
4  sum += n % 10;
5  n /= 10;
6  sum_digits(n, sum);
7}
8
9#include <iostream>
10using namespace std;
11
12int main()
13{
14  int n, sum=0;
15  cout << "enter a non-negative number" << endl;
16  cin >> n;
17  if ( n < 0 ) return -1; // don't trust the user
18  sum_digits(n,sum);
19  cout << "sum is " << sum << endl;
20}