ADVERTISEMENT
Fibonacci Series
This code generates a Fibonacci series by calculating the next number in the series as the sum of the two previous numbers. The user specifies how many Fibonacci numbers they want to generate by entering a value for num. The program prints the initial Fibonacci numbers and then continues to calculate and print subsequent numbers in the series until it reaches the specified length.
#include<stdio.h>
main()
{
int a=0,b=1,num,c,count;
printf("Enter a number to obtain fibonacci series\n");
scanf("%d",&num);
printf("The series is\n");
printf("%d \n%d\n",a,b);
count=2;
while(count<num)
{
c=a+b;
a=b;
b=c;
printf("%d\n",c);
count++;
}
}C Programming ExamplesExplanation:
This C program generates a Fibonacci series based on user input. The Fibonacci series starts with 0 and 1, and each subsequent number is the sum of the previous two numbers. Here’s a step-by-step explanation of the code:
Header Files:
- The program includes the standard C library header <stdio.h> for input and output operations.
Main Function:
- The main function is the entry point of the program.
Variable Declaration:
Several variables are declared:
- a and b (int): These variables are used to store the first two Fibonacci numbers, which are initialized to 0 and 1, respectively.
- num (int): It stores the user’s input number, which represents the length of the Fibonacci series.
- c (int): It is used to calculate the next Fibonacci number.
- count (int): It counts the number of Fibonacci numbers generated and is initialized to 2 since the first two numbers are already given.
User Input:
- The program prompts the user to enter a number with the message: “Enter a number to obtain the Fibonacci series”.
- The user’s input is read and stored in the num variable using scanf.
Printing Initial Fibonacci Numbers:
- The code prints the first two numbers of the Fibonacci series, which are 0 and 1.
Fibonacci Series Calculation:
- The program enters a while loop that continues until count is less than num.
- Inside the loop, the next Fibonacci number (c) is calculated as the sum of the previous two numbers (a and b).
- The variables are updated to prepare for the next iteration:
- a is assigned the value of b.
- b is assigned the value of c.
- The calculated Fibonacci number c is then printed, and the count is incremented.
End of Program:
- The program reaches the end of the main function and terminates.