Ques:-12) Write a program to find the factorial value of any number entered through the keyboard.

				
					#include<stdio.h>
#include<conio.h>
void main()
{
  int num,fact=1;
  clrscr();
  printf("\nenter any number:");
  scanf("%d",&num);
  for(num;num>0;num--)
  {
    fact=fact*num;
  }
  printf("factorial is %d",fact);
getch();
}

				
			

Out Put

				
					Enter any number 5
factorial is 120
				
			

Below is a simple C program that calculates the factorial of a number entered by the user.

				
					#include <stdio.h>

// Function to calculate factorial
long long int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

int main() {
    int number;
    long long int result;

    // Prompt user for input
    printf("Enter a number to find its factorial: ");
    scanf("%d", &number);

    // Check for negative input
    if (number < 0) {
        printf("Factorial of a negative number doesn't exist.\n");
    } else {
        // Calculate factorial
        result = factorial(number);
        // Display the result
        printf("Factorial of %d is %lld\n", number, result);
    }

    return 0;
}

				
			

Explanation

  1. factorial Function: This function recursively calculates the factorial of a given number. The base case is when n is 0 or 1, where the factorial is 1. For other values, it calls itself with n-1 and multiplies the result by n.
  2. main Function:
    • Prompts the user to enter a number.
    • Reads the input number.
    • Checks if the entered number is negative, as factorials for negative numbers are undefined.
    • Calls the factorial function to compute the factorial of the number if it is non-negative.
    • Prints the result.

Sample Output

Here are a few sample outputs when the program is executed:

Example 1:

				
					Enter a number to find its factorial: 5
Factorial of 5 is 120

				
			

Example 2:

				
					Enter a number to find its factorial: 0
Factorial of 0 is 1

				
			

Example 3:

				
					Enter a number to find its factorial: -3
Factorial of a negative number doesn't exist.


				
			

This program handles both positive and negative inputs appropriately and calculates the factorial using a recursive function. For very large numbers, you might need to consider using a different method to avoid stack overflow due to recursion depth limits or switch to an iterative approach.

Scroll to Top