Joerji Ong Joerji Ong - 2 months ago 6
C Question

Fibonacci Series in C Program where FIRST 2 numbers are given by user

When the first number is

1
and second number is
2
, and the length is
5
, it should be
1 2 3 5 8
. But then my output is always
1 2 1 3 4
. I can't seem to find the problem.

Another input is
2
and
5
. Output is
2 5 1 6 7
. The 3rd number which is 1 shouldn't be there. What should I change or add?

*This is already a submitted HW and yes its wrong I got the deductions already. Now I just want to fix this so I can study this.

int main()
{
int i, lenght = 0, fib, sum, sum1, sum2, a, b, c;
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);

{
while ((a > b) || ((lenght < 2) || (lenght > 100)))
{
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
}
}

printf("%d\t%d\t", a, b);
printf("%d\t", fib);
for (i = 3; i < lenght; i++) {
if (i <= 1) fib = i;
else {
a = b;
b = fib;
fib = a + b;
}

printf("%d\t", fib);
}
}

Answer

Since this is for study, issues with your code: you don't need to duplicate the calls to scanf(), simply initialize one of the variables to fail (which you did: lenght = 0) and let the loop do its thing; pick one indentation style and stick with it; if you're new to C, always include the curly braces, even when the language says they're optional; you (correctly) allow for a length of 2, but then print three numbers; your if (i <= 1) clause is a no-op as the loop starts with for (i = 3; so i is never less than 3.

Putting it all together, we get something like:

#include <stdio.h>

int main() {
    int length = 0, a, b;

    while (length < 2 || length > 100 || a > b ) {
        printf("\nFirst number: ");
        (void) scanf("%d", &a);
        printf("\nSecond number: ");
        (void) scanf("%d", &b);
        printf("\nHow long?: ");
        (void) scanf("%d", &length);
    }

    printf("%d\t%d\t", a, b);

    for (int i = 2; i < length; i++) {
        int fib = a + b;

        printf("%d\t", fib);

        a = b;
        b = fib;
    }

    printf("\n");

    return 0;
}

Note that the input error checking isn't sufficient to prevent problems. E.g. b can be greater than a, but still mess up the sequence if you input random numbers. You're assuming the user knows to put in two adjacent items from fibonacci sequence which is tricky to test.

Comments