Introduction
The Fibonacci Series is a series of numbers where each number is the sum of the two preceding numbers. In this lab, you will learn how to write a program in C to generate the Fibonacci Series.
Open the main.c
file
To begin, open the main.c
file in your preferred text editor. This file has been created in the ~/project/
directory.
Declare variables
In this step, you will declare all of the variables that you will be using in the program. The variables required for this program are as follows:
-
num
: An integer to store the number of terms of the Fibonacci Series to be generated. -
a
: An integer to store the first number of the series. -
b
: An integer to store the second number of the series. -
c
: An integer to store the sum of the preceding two numbers. -
i
: An integer to count the number of terms generated so far.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void fibonacci(int num);
int main()
{
int num = 0;
printf("Enter number of terms: ");
scanf("%d", &num);
fibonacci(num);
return 0;
}
Define the fibonacci()
function
In this step, you will define the fibonacci()
function. This function takes one argument, num
, which represents the number of terms of the Fibonacci Series to be generated. The function uses a while
loop to generate the series.
void fibonacci(int num)
{
int a, b, c, i = 3;
a = 0;
b = 1;
if(num == 1)
printf("%d",a);
if(num >= 2)
printf("%d\t%d", a, b);
while(i <= num)
{
c = a + b;
printf("\t%d", c);
a = b;
b = c;
i++;
}
}
Run the program
To run the program, compile and execute the main.c
file. The program will prompt the user to enter the number of terms of the Fibonacci Series to be generated. Once the input is provided, the program will generate the series and display it on the screen.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void fibonacci(int num);
int main()
{
int num = 0;
printf("Enter number of terms: ");
scanf("%d", &num);
fibonacci(num);
return 0;
}
void fibonacci(int num)
{
int a, b, c, i = 3;
a = 0;
b = 1;
if(num == 1)
printf("%d",a);
if(num >= 2)
printf("%d\t%d", a, b);
while(i <= num)
{
c = a + b;
printf("\t%d", c);
a = b;
b = c;
i++;
}
}
Summary
In this lab, you learned how to write a C program to generate the Fibonacci Series. You were introduced to the concept of functions and loops. You also learned how to declare and define variables in C. Finally, you were able to write a program that prompts the user to enter the number of terms of the Fibonacci Series to be generated and generates the series accordingly.
Want to learn more?
- 🚀 Practice Fibonacci Series Generation in C
- 🌳 Learn the latest C Skill Trees
- 📖 Read More C Tutorials
Join our Discord or tweet us @WeAreLabEx ! 😄
Top comments (0)