Lab Manual PPS

Program to construct a Fibonacci series up to n terms.

Write a program to construct a Fibonacci series in C upto n terms

Code : Fibonacci series in C

/******************************************************************************

  fibonacci series = 0 1 1 2 3 5 8....
  default values = 0 and 1 starting two values
  formula = f(n) = f(n-1)+ f(n-2)
  means we will add previous two values to get the next one.
  
  input = n no. of terms
  process = calculate each term by adding previous value
  output = the series.

*******************************************************************************/
#include <stdio.h>

int main()
{
    int i,n, next, t1=0, t2=1 ;
    printf("enter no. of terms:");
    scanf("%d", &n);
    printf("%d, ", t1);
    printf("%d, ", t2);
    for(i=1; i<=n-2; i++)
    {
        next = t1+t2;
        t1=t2;
        t2=next;
        printf("%d, ", next);
    }
     
    

    return 0;
}

Description

This code is written to generate the Fibonacci series in c up to a specified number of terms entered by the user.

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, starting from 0 and 1.

The code begins by declaring the required variables: i, n, next, t1 and t2. The variable i is used as a loop counter, n is used to store the number of terms to be generated, next is used to store the next number in the sequence, and t1 and t2 are used to store the two preceding numbers.

The program prompts the user to enter the number of terms they want to generate and then reads it using the scanf() function.

The program then prints the first two terms of the sequence, which are always 0 and 1 respectively.

The for loop is used to generate the remaining terms of the series. It iterates from i=1 to n-2, as the first two terms of the series have already been printed. In each iteration, the program calculates the next term by adding the two preceding terms and stores it in the variable next. It then updates the values of t1 and t2 by moving them one position forward in the series. Finally, the program prints the value of next.

Once the loop completes, the program ends and the Fibonacci series up to the specified number of terms is printed on the screen.

Output

enter no. of terms: 9
0, 1, 1, 2, 3, 5, 8, 13, 21,