Explanation
The program prints the Fibonacci series up to a number entered by the user.
Header
The code begins with including the standard input-output header file using #include <stdio.h>.
Variable Declaration
The main() function is defined, and four integer variables d, m, j, and o are declared. Variables m and j are initialized to 0 and 1, respectively, to represent the first two terms of the Fibonacci series, and o is used to store the next term in the series.
Program Description
The program prints a description message for the user to understand its functionality and explains what the Fibonacci series is.
User Input
The user is prompted to enter a number up to which they want to generate the Fibonacci series. The input is read using scanf("%d", &d);.
Fibonacci Series Calculation
The program starts the Fibonacci series with the first two terms (0 and 1) and calculates the subsequent terms using a while loop:
printf("Fibonacci Series till the entered number %d is: %d, %d, ", d, m, j);: Prints the first two terms.o = m + j;: Calculates the next term in the series.while (o <= d): Continuously checks if the next termois less than or equal to the entered numberd.printf(", %d", o);: Prints the current termo.m = j;: Updatesmto the value ofj.j = o;: Updatesjto the value ofo.o = m + j;: Calculates the next term in the series.
Program End
The program ends with printf("\n"); to print a new line and return 0; to indicate successful execution.
Code
/*
* -----------------------------------------------------------
* Logic Building with Computer Programming (CSU1128)
* Instructor: Dr. Pankaj Vaidya | Author: Divya Mohan
*
* This code is a part of the educational initiative by dmj.one
* with aim of empowering and inspiring learners in the field of
* Computer Science and Engineering through the respective courses.
*
* (c) 2022, Divya Mohan for dmj.one. All rights reserved.
* -----------------------------------------------------------
*/
#include <stdio.h>
int main()
{
int d, m = 0, j = 1, o = 0;
printf("\n\n Program to print the fibonacci series till an entered number.");
printf("Fibonacci series is a series where the number at any point is the sum of previous two numbers.");
printf("Example 9 = 1 2 3 5 8 \n\n");
printf("Enter a number till which you want to count the number of digits (Example: 2100) - and press enter: ");
scanf("%d", &d);
// display the first two terms which is always 0 and 1
printf("Fibonacci Series till the entered number %d is: %d, %d, ", d, m, j);
o = m + j;
while (o <= d)
{
printf(", %d", o);
m = j;
j = o;
o = m + j;
}
printf("\n");
return 0;
}
Output
Program to print the fibonacci series till an entered number. Fibonacci series is a series where the number at any point is the sum of previous two numbers. Example 9 = 1 2 3 5 8
Enter a number till which you want to count the number of digits (Example: 2100) - and press enter:
44
Fibonacci Series till the entered number 44 is: 0, 1, , 1, 2, 3, 5, 8, 13, 21, 34