Answer to Question #160255 in C++ for Moeez Azam

Question #160255

Write a C++ program that inputs a positive number form user and program will display its factorial. For example (factorial of 4 = 1x2x3x4 which equals to 24)



1
Expert's answer
2021-01-31T10:16:29-0500
#include <iostream>

//factorial function
unsigned int fact(unsigned int n) {
	if (n <= 1) //edge case, factorial of 0 is 1
		return 1;
	return n * fact(n - 1); //recursive call with n reduced by one
}

int main() {
	unsigned int num;
	std::cout << "Enter positive number: ";
	std::cin >> num;
	std::cout << "Factorial of " << num << " is " << fact(num) << std::endl;
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog