C Program to print The Fibonacci Series upto nth term

Write a C program to print the nth term of the Fibonacci series. In this C programming example, Let’s write C code find the nth term of the Fibonacci series

What is the Fibonacci Series?

Fibonacci series is the successive sum of two preceding terms to give the next one

the sequence is always  like 0,1,1,2,3,5,8,13,21,34,55…. and so on

here if we took any digit let say 8 its’s summed up by preceding two digits that are 3 and 5

Algorithm of Fibonacci Series

  • Include the library and declaring the main method
  • Initializing the variable and take input
  • Check the taken input whether valid or invalid
  • Performing the operation on it logically
  • Printing appropriate message at the end

C Program to print The Fibonacci Series up to nth number

#include<stdio.h>
void main(){
  int a,b,n,i,c;
  printf("enter the nth term :");
  scanf("%d",&n);
  a=0,b=1; 
  if(n<0){
    printf("enter valid number");
  }
  else if(n==1){
    printf("%d",a);
  }
  else{
  printf("%d ",a);
  printf("%d ",b);
  for(i=2;n>i;i++){
    c=a+b;
    a=b;
    b=c;
    printf("%d ",c);
    }
  }	
}

Explanation of the Code

On-Line no:1 including the library to take and give input and output respectively

On-Line no:2 declaring the main method with void as return type

On-Line no:3  declaring the variables as per the requirements

On-Line no:4 print a message for the user

On-Line no:5 take input from user using scanf method

On-Line no:6 initializing the variable with values

On-Line no: 7  now we check the input value for valid input which means the input should be greater than zero

On-Line no:8 if it is smaller than zero we print a message of invalid input

On-Line no:9 closing the scope of the if condition

On-Line no:10 now using else if we check another condition

On-Line no:11 if it is equal to one we print output according to logic

On-Line no:12 closing the scope of the else if condition

On-Line no:13  here we create else part to check for the remaining number which user can give

On-Line no:14 printing the first term of Fibonacci series

On-Line no:15 printing the second term of Fibonacci series

On-Line no:16 for the further terms we have to run a loop that will start from 2 and run until the value reached to inputted term by the user with increment each time

On-Line no:17 using a variable we dump the value of the added values

On-Line no:18 and On-Line no:19 swapping the values of variables for further

On-Line no:20  printing the result we get from logic we fixed

Closing the scope of the different scopes we used

Output

In this blog, we learned how to create a Fibonacci series program  and print the nth term of Fibonacci series