C Program

Write a program using function to find factorial of a number

Write a C program to pass an array containing age of person to a function
#include <stdio.h> // Include the standard input-output header

// Function to calculate factorial
int factorial(int n) {
int i, p = 1; // Initialize p to 1, which will hold the factorial value

// Loop from n down to 2
for (i = n; i > 1; i--) {
p *= i; // Multiply p by i at each step
}

return p; // Return the calculated factorial
}

int main() {
int a, result; // Declare variables for input number and the result

// Ask the user to input a number
printf("Enter an integer number: ");
scanf("%d", &a);

// Calculate factorial by calling the factorial function
result = factorial(a);

// Display the result
printf("The factorial of %d is %d.\n", a, result);

return 0; // Return 0 to indicate successful execution
}

Explanation:

  1. Function Declaration (factorial): The factorial function takes an integer n as an argument and calculates its factorial using a for loop. It multiplies the variable p with each number starting from n down to 2 and returns the result.

  2. Main Function:

    • It asks the user for an integer input.
    • The factorial is calculated using the factorial function.
    • The result is printed to the screen.

Sample Input/Output:

Input:

Enter an integer number: 5

Output:

The factorial of 5 is 120.

Team Educate

About Author

Leave a comment

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

You may also like

C program to test whether a given identifier is valid or not
C Program

C Program to Test Whether a Given Identifier is Valid or Not

Rules for Valid Identifiers in C: The identifier must begin with a letter or an underscore (_). It cannot start
C program to test whether a given identifier is valid or not
C Program Compiler Design

C program to implement simple code generator

ALGORITHM:1. Start2. Get address code sequence.3. Determine current location of 3 using address (for 1st operand).4. If current location not