Example Programs
Program to Find the Sum of Fibonacci Series in C
# include
<stdio.h>
# include
<conio.h>
void
main()
{
int
a = -1, b = 1, c = 0, i, n, sum = 0 ;
clrscr()
;
printf("Enter
the limit : ") ;
scanf("%d",
&n) ;
printf("\nThe fibonacci series
is : \n\n") ;
for(i
= 1 ; i <= n ; i++)
{
c
= a + b ;
printf("%d
\t", c) ;
sum = sum + c ;
a
= b ;
b = c ;
}
printf("\n\nThe
sum of the fibonacci series is : %d", sum) ;
getch() ;
}
Output of above program
Enter the
limit : 5
The
fibonacci series is : 0 1 1 2 3
The sum of
the fibonacci series is : 7
Program to Find the Factorial Series in C
#include
<stdio.h>
int main()
{
int
c, n, fact = 1;
printf("Enter
a number to calculate it's factorial\n");
scanf("%d",
&n);
for
(c = 1; c <= n; c++)
{
fact
= fact * c;
}
printf("Factorial
of %d = %d\n", n, fact);
return
0;
}
Output of above program
Enter a
number to calculate it's factorial
6
Factorial
of 6 = 720
Program to Find the Factorial Series Using Recursion
in C
#include<stdio.h>
long
factorial(int);
int main()
{
int n;
long f;
printf("Enter an integer to
find factorial\n");
scanf("%d", &n);
if (n < 0)
{
printf("Negative
integers are not allowed.\n");
}
else
{
f = factorial(n);
printf("%d! =
%ld\n", n, f);
}
return 0;
}
long
factorial(int n)
{
if (n == 0)
{
return 1;
}
else
{
return(n *
factorial(n-1));
}
}
Program to check if given number is Prime or not in C
#include<stdio.h>
#include<conio.h>
void main()
{
int
n,i,m=0,flag=0;
clrscr();
printf("Enter the
number to check prime:");
scanf("%d",&n);
m=n/2;
for(i=2;i<=m;i++)
{
if(n%i==0)
{
printf("Number is not
prime");
flag=1;
break;
}
}
if(flag==0)
printf("Number is
prime");
getch();
}
Output of above program
#include<stdio.h>
#include<conio.h>
void main()
{
int
n,i,m=0,flag=0;
clrscr();
printf("Enter the
number to check prime:");
scanf("%d",&n);
m=n/2;
for(i=2;i<=m;i++)
{
if(n%i==0)
{
printf("Number is not
prime");
flag=1;
break;
}
}
if(flag==0)
printf("Number is
prime");
getch();
}
Output of above program
Output of above program
Result 1
Enter the number to check prime:56
Number is not prime
Result 2
Enter the number to check prime:23
Number is prime
Result 1
Enter the number to check prime:56
Number is not prime
Enter the number to check prime:23Result 2
Number is prime
Comments
Post a Comment