In: Computer Science
Write a function, which accepts an integer value as an argument, finds the factorial of that integer value, and then returns the factorial value to the main program. Write a main program that will call the function by passing an integer value and print the factorial value returned by the function.
1. First we create a function called findFactorial .
void findFactorial(int number)
{
}
2. Now we implement logic in out findFactorial function.
2.1: The main logic is to create a variable named factorial and give a value 1 .
void findFactorial(int number)
{
int factorial = 1;
if (number == 0)
{
cout << "Please enter some number";
}
else
{
for (int i = 1; i <= number; i++)
{
factorial = factorial * i;
}
}
cout << "Factorial of " << number << " is: " << factorial;
}
2.2: Now using the if statement we check if the user input value is zero or not
2.3: After that, we show a simple message and use for loop for the main logic
2.4: in for loop we declare variable i and give it value 1 and we say that i is less than user given number and increment the i .
2.5: then we multiply this by factorial variable with i and store in factorial variable and return the variable factorial
3. Now we call in the main function.
int main()
{
int inputInteger;
cout << "Enter an Integer: ";
cin >> inputInteger;
findFactorial(inputInteger);
getch();
}
And the whole program looks like this:
#include
#include
using namespace std;
void findFactorial(int);
int main()
{
int inputInteger;
cout << "Enter an Integer: ";
cin >> inputInteger;
findFactorial(inputInteger);
getch();
}
void findFactorial(int number)
{
int factorial = 1;
if (number == 0)
{
cout << "Please enter some number";
}
else
{
for (int i = 1; i <= number; i++)
{
factorial = factorial * i;
}
}
cout << "Factorial of " << number << " is: " << factorial;
}
#include <iostream>
#include <conio.h>
using namespace std;
void findFactorial(int);
int main()
{
int inputInteger;
cout << "Enter an Integer: ";
cin >> inputInteger;
findFactorial(inputInteger);
getch();
}
void findFactorial(int number)
{
int factorial = 1;
if (number == 0)
{
cout << "Please enter some number";
}
else
{
for (int i = 1; i <= number; i++)
{
factorial = factorial * i;
}
}
cout << "Factorial of " << number << " is: " << factorial;
}