Sheet 2 (Functions) - Q1 (OCD Edition)
itsLu
c_cpp
a year ago
1.1 kB
10
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; do { cout << "Please enter a: " << endl; cin >> a; } while (a < 0); do { cout << "Please enter b: " << endl; cin >> b; } while (b < 0); do { cout << "Please enter c: " << endl; cin >> c; } while (c < 0); res = rec_factorial(a) + rec_factorial (b) - rec_factorial(c); cout << "Result = " << res; }
Editor is loading...
Leave a Comment