# Calculate nth fibonacci Number using C program

### Description :

This program accepts one integer(n) as input and calculate the nth number in Fibonacci Series. As we discussed earlier Fibonacci series starts with 0 and 1. so 0 is the 0th  Fibonacci number and 1 is 1st Fibonacci Number. like this our program will calculate nth Fibonacci number.

• 0 : 0
• 1 : 1
• 2 : 1
• 3 : 2
• 4 : 3
• 5 : 5
• 6 : 8
• 7 : 13
• 8 : 21
• 9 : 34
• 10 : 55

### Program :

1. /* C program to calculate nth Fibonacci Number
2.  * Author : Venkatesh Macha
3.  */
4. #include<stdio.h>
5. void main()
6. {
7.         int i,j,k,num,cnt;
8.         printf(“Enter which fibonacci number you want to print : “);
9.         scanf(“%d”,&num);
10.         /* First two numbers in Fibonacci Series is 0 and 1 so
11.          * so i am assuming i and j as first and Second Numbers in
12.          * in Fibonacci Series
13.         */
14.         i=0;
15.         j=1;
16.         k=i+j;
17.         if(num==0)
18.         {
19.                 printf(“1st Number in Fibonacci Series is : %dn,i);
20.                 return;
21.         }
22.         if(num==1)
23.         {
24.                 printf(“2nd Number in Fibonacci Series is : %dn,j);
25.                 return;
26.         }
27.         /* cnt is 1 because we already have i and j as first two numbers i.e 0th and 1st numbers */
28.         cnt=1;
29.         for(cnt;cnt<num1;cnt++)
30.         {
31.                 i=j;
32.                 j=k;
33.                 k=i+j;
34.         }
35.         printf(“%dth Number in Fibonacci series is : %dn,num,k);
36.         return;
37. }

### Output :

Note : If you try to calculate above 46th Fibonacci Number, you will get invalid values (invalid valid means negative values or wrong values ) you can overcome this problem by using long long Integer for i,j,k variables. Above program i used Long int so its max size is 2 giga plus. so up to 46th Fibonacci value i got correct values but when i try to calculate 47th one i got Negative Values. actually 47th Fibonacci number is  2971215073.

### Related Articles :

Venkatesh Macha

Hi Guys, I am Venkatesh Macha. I am a programmer and an Open Source enthusiast, Presently working as a Software Engineer. Apart from that, I love to explore new technologies and things.