QUESTION 9 C programming The Fibonacci number series is defi
QUESTION 9 C programming
The Fibonacci number series is defined as follows:
f(0) = 0, f(1) = 1, and for i > 1, f(i) = f(i-1) + f(i-2).
The first 10 numbers from the series are 0,1,1,2,3,5,8,13,21,34. Thus, f(0)=0, f(1)=1, f(2)=1, f(3)=2, etc.
a) Write in the text box below a function called fib that returns void and that takes as parameters an array v of type int and an integer n that indicates the length of array v. This function computes each Fibonacci number f(i) and saves it to array element v[i], for 0 <= i < n. If parameter n is negative, the function must print an error message and call exit(1).
Hint: when computing element v[i] use v[i-1] and v[i-2].
b) Write a main() function that declares an int array numbers of size N, where N is a constant equal to 100 and then calls the fib function defined above with parameters numbers and N. After that, print all elements from the numbers array to the terminal.
Ensure the code is correct, aligned, and indented properly. Use meaningful variable names.
Solution
#include <stdio.h>
#include <stdlib.h>
//fib method
void fib(int v[],int n ){
//if n is negative print error message and exit
if(n < 0){
printf(\"Entered n is negative !! \ \");
exit(1);}
else{
v[0]=0; //first term in series is 0
v[1]=1; //Second term in series is 0
int i; //loop variable
for(i=2;i<n;i++)
v[i]=v[i-1]+v[i-2]; //calculating fibnoacci
printf( \"The Fibonacci number series for %d numbers : \",n);//print output
int j; //loop variable
for(j=0;j<n;j++)
printf(\"%d,\",v[j]); //printing fibnoacci series
}
}
int main() //main function
{ const int N =100; //constant N variable
int numbers[N]; //difining integer array of size N
fib(numbers,N); //calling fib method passing array :numbers and N
return 0;
}
/*******OUTPUT*******
The Fibonacci number series for 10 numbers : 0,1,1,2,3,5,8,13,21,34,
******OUTPUT********/
/* Code has been tested on gcc compiler,all the variables and method name has been given according to the question,please do ask in case of any doubt,Thanks. */
