Ex: write a C program to print factorial of given number using function. How to write a C program to print factorial of the given number using function. C program to print factorial of given number using function.
Input from user:
Enter the number: 5
Expected output:
Factorial of given number is 120.
In this program we will used recursion function
to find factorial of given number.
In short recursion function means- function calling it self that means call a function inside the same function then it is called a recursive call of the function.
1. First declare function give it meaningful name fact().
2. Inside the main() accept input (number) from user declare variable say no.
3. Call the fact() inside the printf() directly (It will print returned value means factorial of given number).
4. In the body of fact() use one if statement to check number is less than 1. If it is less than or equal to 1 return 1.
5. Otherwise use following factorial logic no=no*fact(no).
After that return no.
#include<stdio.h>
int fact(int no);
void main()
{
int no;
printf("Enter the number\n");
scanf("%d",&no);
printf("Factorial of given number is %d",fact(no));
}
int fact(int no)
{
if(no<=1)
{
return 1;
}
else
{
no=no*fact(no-1);
return no;
}
}
Above program shows the following output:
Input from user:
Enter the number: 5
Expected output:
Factorial of given number is 120.
In this program we will used recursion function
to find factorial of given number.
In short recursion function means- function calling it self that means call a function inside the same function then it is called a recursive call of the function.
Step by step logic to print factorial of given number using function:
1. First declare function give it meaningful name fact().
2. Inside the main() accept input (number) from user declare variable say no.
3. Call the fact() inside the printf() directly (It will print returned value means factorial of given number).
4. In the body of fact() use one if statement to check number is less than 1. If it is less than or equal to 1 return 1.
5. Otherwise use following factorial logic no=no*fact(no).
After that return no.
C program to print factorial of given number using function:
#include<stdio.h>
int fact(int no);
void main()
{
int no;
printf("Enter the number\n");
scanf("%d",&no);
printf("Factorial of given number is %d",fact(no));
}
int fact(int no)
{
if(no<=1)
{
return 1;
}
else
{
no=no*fact(no-1);
return no;
}
}
Above program shows the following output:
No comments:
Post a Comment
If you have any doubts, please discuss here...👇