Calculate the N-th term UN of the FIBONACCI sequence that is given by the recurrence relation:
\(U_1=1 \ \ \ U_2=1 \ \ \ U_N=U_{N-1}+ U_{N-2}\) (for N>2)
Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
int main()
{
int U1, U2, UN;
int N;
int I;
do{
printf("Enter N : ");
scanf("%d", &N);
}while(N<1);
U1=U2=1;
if (N==1)
UN=U1;
else
if (N==2)
UN=U2;
else
for (I=3 ; I<=N ; I++)
{
UN = U1+U2;
U1 = U2;
U2 = UN;
}
printf("Fibonacci sequence at term %d : %d\n", N, UN);
return 0;
}
****************************************************
****************************************************
FIBONACCI - INT / LONG
****************************************************
****************************************************
#include <stdio.h>
#include <limits.h>
int main()
{
int U1, U2, UN;
int I;
UN=U1=U2=1;
I=3;
while(1)
{
UN = U1+U2;
if(UN<0) break;
U1 = U2;
U2 = UN;
I++;
}
printf("Fibonacci sequence at term %d : %d\n", --I, U2);
return 0;
}
// Fibonacci sequence at term 46 : 1836311903
****************************************************
****************************************************
FIBONACCI - LONG LONG
****************************************************
****************************************************
#include <stdio.h>
#include <limits.h>
int main()
{
long long U1, U2, UN;
int I;
UN=U1=U2=1;
I=3;
while(1)
{
UN = U1+U2;
if(UN<0) break;
U1 = U2;
U2 = UN;
I++;
}
printf("Fibonacci sequence at term %d : %lld\n", --I, U2);
return 0;
}
// Fibonacci sequence at term 92 : 7540113804746346429
****************************************************
****************************************************
FIBONACCI - DOUBLE
****************************************************
****************************************************
#include <stdio.h>
#include <limits.h>
#include <math.h>
int main()
{
double U1, U2, UN;
int I;
UN=U1=U2=1;
I=3;
while(1)
{
UN = U1+U2;
if(isinf(UN)) break;
U1 = U2;
U2 = UN;
I++;
}
printf("Fibonacci sequence at term %d : %e\n", --I, U2);
return 0;
}
//Fibonacci sequence at term 1476 : 1.306989e+308
****************************************************
****************************************************
FIBONACCI - LONG DOUBLE
****************************************************
****************************************************
#include <stdio.h>
#include <limits.h>
#include <math.h>
int main()
{
long double U1, U2, UN;
int I;
UN=U1=U2=1;
I=3;
while(1)
{
UN = U1+U2;
if(isinf(UN)) break;
U1 = U2;
U2 = UN;
I++;
}
printf("Fibonacci sequence at term %d : %Le\n", --I, U2);
return 0;
}
//Fibonacci sequence at term 23601 : 9.285655e+4931
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Finding a value in an array using jump search