• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 264
  • Last Modified:

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;

  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);


1 Solution
spngegirl01Author Commented:
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;


Please disregard the code posted by shasunder and work on improving your own code which is good and can be easily improved.

>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

That happens because of this loop in which you are printing
  for (i = 0; i<1000; i++)
      printf("%d %d\n", i, fib[i]);
You are printing all values from 0 to 999 ... while you need to stop at the specific number. Edit your loop to iterate upto j times - that is the number of values you want printed - instead of 1000.

Next improvement that you can make is to calculate only j values instead of 1000 values. To do that - again make similar modifications to the loop in which you are calculating the values.

Shanmuga SundaramDirector of Software EngineeringCommented:
Sorry sunnycoder,

I was not aware that it was homework problem
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now