recursion in c 2b 2b

Solutions on MaxInterview for recursion in c 2b 2b by the best coders in the world

showing results for - "recursion in c 2b 2b"
Jarvis
24 Feb 2019
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}
Elina
17 May 2019
1//recursion in c++
2//factorial
3#include<iostream>
4#include<bits/stdc++.h>
5using namespace std;
6
7int factorialfun(int num)
8{
9	if (num>0)
10	{
11		return num*factorialfun(num-1);
12	}
13	else
14	{
15		return 1;
16	}
17}
18int main()
19{
20	int num;
21	cin>>num;
22	cout<<factorialfun(num);
23}
24
Sol
29 Mar 2018
1//AUTHOR:praveen
2//Function calling itself 
3//Example in c++
4#include<iostream>
5using namespace std;
6int recursion(int a){
7  	if(a==1)//BASE CASE
8      return 0;
9	cout<<a;
10  	a=a-1;
11  	return recursion(a);//FUNCTION CALLING ITSELF
12}
13int main(){
14  	int a=5; 
15	recursion(a);
16  	return 0;
17}
18//OUTPUT: 5 4 3 2