Advertisement
janac

Multiply two positive integers using recursion

Dec 13th, 2021
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. #include <iostream>  
  2. #include <string>
  3. #include <limits>
  4. using namespace std;
  5.  
  6. // This function uses recursion to
  7. // multiply two positive integers, or zero.
  8. int mult(int i, int n)
  9. {
  10.     if (n == 0) return 0; // Base case.
  11.     else if (n == 1) return i; // Base case.
  12.     else
  13.     {
  14.         // Recurrence relation.
  15.         return i + mult(i, n - 1);
  16.     }
  17. }
  18.  
  19. int main()
  20. {
  21.     string int_1_string; // Input number to multiply.
  22.     string int_2_string; // Input number of times.
  23.     int int_1 = 0; // Number to multiply converted to int.
  24.     int int_2 = 0; // Number of times converted to int.
  25.     int product = 0; // Result of multiplication.
  26.  
  27.     cout << "This program shows how recursion can be\n"
  28.         "used to multiply two positive integers.\n"
  29.         "What integer would you like to multiply? ";
  30.     getline(cin, int_1_string); // Get number to multiply.
  31.     int_1 = stoi(int_1_string); // Convert to int.
  32.     while (int_1 < 0) // If it's not positive or zero,
  33.     {
  34.         cout << "Please enter an integer greater than or"
  35.             " equal to zero. ";
  36.         getline(cin, int_1_string); // Get new input.
  37.         int_1 = stoi(int_1_string); // Convert it to int.
  38.     }
  39.  
  40.     cout << "How many times would you like to multiply it? ";
  41.     getline(cin, int_2_string); // Get number of times.
  42.     int_2 = stoi(int_2_string);  // Convert to int.
  43.     while (int_2 < 0) // If it's not positive or zero,
  44.     {
  45.         cout << "Please enter an integer greater than or"
  46.             " equal to zero. ";
  47.         getline(cin, int_2_string); // Get new input.
  48.         int_2 = stoi(int_2_string); // Convert it to int.
  49.     }
  50.  
  51.     product = mult(int_1, int_2); // Calculate the result.
  52.  
  53.     // Display the result.
  54.     cout << "The product of " << int_1 << " and "
  55.         << int_2 << " is " << product << ".\n";
  56.  
  57.     // End the program.
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement