Sheet 2 (Functions) - Q1
itsLu
c_cpp
2 years ago
864 B
14
Indexable
/* A. Write a function to calculate factorial of any number, then write a
program to calculate a! + b! - c! using:
• Loop */
/* 5! = 5x4x3x2x1, 3! = 3x2x1
2! = 2x1, 0! - 1! = 1, n<0 = no factorial*/
#include <iostream>
using namespace std;
int loop_factorial (int n)
{
int fact = 1; //n = 3
for (int k = n ; k >= 1 ; k--)
{
fact *= k;
//or fact = fact * k;
}
if (n == 0)
return 1;
else
return fact;
}
//• Recursion (without loops)
int rec_factorial (int n)
{
if (n == 0 || n == 1)
return 1;
else
return n * rec_factorial(n-1);
}
int main()
{
int a, b, c, res;
cout << "Please enter a, b and c: " << endl;
cin >> a >> b >> c;
res = rec_factorial(a) + rec_factorial (b) - rec_factorial(c);
cout << "Result = " << res;
}
Editor is loading...
Leave a Comment