Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

AIM: Functions

1.Write a program that calculates the power of a number using a user defined
function
Code:
#include<stdio.h>
int power(int a,int b)
{
if(b==0)
return 1;
else if(a==0)
return 0;
else
return a*power(a,b-1);
}
int main()
{
int a,b;
printf("Enter the Number: ");
scanf("%d",&a);
printf("Enter the power of number: ");
scanf("%d",&b);
printf("The value of power is %d",power(a,b));
return 0;
}
Output:

2.Develop a program to check if a number is prime or not using a function.


Code:
#include<stdio.h>
int prime(int n)
{
if(n<=1)
{
printf("not a composite and ");
return 0;
}
else
for(int i=2;i<=n-1;i++)
{
if(n%i==0)
{
return 0;
}
}
return 1;
}
int main()
{
int n;
printf("Enter the number: ");
scanf("%d",&n);
if(prime(n))
printf("%d is prime",n);
else
printf("%d is not prime",n);
return 0;
}
Output:

3.Create a function to calculate the factorial of a number.


Code:
#include<stdio.h>
int factorial(int n)
{
for(int i=n-1;i>=1;i--)
{
n= n*i;
}
return n;
}
int main()
{
int n,fact;
printf("Enter the value: ");
scanf("%d",&n);
printf("The factorial of %d is %d",n,factorial(n));
return 0;
}
Output:

4.Write a function to find the maximum of three numbers.


Code:
#include<stdio.h>
int maximum(int n1,int n2,int n3)
{
if(n2<n1)
{
if(n3<n1)
return n1;
}
else if(n1<n2)
{
if(n3<n2)
return n2;
}
else if(n1<n3)
{
if(n2<n3)
return n3;
}
}
int main()
{
int n1,n2,n3;
printf("Enter the number 1: ");
scanf("%d",&n1);
printf("Enter the number 2: ");
scanf("%d",&n2);
printf("Enter the number 3: ");
scanf("%d",&n3);
printf("The numbers given by you are %d,%d,%d\n",n1,n2,n3);
printf("The maximum of these numbers is %d.",maximum(n1,n2,n3));
return 0;
}
Output:

5.Implement recursive functions for Fibonacci series,factorial, and any other


suitable problem.
Code:
#include<stdio.h>
int fibo(int a,int x,int y)
{
int fib=0;
x=0;y=1;
for(int i=0;i<a;i++)
{
printf("%d\n",fib);
x=y;
y=fib;
fib=x+y;
}
}
int factorial(int b)
{
for(int i=b-1;i>=1;i--)
{
b=b*i;
}
printf("%d",b);
}
int power(int c,int d)
{
if(d==0)
{
return 1;
}
else if(c==0)
{
return 0;
}
else
{
return c*power(c,(d-1));
}
}
int main()
{
int n,a,b,c,d;
printf("Press \n1 for Fibonacci\n2 for factorial\n3 for power calculation\
n= ");
scanf("%d",&n);

switch(n)
{
case 1: printf("For Fibonacci Series: ");
int x,y,fib=0;
printf("Enter the value: ");
scanf("%d",&a);
fibo(a,x,y);
return 0;

case 2:printf("For Factorial Value: ");


printf("Enter the value: ");
scanf("%d",&b);
factorial(b);
return 0;

case 3:printf("For Power calculation: ");


printf("Enter the number: ");
scanf("%d",&c);
printf("Enter the power: ");
scanf("%d",&d);
printf("%d",power(c,d));
return 0;
}
}
Output:

You might also like