Write a C program to generate Fibonacci series using recursion.
#include <stdio.h>
/* prints first n fibonacci numbers */
void fibonacci(int *num1, int *num2, int *count, int n) {
int temp;
if (*count < n) {
printf("%d ", *num1);
temp = *num1 + *num2;
*num1 = *num2;
*num2 = temp;
*count = *count + 1;
/* recursive call */
fibonacci(num1, num2, count, n);
}
return;
}
int main() {
int num1 = 0, num2 = 1, n, count = 0;
/* get the number of fibonacci numbers needed */
printf("Enter the value for n:");
scanf("%d", &n);
/* prints first n fibonacci numbers */
printf("Fibonacci Series:\n");
fibonacci(&num1, &num2, &count, n);
printf("\n");
return 0;
}
/* prints first n fibonacci numbers */
void fibonacci(int *num1, int *num2, int *count, int n) {
int temp;
if (*count < n) {
printf("%d ", *num1);
temp = *num1 + *num2;
*num1 = *num2;
*num2 = temp;
*count = *count + 1;
/* recursive call */
fibonacci(num1, num2, count, n);
}
return;
}
int main() {
int num1 = 0, num2 = 1, n, count = 0;
/* get the number of fibonacci numbers needed */
printf("Enter the value for n:");
scanf("%d", &n);
/* prints first n fibonacci numbers */
printf("Fibonacci Series:\n");
fibonacci(&num1, &num2, &count, n);
printf("\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the value for n:10
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
Enter the value for n:10
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
No comments:
Post a Comment