Programming C++ Exercise 5.1.1. Write a program that defines and tests a factori
ID: 3805624 • Letter: P
Question
Programming C++
Exercise 5.1.1. Write a program that defines and tests a factorial function. The factorial of a number is the product of all whole numbers from 1 to N. For example, the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120. (Hint: Use a for loop as described in Chapter 3.)
Exercise 5.1.2. Write a function named print_out that prints all the whole numbers from 1 to N. Test the function by placing it in a program that passes a number n to print_out, where this number is entered from the keyboard. The print_out function should have type void; it does not return a value. The function can be called with a simple statement:
print_out(n);
Explanation / Answer
#include<iostream>
using namespace std;
int main()
{
//declaring the variables and functions
int num, factorial,n;
int fact(int num);
void print_out(int n);
//asking the user to enter the input
cout<<"Enter the number whose factorial is to be calculated";
cin>>num;
//calling fact function and storing the returned value in factorial
factorial=fact(num);
cout<<endl<<"Factorial of the number is "<<factorial;
//asking the user to provide input to print the whole numbers
cout<<endl<<"Enter the limit upto which you want to display the whole numbers";
cin>>n;
//calling print_out function
print_out(n);
return 0;
}
//fact() function body
int fact(int num)
{
int f=1;
//checking if the number is 0 the assigning the value of factorial to 1 else calculating the factorial using for loop
if(num==0)
f=1;
else
{
for(int i=1;i<=num;i++)
{
f=f*i;
}
}
return f;
}
//print_out() function body
void print_out(int n)
{
//displaying the whole numbers upto 'n' using for loop
for(int i=0;i<=n;i++)
{
cout<<endl<<i;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.