Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <limits>
- using namespace std;
- // This function uses recursion to
- // multiply two positive integers, or zero.
- int mult(int i, int n)
- {
- if (n == 0) return 0; // Base case.
- else if (n == 1) return i; // Base case.
- else
- {
- // Recurrence relation.
- return i + mult(i, n - 1);
- }
- }
- int main()
- {
- string int_1_string; // Input number to multiply.
- string int_2_string; // Input number of times.
- int int_1 = 0; // Number to multiply converted to int.
- int int_2 = 0; // Number of times converted to int.
- int product = 0; // Result of multiplication.
- cout << "This program shows how recursion can be\n"
- "used to multiply two positive integers.\n"
- "What integer would you like to multiply? ";
- getline(cin, int_1_string); // Get number to multiply.
- int_1 = stoi(int_1_string); // Convert to int.
- while (int_1 < 0) // If it's not positive or zero,
- {
- cout << "Please enter an integer greater than or"
- " equal to zero. ";
- getline(cin, int_1_string); // Get new input.
- int_1 = stoi(int_1_string); // Convert it to int.
- }
- cout << "How many times would you like to multiply it? ";
- getline(cin, int_2_string); // Get number of times.
- int_2 = stoi(int_2_string); // Convert to int.
- while (int_2 < 0) // If it's not positive or zero,
- {
- cout << "Please enter an integer greater than or"
- " equal to zero. ";
- getline(cin, int_2_string); // Get new input.
- int_2 = stoi(int_2_string); // Convert it to int.
- }
- product = mult(int_1, int_2); // Calculate the result.
- // Display the result.
- cout << "The product of " << int_1 << " and "
- << int_2 << " is " << product << ".\n";
- // End the program.
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement