C program to find nth term of Fibonacci series unlimited number | Unlimited Fibonacci series in C Language | upto nth number Fibonacci series in C language
#define MAX 2100
#include
#include
#include
void print(char x[]);
void add(char x[], char y[], char z[]);
int main()
{
int i=0,j,num;
char n_minus1[MAX]="1",n_minus2[MAX]="1",nth[MAX]="";
printf("This is a program to print fibonacci sequence upto desired term.(max 10000)\n");
printf("\nenter a natural number upto which do you want fibonacci series\n");
scanf("%d",&num);
if( num<1||num>10000)
{
printf("The desired term index was either invalid or greater than 10000\n");
exit(0);
}
printf("\noptions:\n1. print only %dth term\n2. print all terms\n",num);
scanf("%d",&j);
switch(j)
{
case 1:
if(num<2){
printf("The first term is 1\n");
break;
}
if(num<3){
printf("The second term is 1\n");
break;
}
for(i=2;i<num;i++)
{
add(nth,n_minus1,n_minus2);
strcpy(n_minus2,n_minus1);
strcpy(n_minus1,nth);
}
printf("The %dth term is ",num);
print(nth);
break;
case 2: printf("\nFibonacci series upto %dth term\n\n",num);
printf("term \tvalue\n",num);
printf("%4d \t1\n",1);
if(num<2)
break;
printf("%4d \t1\n",2);
if(num<3)
break;
for(i=2;i<num;i++)
{
add(nth,n_minus1,n_minus2);
printf("%4d\t",i+1);
print(nth);
strcpy(n_minus2,n_minus1);
strcpy(n_minus1,nth);
}
break;
default: printf("Invalid choice...!!! \tExiting\n");
exit(0);
}
printf("\n\nprgram finished successfully.\t press any key to continue\n");
getchar();
return 0;
}
void print(char x[])
{
int i;
for(i=strlen(x)-1;i>=0;i--)
{
putchar(x[i]);
if(i%5==0)
putchar(' ');
}
putchar('\n');
return;
}
void add(char x[],char y[],char z[])
{
int i,ylen,zlen,equal;
char c = 0,temp;
ylen = strlen(y);
zlen = strlen(z);
equal = (ylen == zlen) ? 1 : 0;
for(i=0;i<zlen;i++)
{
x[i]=c + y[i] + z[i] - '0';
if( x[i]-'0' > 9)
{
x[i]-=10;
c=1;
}
else
c=0;
}
if(equal)
{
if(c!=0)
{
x[i]=c + '0';
x[i+1]='\0';
}
}
else
{
x[i]=c + y[i];
x[i+1]='\0';
}
return;
}
Related Links :
No comments:
Post a Comment