Petro_zzz

new_lesson7_2

Aug 31st, 2022
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int factorial(int n) {
  6.     if (n < 1)
  7.         return 0;
  8.     if (n == 1)
  9.         return 1;
  10.     int res = 1;
  11.     for (; n > 1; n--)
  12.         res *= n;
  13.     return res;
  14. }
  15.  
  16. int fun1(int n) {
  17.     if (n == 1)
  18.         return 1;
  19.     return n * fun1(n-1);
  20. }
  21.  
  22. int sum(int n) {
  23.     if (n == 1) return 1;
  24.     return n + sum(n - 1);
  25. }
  26.  
  27. int sumArr(int arr[], int sz) {
  28.     if (sz == 1) return arr[0];
  29.     return arr[sz - 1] + sumArr(arr, sz-1);
  30. }
  31.  
  32. void showArr(int arr[], int sz) {
  33.     if (sz == 1)
  34.         cout << arr[0];
  35.     else {
  36.         cout << arr[sz - 1] << " ";
  37.         showArr(arr, sz - 1);
  38.     }
  39. }
  40.  
  41. double power(double x, int n) {
  42.     if (n == 0) return 1;
  43.     if (n == 1) return x;
  44.     return x * power(x, n - 1);
  45. }
  46.  
  47. void main() {
  48.     cout << "Iteration VS Recursion" << endl;
  49.     cout << "5! = " << factorial(5) << endl;
  50.     cout << "5! = " << fun1(5) << endl;
  51.     cout << "3^4 = " << power(3, 4) << endl;
  52.     cout << sum(5) << endl;
  53.  
  54.     int arr[4]{ 3, 5, 2, 1 };
  55.     cout << sumArr(arr, 4) << endl;
  56.     showArr(arr, 4);
  57.     cout << endl;
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment