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

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

王林
Release: 2023-09-02 23:49:06
forward
1026 people have browsed it

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
Copy after login

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;
}
Copy after login

Output

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

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template