Home  >  Article  >  Backend Development  >  Given a number, write a C program to find the Fibonacci Sequence

Given a number, write a C program to find the Fibonacci Sequence

王林
王林forward
2023-09-02 23:49:06984browse

Given a number, write a C program to find the Fibonacci Sequence

The Fibonacci sequence is a series of numbers obtained by adding the previous two numbers.

The Fibonacci sequence starts with two numbers f0 and f1.

The initial values ​​of fo and f1 can be 0, 1 or 1, 1.

Fibonacci sequence satisfies the following conditions:

fn = fn-1 fn-2

Algorithm

Refer to the algorithm of Fibonacci sequence.

START
Step 1: Read integer variable a,b,c at run time
Step 2: Initialize a=0 and b=0
Step 3: Compute c=a+b
Step 4: Print c
Step 5: Set a=b, b=c
Step 6: Repeat 3 to 5 for n times
STOP

Example

The following is a C program using a While loop to generate the Fibonacci sequence:

Online Demonstration

#include <stdio.h>
int main(){
   int number, i = 0, Next, first = 0, second = 1;
   printf("</p><p> Please Enter the Range Number: ");
   scanf("%d",&number);
   while(i < number){
      if(i <= 1){
         Next = i;
      }
      else{
         Next = first + second;
         first = second;
         second = Next;
      }
      printf("%d \t", Next);
      i++;
   }
   return 0;
}

Output

When the above program is executed, it produces the following results −

Please Enter the Range Number: 6
0 1 1 2 3 5

The above is the detailed content of Given a number, write a C program to find the Fibonacci Sequence. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete