Call us at 0700-922-6559 or Click here

Write a program to find the factorial of a number.

#include <iostream>

using namespace std;

int main() {

 // Declare variables with Indian names

 int priya_age = 5;

 long long factorial = 1;  // Use long long to handle larger factorials

 // Calculate factorial using a loop

 for (int i = 1; i <= priya_age; ++i) {

   factorial *= i;  // Multiply factorial by each number from 1 to priya_age

 }

 cout << “The factorial of ” << priya_age << ” is ” << factorial << endl;

 return 0;

}

Output:

The factorial of 5 is 120

Here’s a step-by-step explanation of the code:

1. Header and Namespace:

  • #include <iostream>: Includes the iostream header for input/output operations.
  • using namespace std;: Brings the std namespace into scope for convenient use of elements like cin, cout, and endl.

2. Main Function:

  • int main(): The main function where program execution begins.

3. Variable Declaration:

  • int priya_age = 5;: Declares an integer variable named priya_age and initializes it with the value 5 (representing Priya’s age).
  • long long factorial = 1;: Declares a long long variable named factorial to store the factorial result. It’s initialized to 1 because the factorial of any number multiplied by 1 is that number itself.

4. Factorial Calculation:

  • for (int i = 1; i <= priya_age; ++i) { … }: This loop iterates from 1 up to the value of priya_age.
  • factorial *= i;: Inside the loop, the current value of factorial is multiplied by the loop counter i. This effectively calculates the factorial by multiplying consecutive numbers from 1 up to priya_age.

5. Output:

  • cout << “The factorial of ” << priya_age << ” is ” << factorial << endl;: Prints the calculated factorial to the console, along with a descriptive message.

6. Return Statement:

  • return 0;: Indicates successful program termination.

Leave a Reply

Your email address will not be published. Required fields are marked *