Link to home
Start Free TrialLog in
Avatar of spngegirl01
spngegirl01

asked on

How Do I Get This Fibonacci Program to Accept User Input?

I am trying to develop a program that takes in a user input of a number and returns as an output that number in the fibonacci series.  For example, if the user types in 5, the 5th number is displayed; 23 and the 23rd number is displayed.  So far I have this, but it only spits out the fibonacci series for 100 numbers and does not stop at the number put in by the user.  Please help!

#include <stdio.h>

char line[1000];

int main()
{

  int fib[1000];
  int i;

  printf("Fibonacci\n");
  fgets(line, sizeof(line), stdin);
  sscanf(line," %d", &i);

  if (i<0) return 0;

  fib[0] = 0;
  fib[1] = 1;

  for (i = 2; i<1000; i++)
{
    fib[i] = fib[i-1] + fib[i-2];
    }

  for (i = 0; i<1000; i++)
    {
      printf("%d %d\n", i, fib[i]);
    }

  return (0);

}

Avatar of spngegirl01
spngegirl01

ASKER

Hi thank you that fixed the problem of having the output end after the term, however, the series now starts at 0 in the output, so when I enter Fibonacci 3, I really only see the series up to the second term (assuming the first term is 1).  I added this below, but it won't work.  Any ideas?


fib[0] ='\0';
  fib[1] = 1;
  fib[2] = 1;

ASKER CERTIFIED SOLUTION
Avatar of sunnycoder
sunnycoder
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry sunnycoder,

I was not aware that it was homework problem