Computer for SEE and NEB

It is a complete SEE and NEB solution for computer science. It includes Computer Fundamentals, Database (SQL), Programming in C QBASIC, CSS, JavaScript, and PHP for beginners.

Breaking

Post Top Ad

Your Ad Spot

Sunday, July 31, 2022

C program to display fibonacci series

 C program to display Fibonacci series 




Introduction:


The Fibonacci series is a popular mathematical sequence that has fascinated mathematicians and computer scientists alike. In this blog post, we will discuss how to write a C program to display the Fibonacci series.

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones. The sequence starts with 0 and 1, and the subsequent numbers are the sum of the previous two. The first few numbers in the Fibonacci series are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, and so on.

To display the Fibonacci series, we can use a loop to generate the sequence. 

Here's the code to do that:

#include<stdio.h>
int main()
{
int a=1,b=1,i;
for(i=1;i<=5;i++)
{
printf("%d\t%d\t",a,b);
a=a+b;
b=a+b;
}
return 0;
}

Output:




Another method:

#include <stdio.h>
int main()
{
int n, i, first = 0, second = 1, next;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 0; i < n; i++) 
{
if (i <= 1)
next = i;
else 
{
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
}
return 0;
}



Let's go through the code step-by-step:

  1. We declare four integer variables: n, i, first, second, and next.
  2. We prompt the user to enter the number of terms in the Fibonacci series and store it in the variable n.
  3. We initialize the variables first and second to 0 and 1, respectively.
  4. We print the message "Fibonacci Series:" to indicate that we are going to print the sequence.
  5. We use a loop to generate the Fibonacci series. For the first two terms, we simply print 0 and 1. For subsequent terms, we calculate the next number in the sequence by adding the previous two numbers (first and second). We then update the value of first to second and second to next.
  6. We print each number in the sequence using the printf() function.

Conclusion:

In conclusion, we have discussed how to write a C program to display the Fibonacci series. The program uses a for loop to iterate through each term in the sequence and calculate the value of the next term using the previous two terms. By understanding the logic behind the program, you can modify it to display the sequence in reverse order or to display only even or odd terms in the sequence.

You can also read:


No comments:

Post a Comment

Post Top Ad

Your Ad Spot

Pages