In: Computer Science
This C++ program will use arrays, recursion, and
pass by reference to calculate 02, 12,
22, 32, 42 and then print a
message.
Write a driver program (main) that includes the
following:
An array class (not a built-in-array) of
5 integers initialized to 0,1,2,3,4 the bases
An integer initialized to 2 to hold the
exponent
A string initialized to “Good Job!\n”;
A for loop that calls the recursive pow
function with all of the bases and the exponent.
Call the print function with the string using pass
by reference by passing the address of s.
You must use the array class (not built-in-arrays)
for full credit.
Write a pow function that implements raising a
base to a power. The function takes an int base and an int
exp. It returns an int which is baseexp. You
must use recursion for full credit.
Base case: base1 = base
Recursive case: baseexp = base *
baseexp-1
Write a print function that takes a string pointer and
uses the indirection operator (*) to print the contents of the
string to the screen. This function does not return anything.
This function must use pass by reference with pointers for full
credit.
Code in C++ with comments (code to copy)
// This C++ program will use arrays, recursion, and pass by reference to calculate 0^2, 1^2, 2^2, 3^2, 4^2 and then print a message.
#include <bits/stdc++.h>
using namespace std;
// Write a pow function that implements raising a base to a power. The function takes an int base and an int exp. It returns an int which is baseexp. You must use recursion for full credit.
int pow(int base, int exp){
if(exp==1)
// Base case: base1 = base
return base;
else{
// Recursive case: baseexp = base * baseexp-1
return base*pow(base, exp-1);
}
}
// Write a print function that takes a string pointer and uses the indirection operator (*)
//to print the contents of the string to the screen. This function does not return anything.
//This function must use pass by reference with pointers for full credit.
void print(string *msg){
cout<<*msg;
}
// Write a driver program (main) that includes the following:
int main(){
// An array class (not a built-in-array) of 5 integers
// initialized to 0,1,2,3,4 the bases
// You must use the array class (not built-in-arrays) for full credit.
array<int,6> arr = {0, 1, 2, 3, 4};
// An integer initialized to 2 to hold the exponent
int exp = 2;
// A string initialized to “Good Job!\n”;
string greet = "Good Job!\n";
// A for loop that calls the recursive pow function with all of the bases and the exponent.
for(int i=0;i<5;i++){
arr[i]=pow(arr[i], exp);
}
// Call the print function with the string using pass by reference by passing the address of s.
print(&greet);
}
Code Screenshot
Console Output Screenshot
Let me know in the comments if you have any doubts.
Do leave a thumbs up if this was helpful.