Need a C program that takes a single command line argument which is an integer t
ID: 3541822 • Letter: N
Question
Need a C program that takes a single command line argument which is an integer telling the program the index of the Fibonacci number to print. If the number is negative or missing, print an error message. Otherwise, print the Fibonacci number.
Printing the Fibonacci number should be handled in a separate function. This function takes a single integer parameter which is the index of the Fibonacci number to be printed. It will then print that Fibonacci number.
Example output(s) (assume the executable is called Fibonacci):
./Fibonacci
Error: Expected one argument, the index of the Fibonacci number to print.
./Fibonacci -1
Error: The index must be >= 0.
./Fibonacci 8
Fibonacci Number [8] = 21
Explanation / Answer
#include<stdio.h>
#include <stdlib.h>
int fibonacci(int number)
{
int a=0,b=1,c=0,i;
for( i=0; i<number-1; i++)
{
c=a+b;
a=b;
b=c;
}
return c;
}
int main(int argc, char *argv[])
{
int a = 0;
int b = 1;
int c;
int i=0;
if(argc!=2)
{
printf("Error: Expected one argument, the index of the Fibonacci number to print.");
}
else
{
int number = atoi(argv[1]);
if(number<=0)
printf("Error: The index must be >= 0. ");
else
{
printf("Fibonacci Number [ %d ] = %d",number,fibonacci(number));
}
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.