215k views
4 votes
. Write a recursive function names factorial to compute the factorial of the parameter. Also write the main function, where you ask the user to input a non-negative integer number. Then call the function factorial and display the result.

User Bbb
by
4.4k points

1 Answer

1 vote

Answer:

Following are the code in c language

#include <stdio.h> // header file

long int factorial(int n); // declaration of factorial function

int main() // main function

{

int n; // variable declaration

printf("Enter a positive integer: ");

scanf("%d", &n); // input number

while(n<0) // checking the condition if number is negative

{

printf("please enter a positive number:");

scanf("%d", &n);

}

printf("Factorial of %d = %ld", n, factorial(n)); // calling factorial function

return 0;

}

long int factorial(int n1) // recursive definition of factorial

{

if (n1 >= 1)

return n1*factorial(n1-1);

else

return 1;

}

Step-by-step explanation:

In this program, it ask for a positive number input. if the value enter by user is negative then it again ask for positive input i.e positive number. Then it calls the recursive function of factorial. the recursive function factorial calculate the factorial recursively. suppose user input 4 then it goes to the if part of program i.e return n*factorial(n-1); that means return 4*factorial(3) again recursive function call itself .this process repeated until it meets the base condition. when a base condition meets, it return factorial of the given number.

output

Enter a positive integer: 5

factorial of 5=120

Enter a positive integer: -8

please enter a positive number:4

factorial of 4=24

User Tot Zam
by
5.5k points