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}
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
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
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}
1// Factorial of n = 1*2*3*...*n
2#include <iostream>
3using namespace std;
4
5int factorial(int);
6
7int main() {
8 int n, result;
9
10 cout << "Enter a non-negative number: ";
11 cin >> n;
12
13 result = factorial(n);
14 cout << "Factorial of " << n << " = " << result;
15 return 0;
16}
17
18int factorial(int n) {
19 if (n > 1) {
20 return n * factorial(n - 1);
21 } else {
22 return 1;
23 }
24}