Table of Contents

## Introduction

In this program, you will learn to display the Fibonacci sequence of first n numbers.

The value of n will be entered by the user.

Fibonacci sequence always starts from 0,1 i.e., the first two members of this series remain fixed, and the next member is the sum of the previous two members.

For example**, 0,1,1,2,3,5,8,13………….. **is a Fibonacci sequence

To understand this program, you should know about

1. Operators in C

2. for loop in C

## Program

#include<stdio.h> int main() { int x=0; // x is the first term initilaized with 0 int y=1; // y is the second term initilaized with 1 int n; // n is the number of terms in sequence printf("Enter an integer:"); scanf("%d",&n); printf("Fibonacci sequence up to %d is\n0,1",n); int next_term=x+y; for(int i=3;i<=n;i++) // for rest of the sequence { printf(",%d",next_term); x=y; y=next_term; next_term=x+y; } }

## Output

## Explanation

As we already know, the first and second term of a Fibonacci sequence is 0 and 1, respectively that’s why ‘x’ and ‘y’ are initialized with the respective values.

n is the variable that stores the value up to which we want to print the Sequence.

**int next_term=x+y;**

Here, we are printing the 3^{rd} term i.e., the sum of x and y(0+1) thus, next_term=1.

After that, for the rest of the sequence, we use the ‘for’ loop.

**for(int i=3;i<=n;i++) **

‘i’ is initialized with 3 and iterates upto ‘n’.

Then the code written below will work accordingly until ‘i’ becomes equal to ‘n’.

** {**

** printf(“,%d”,next_term);**

** x=y;**

** y=next_term;**

** next_term=x+y;**

** }**

i=3; x=0; y=1; next_term=1

i=4; x=1; y=1; next_term=2

i=5; x=1; y=2; next_term=3

and so on.

## 0 Comments