Search⌘ K
AI Features

Solution: Input via Command Line

Understand how to manage command-line input in C programs by examining argument count and converting strings to integers. Learn to implement input validation and error messages while computing Fibonacci numbers, enhancing your skills in handling user input effectively.

We'll cover the following...
#include <stdio.h>

int fib(int n);

int main(int argc, char *argv[])
{
  if (argc < 2) {
    printf("Error: please pass a number\n");
    return 1;
  }
  else {
    int n = atoi(argv[1]);
    if (n < 0) {
      printf("Error: n must be at least 0\n");
      return 1;
    }
    else {
      printf("fib(%d) = %d\n", n, fib(n));
      return 0;
    }
  }
}

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;
}
Solution: Input via command line
...