Dr. A.P.J. Abdul Kalam Technical University, Lucknow
KCS151 / KCS251 Programming for Problem Solving - Using C Language
Lab Exercises
18. Write a program to find the sum of the Fibonacci series using a function.
/*
File: Prgrm18.c
Author: Aditya Saini
Date: Jan 17, 2021
Description: Program to find the sum of the Fibonacci series using a function.
*/
#include <stdio.h>
int sum_of_fibona (int);
int main (void)
{
int terms;
int sum;
//Input number of terms
printf ("Input number of terms: ");
scanf ("%d", &terms);
//Function call
sum = sum_of_fibona (terms);
//Print result
printf ("Sum of Fibonacci Series: %d", sum);
};
int sum_of_fibona (int terms)
{
int previous, current, next;
int sum;
int i;
previous = 0;
current = 1;
if (terms >= 3)
{
printf ("%d terms of Fibonacci Series: %d %d ", terms, previous, current);
sum = 1;
for (i = 3; i <= terms; i++)
{
next = previous + current;
printf ("%d ", next);
sum = sum + next;
previous = current;
current = next;
}
printf ("\n");
}
else if (terms == 2)
{
sum = 1;
printf ("%d terms of Fibonacci Series: %d %d\n", terms, previous, current);
}
else
sum = 0;
//Return sum
return sum;
};
Output
Input number of terms: 10
10 terms of Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
Sum of Fibonacci Series: 88
No comments:
Post a Comment
Please do not post spam links.