In this tutorial we are going to learn how to print Fibonacci series in c program using iterative method.
In this series number of elements of the series is depends upon the input of users. Program will print n number of elements in a series which is given by the user as a input.
Before moving directly on the writing Fibonacci series in c program, first you should know
What is Fibonacci Series?
A Fibonacci series is a series in which next number is a sum of previous two numbers.
For example : 0, 1, 1, 2, 3, 5, 8 ……
In Fibonacci Series, first number starts with 0 and second is with 1 and then its grow like,
0 + 1 = 1
1 + 1 = 2
1 + 2 = 3
2 + 3 = 5 and
How our program will behave?
Suppose if someone gives an input 5 then our program should print first 5 numbers of the series.
Like if someone given 5 as a input then our Fibonacci series which is written in C should print output as,
0, 1, 1, 2, 3
C program to print Fibonacci series program in c using Iterative methods
- In the above program I have taken 5 variables of integer type.
- Variables are n, i, first, second and result.
- Variable first and second has assigned value 0 and 1 respectively. Because we have assumed that out first and second number of this is series is fixed. And the further numbers we will calculate on the basis of these two first elements.
- Now we have a “for loop” here where the complete logic is written. This loop will be execute n number of times which is given as input.
- result is a variable which will hold the final result and print each time. If the input is given 0 then program will print 0 and if input is 1 then it will print 0, 1.
- But if it greater than 1 then calculation required and as per calculation it will print the output.
- For 3rd element of the series result will hold the sum of first and second number. And after calculation now second element will become first element and and result will become second element.
- This logic will be apply for the calculation of all next elements of the Fibonacci series.
I hope you enjoyed it and learnt it.
Please Share :
Next QuestionsQ3). What is data type? Write the all built-in data type of C.