In: Computer Science
1. Write a program in C++ to find the factorial of a number.
Prompt the user for a number and compute the factorial by using the
following expression. Use for loops to write your solution
code.
Factorial of n = n! = 1×2×3×...×n; where n is the user input.
Sample Output:
Find the factorial of a number:
------------------------------------
Input a number to find the factorial: 5
The factorial of the given number is: 120
2. Code problem 1 using While loop.
3. Write the code for a C++ program testMath.cpp that reads in two
integer numbers from user input. Write the following functions in
addition to the main() function for computing and returning the
following to the main( ) function. 1. Function sum( ) computes and
returns the sum of the two numbers, 2. Function diff( ) computes
and returns the difference of the two numbers (always positive), 3.
Function avg( ) computes and returns the average, 4. Function max(
) computes and returns the maximum of the two numbers 5. Function
min( ) computes and returns the minimum of the two numbers
The main( ) function performs the unit testing and tests all the
functions.
Sample Output
This program reads in two integer numbers from user input
and returns their sum, difference, average, maximum and
minimum.
Please enter the two numbers: 17 5
The numbers entered are 17 and 5.
The sum of 17 and 5 is: 22
The difference of 17 and 5 is: 12
The average of 17 and 5 is: 11
Fall 2019
The maximum of 17 and 5 is: 17
The minimum of 17 and 5 is: 5
#include <iostream>
using namespace std;
// part one
int factorialFor(int n){
int f = 1;
if (n == 0 || n == 1)
{
return f;
}
for (int i = 2; i <= n; ++i)
{
f *= i;
}
return f;
}
// part two
int factorialWhile(int n){
int f = 1, i = 2;
if (n == 0 || n == 1)
{
return f;
}
while(i <= n)
{
f *= i;
++i;
}
return f;
}
int main()
{
int n;
cout<<"Input a number to find the factorial:
";
cin>>n;
cout<<"\nThe factorial of the given number is: "<<factorialFor(n)<<endl;
cout<<"The factorial of the given number
is(using while): "<<factorialWhile(n)<<endl;
return 0;
}
// part 3
#include <iostream>
using namespace std;
int sum(int a, int b){
return (a+b);
}
int diff(int a, int b){
return (a > b? (a-b):(b-a));
}
int agv(int a, int b){
return (a+b)/2;
}
int max(int a, int b){
return (a > b? a:b);
}
int min(int a, int b){
return (a > b? b:a);
}
int main()
{
int a,b;
cout<<"Please enter the two numbers: ";
cin>>a>>b;
cout<<"The numbers entered are
"<<a<<" and "<<b<<"."<<endl;
cout<<"The sum of "<<a<<" and
"<<b<<" is: "<<sum(a,b)<<endl;
cout<<"The difference of "<<a<<" and
"<<b<<" is: "<<diff(a,b)<<endl;
cout<<"The average of "<<a<<" and
"<<b<<" is: "<<agv(a,b)<<endl;
cout<<"The maximum of "<<a<<" and
"<<b<<" is: "<<max(a,b)<<endl;
cout<<"The minimum of "<<a<<" and
"<<b<<" is: "<<min(a,b)<<endl;
return 0;
}