Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

You are to write two functions. A factorialfunction that takes as input an integ

ID: 3923570 • Letter: Y

Question

You are to write two functions. A factorialfunction that takes as input an integer (pass-by-value) and returns thefactorial of the number. Your function should return a -1 if the input parameteris negative. Another function is your own power function (like the built-in pow function). Inthe power function, you are to take as input two integers (pass-by-value) thatdenote the base and the exponent, and returns the base to the power of exponent(NOTE: you cannot do base^exponent -- that doesn't work). One last requirement, each input that is passed into the functions needs to be arandom number between 1 and 10.Be sure to call srand(time(NULL)) only once in your program.

Explanation / Answer

// C++ code factorial and power function

#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <fstream>
using namespace std;

int factorialfunction(int number)
{
    if(number < 0)
      return -1;

    int factorial = 1;
    for (int i = 2; i <= number ; ++i)
    {
       factorial = factorial *i;
    }

    return factorial;

}

int powerfunction(int base, int exponent)
{
    int temp = base;
    while(exponent-- != 1)
    {
        base = base*temp;
    }

    return base;
}

int main()
{
    srand(time(NULL));

    int number = rand()%10 + 1;
    int base = rand()%10 + 1;
    int exponent = rand()%10 + 1;

    cout << number << "! = " << factorialfunction(number) << endl << endl;
    cout << base << "^" << exponent << " = " << powerfunction(base,exponent) << endl << endl;


    return 0;
}

/*
output:

10! = 3628800
3^9 = 19683


1! = 1
7^9 = 40353607


8! = 40320
1^7 = 1


4! = 24
8^2 = 64

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote