C++ Factorial of a Given Number Program

Beginner

Introduction

In this lab, we will learn how to find the factorial of a given number using the C++ programming language. In mathematics, the factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n.

Include the necessary libraries

We will be using the iostream library, which is used for standard input and output in C++. Add the following line of code to the beginning of your program:

#include <iostream>
using namespace std;

Define the main() function

The main function is the entry point of a C++ program. All C++ programs must have a main function. Add the following code to your program:

int main()
{
    // Code goes here
    return 0;
}

Print a welcome message

Add the following code to your program to print a welcome message:

cout << "\n\nWelcome to my Factorial program :-) \n\n\n";

Ask the user for input

Next, we will ask the user to enter a number to find the factorial for. Add the following code to your program:

int n;
cout << "Enter a number to find factorial: ";
cin >> n;

Calculate the factorial

We will use a loop to calculate the factorial of the number entered by the user. The loop will multiply all the numbers from 1 to n. Add the following code to your program:

//as we are dealing with the product, it should be initialized with 1.
int factorial = 1;
for (int i = 1; i <= n; ++i)
{
    factorial *= i; // same as factorial = factorial * i
}

Print the factorial

Finally, let's print the factorial of the number entered by the user. Add the following code to your program:

cout << "The factorial of " << n << " is: " << factorial << endl;

Compile and run the program

You can compile the program using the following command:

g++ main.cpp -o main && ./main

The program will ask the user to enter a number, and then it will calculate and print the factorial of that number.

Summary

In this lab, we learned how to find the factorial of a given number using the C++ programming language. We used a loop to calculate the factorial by multiplying all the numbers from 1 to n. Finally, we printed the factorial of the number entered by the user.

Other Tutorials you may like