Explanation
To print the first 'n' Fibonacci terms with a function in C, you can create a function that takes 'n' as an argument and prints 'i * Fibonacci' for each term 'i' from 1 to 'n'. Here's an example of how you can achieve this:
#include <stdio.h>
// Function to print the i-th Fibonacci term
void printIFibonacci(int n) {
int a = 0, b = 1, c;
for (int i = 1; i <= n; i++) {
// Print i * Fibonacci
printf("%d * Fibonacci: %d\n", i, a);
c = a + b;
a = b;
b = c;
}
}
int main() {
int n;
printf("Enter the number of Fibonacci terms to print: ");
scanf("%d", &n);
printIFibonacci(n);
return 0;
}
In this code:
-
The printIFibonacci function takes the number of Fibonacci terms to print ('n') as an argument.
-
Inside the function, a loop runs from 1 to 'n', and it prints 'i * Fibonacci,' where 'i' is the term number, and 'a' represents the Fibonacci value.
-
The Fibonacci sequence is calculated using two variables 'a' and 'b,' and the loop updates them in each iteration to calculate the next term in the sequence.
-
The main function prompts the user to enter the number of Fibonacci terms they want to print and then calls the printIFibonacci function with the specified 'n'.