Problem Solving Through C (BCA) 1st Sem Previous Year Solved Question Paper 2022

Practice Mode:
8.

Define a function to print ith Fibonacci where term i is passed as argument to the function. Use this function to print first n Fibonacci terms.

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:

  1. The printIFibonacci function takes the number of Fibonacci terms to print ('n') as an argument.

  2. 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.

  3. 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.

  4. 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'.