Write in C++ please. I\'m using a VirtualBox machine running linux using Geany a
ID: 3826653 • Letter: W
Question
Write in C++ please. I'm using a VirtualBox machine running linux using Geany as an editor.
The goal of this assignment is to get some experience writing simple functions, and to appreciate that iteration and recursion are equally powerful programming techniques. Many mathematical operations can be expressed, or are defined, in terms of other, simpler, operations. In particular, multiplication is defined in terms of addition, because the product of integers a and b can be obtained by adding a to itself, b times. In other words, a * b = a + a + a + ... + a In the above, we assume that b is a non-negative integer. In this programming assignment, we will write two different, yet equivalent, C++ functions for integer multiplication. Both functions will be based upon the above definition of multiplication. However, our first function will be iterative, and the second one recursive. Declarations of our functions are: int muli(int a, int b); int mulr(int a, int b); The function muli should compute the product of its parameters a and b by iteration, while the function mulr should compute the product of its parameters by recursion. The parameter a may be any integer value, but you should assume that the parameter b of the above functions is a non-negative integer, i.e. b lessthanorequalto 0. Write declarations and definitions of both above functions in a single C++ source file. Also include in this file, a mainline that prompts for and inputs two integers, verifies that the second of these two input integers is non-negative, and outputs their products obtained from each of the above functions.Explanation / Answer
// Example program
#include <iostream>
using namespace std;
int multi(int a, int b);
int multr(int a, int b);
int main()
{
cout << "Enter two integers: ";
int a, b;
cin >> a>> b;
if (b < 0)
{
cout << "ERROR: The second value must be non-negative" << endl;
return 1;
}
cout << "Product obtained iteratively = " << multi(a, b) << endl;
cout << "Product obtained recursively = " << multr(a, b) << endl;
}
int multi(int a, int b)
{
int result = 0;
for(int i = 1; i <= b; i++)
{
result = result + a;
}
return result;
}
int multr(int a, int b)
{
if(b == 1)
return a;
return a + multr(a, b-1);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.