This program uses functions. The Problem Statement You are creating a program to
ID: 3679325 • Letter: T
Question
This program uses functions.
The Problem Statement
You are creating a program to help you understand some important math concepts: factorials and exponents. Since you are focused on understanding the concepts, you will not use the math library (math.h).
Program Setup
A scaffold of the solution has been created for you:
Do not modify the code that is already present. Instead, fill in the sections that are marked like this: /*** ... ***/
One of those sections will be the function to calculate a factorial. Your function will take in a single non-negative integer (n) and you'll calculate n! or n factorial. To calculate n! you would calculate the following product: 1x2x3x...xn.
Function Prototype
You must use this prototype to receive credit for the assignment.
// Pre-condition: 0 < n < 13
// Post-condition: Returns n!
int fact(int n);
Sample Run
What would you like to do?
1 - Calculate a power.
2 - Calculate a factorial
2
Please enter a value.
7
7! = 5040.
Explanation / Answer
#include <stdio.h>
//function prototypes
int exp(int base, int exponent);
int fact(int n);
/***Add the factorial function prototype here***/
//main function
int main(){
int n, pow, result, option;
printf("What would you like to do? ");
printf("1 - Calculate a power. ");
printf("2 - Calculate a factorial. ");
scanf("%d", &option);
while (option != 1 && option != 2) {
printf("Sorry, that was not a valid option. ");
printf("What would you like to do? ");
printf("1 - Calculate a power. ");
printf("2 - Calculate a factorial. ");
scanf("%d", &option);
}
if (option == 1) {
printf("Please enter the base value. ");
scanf("%d", &n);
printf("Please enter the exponent. ");
scanf("%d", &pow);
while (pow < 0) {
printf("Sorry, that was not a valid exponent. ");
printf("Please enter the exponent. ");
scanf("%d", &pow);
}
/***Add the function call for exp here***/
result = exp(n, pow);
printf("The result of %d raised to %d is %d. ", n, pow, result);
}
else {
printf("Please enter a value. ");
scanf("%d", &n);
while (n <= 0 || n >= 13) {
printf("Sorry, that was not a valid number. ");
printf("Please enter a value. ");
scanf("%d", &n);
}
result = fact(n);
printf("%d! = %d.", n, result);
}
return 0;
}
// Precondition: base is a real number, exp >= 0
// Postcondition: Returns base raised to the exp power.
int exp(int base, int exponent) {
int i, result = 1;
for(i=0; i<exponent; i++)
result *= base;
return result;
}
/*** Add the factorial function here ***/
int fact(int n){
int fact = 1;
while(n>=1){
fact *=n;
n--;
}
return fact;
}
/*
Output:
What would you like to do?
1 - Calculate a power.
2 - Calculate a factorial.
2
Please enter a value.
7
7! = 5040.
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.