Exercise: Input via Command Line

Question

We saw in this section how to use command-line arguments in a C program. Modify the main function given below so that the nth Fibonacci number is printed when the argument n is passed through the command-line.

Your program should be able to run like this from the terminal:

./main 10
fib(10) = 55
./main 12
fib(12) = 144

Exercise: Input via Command Line

Question

We saw in this section how to use command-line arguments in a C program. Modify the main function given below so that the nth Fibonacci number is printed when the argument n is passed through the command-line.

Your program should be able to run like this from the terminal:

./main 10
fib(10) = 55
./main 12
fib(12) = 144
#include <stdio.h>

int fib(int n);


int main(int argc, char *argv[])
{
  // Give your code here
}

int fib(int n)
{
  int i;
  if ((n == 0) || (n == 1)) return n;
  int a = 0;
  int b = 1;
  int tmp;
  for (i = 2; i <= n; i++) {
    tmp = b;
    b = a + b; // Now b contains the i^th Fibonacci number
    a = tmp;
  }
  return b;
}
Try it yourself