recursion in cpp with reference

#include <iostream>
#include <cstdlib> //had to force it becasue my compiler (Code::Blocks) does not contain system.

using namespace std;
/*int n = 1, sum = 0;

int sumDigits(int n, int sum)
{
    //
	if (n == 0)
    {
        return sum;
    }
    else
    {
        // applying recursion and returning the value into the function
        sum = sum + n%10;
		n= n/10;
        return sumDigits(n, sum);
    }
}

int main(int argc, char* argv[])
{
	n = 1, sum = 0;

        cout << "Enter a non-negative integer: ";
        cin >> n;
        sum = sumDigits (n, sum);
        cout << "The sum of all digits "<< n << " is: " << sum << endl;

	system ("PAUSE");

        return 0;
}
*/

int sumDigits(int &);

int main()
{
	int n;
	sumDigits(n);
}

int sumDigits(int &n)
{
    cout << "Enter a non-negative integer: ";
    cin >> n;
        if (n == 1)
        {
            return 1;
        }
        else
        {
            return (n - 1) + n;
        }
    cout << "The sum of all digits "<< n << " is: " << n << endl;


	system ("PAUSE");

        return 0;
}

3.64
8
Andy Lu 135 points

                                    void sum_digits(int &amp; n, int &amp; sum)
{
  if ( n == 0 ) return;
  sum += n % 10;
  n /= 10;
  sum_digits(n, sum);
}

#include &lt;iostream&gt;
using namespace std;

int main()
{
  int n, sum=0;
  cout &lt;&lt; &quot;enter a non-negative number&quot; &lt;&lt; endl;
  cin &gt;&gt; n;
  if ( n &lt; 0 ) return -1; // don't trust the user
  sum_digits(n,sum);
  cout &lt;&lt; &quot;sum is &quot; &lt;&lt; sum &lt;&lt; endl;
}

3.64 (14 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source