0
#include <stdio.h>

int fibonacci(int n) {
    int count, n1 = 0, n2 = 1, fib = 0;
    printf("Given number: ");
    scanf("%d", &n);
    count = 0;
    while (count < n) {
        fib = n1 + n2;
        n1 = n2;
        n2 = fib;
        ++count;
        if (n > fib)
            printf("%d ", fib);
    }
    return 0;
}

int main() {
    int szam;
    fibonacci(szam);
    return 0;
}

I've gotten this far, I just don't know how to count the numbers. for example:
input: 10
output: 1 2 3 5 8

but it should be:
in: 10
out: 5

chqrlie
  • 131,814
  • 10
  • 121
  • 189

2 Answers2

0

The stop condition in your code is incorrect: you stop after n fibonacci numbers have been computed instead of stopping when you have computed a fibonacci number larger than n.

Here is a corrected version:

#include <stdio.h>
int count_fibonacci(unsigned long long int n) {
    int count = 0;
    unsigned long long n1 = 1, n2 = 1, fib = 1;
    while (fib < n) {
        count++;
        fib = n1 + n2;
        n1 = n2;
        n2 = fib;
    }
    return count;
}

int main(void) {
    unsigned long long n = 0;
    printf("Given number: ");
    scanf("%llu", &n);
    printf("%d\n", count_fibonacci(n));
    return 0;
}

It prints 5 for an input of 10, because your fibonacci sequence is: 1 2 3 5 8....

But the standard sequence is usually defined as 1 1 2 3 5 8..., and it should return 6. You can get this behavior bu changing the initial state to n1 = 0, n2 = 1, fib = 1.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

Added the variable fib_count that counts the Fibonacci numbers (did not test this...)

#include <stdio.h>

int fibonacci(int n)
{
  int n1=0, n2=1, fib=0, fib_count;
  printf("Given number: ");
  scanf("%d",&n);
  fib_count = 0;
  while (fib<n)
  {`

      fib=n1+n2;
      n1=n2;
      n2=fib;
      fib_count += 1;
      printf("%d ",fib);

  }
  printf("Fibonacci numbers smaller than %d : %d ",n, fib_count);
  return 0;
}

int main(){
int szam;
fibonacci(szam);
return 0;
}
ralf htp
  • 9,149
  • 4
  • 22
  • 34