Advertisement
Garey

Modern Recursive way

Feb 28th, 2018
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. // BP_Self_Programs.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include <iostream>
  5. #include <string>
  6. #include <conio.h>
  7.  
  8. #define s_c(wParam, lParam) ( static_cast<wParam> (lParam) )
  9. #define r_c(wParam, lParam) ( reinterpret_cast<wParam &> (lParam) )
  10.  
  11. template <typename FROM, typename TO, typename STEP, typename SUM>
  12. auto sum_recursive(FROM from, TO to, STEP step, SUM &sum) -> decltype(&sum) {
  13.     if (from < to) {
  14.         sum += from;
  15.         from += step;
  16.  
  17.         return sum_recursive(from, to, step, sum);
  18.     }
  19.  
  20.     return 0;
  21. }
  22.  
  23.  
  24. int main() {
  25.    
  26.     size_t choice;
  27.  
  28.     do {
  29.         system("cls");
  30.  
  31.         std::cout << "Menu: \n";
  32.         std::cout << "[1] Recursive sum in range with step & variable type choose\n";
  33.         std::cout << "[2] Exit\n";
  34.        
  35.         std::cout << "Your choice: ";
  36.         std::cin >> choice;
  37.  
  38.         switch (choice) {
  39.             case 1:
  40.                 std::string var_type("");
  41.  
  42.                 auto from(.0), to(.0), step(.0), sum(.0);
  43.  
  44.                 std::cout << "Enter number to sum from: ";
  45.                 std::cin >> to;
  46.                 std::cout << "Enter number to sum to: ";
  47.                 std::cin >> to;
  48.                 std::cout << "Enter incrementation: ";
  49.                 std::cin >> step;
  50.  
  51.                 std::cout << "Write variable type: \n";
  52.                 std::cin >> var_type;
  53.  
  54.                 if (var_type == "float")
  55.                     sum_recursive(s_c(float, from), s_c(float, to), s_c(float, step), r_c(float , sum));
  56.                 else if (var_type == "double")
  57.                     sum_recursive(s_c(double, from), s_c(double, to), s_c(double, step), r_c(double, sum));
  58.                 else if (var_type == "int")
  59.                     sum_recursive(s_c(int, from), s_c(int, to), s_c(int, step), r_c(int, sum));
  60.                 else if (var_type == "size_t")
  61.                     sum_recursive(s_c(size_t, from), s_c(size_t, to), s_c(size_t, step), r_c(size_t,sum));
  62.                 else {
  63.                     std::cout << "\n\nUnsupported type\n\n";
  64.                     break;
  65.                 }
  66.  
  67.                 std::cout << "\n\nSum: " << sum << std::endl << std::endl;
  68.                 _getch();
  69.         }
  70.     } while (choice != 2);
  71.  
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement