Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fibonacci series gone wrong?

Tags:

c

we have been asked to write a program to generate fibonacci series as our homework. so i wrote a program that generates the first n fibonacci numbers .here is my frist code that dosent work properly

# include <stdio.h>
void main()
{
    int a = -1, b = 1, c = 0, i, n, sum = 0 ;
    printf("Enter the limit : ") ;
    scanf("%d", &n) ;
    printf("\nThefibonacci series is : \n\n") ;

    for(i = 1 ; i <= n ; i++)
    {
        c = a + b ;
        printf("%d \t", c) ;
        b=c;
        a=b;
    }
}

so i tried various combinations and i found out that my code would work well if i interchanged the 12th and 13th lines. i.e

# include <stdio.h>
void main()
{
    int a = -1, b = 1, c = 0, i, n, sum = 0 ;
    printf("Enter the limit : ") ;
    scanf("%d", &n) ;
    printf("\nThefibonacci series is : \n\n") ;
    for(i = 1 ; i <= n ; i++)
    {
        c = a + b ;
        printf("%d \t", c) ;
        a=b;
        b=c;
    }
}

It is the same logic right. why does the first code give me wrong output?

what are segmentation faults?(my compiler frequently tells me that there are segmentation faults in my code)

P.S-i am a begginer.Just three weeks into c language and we are learning about loops.

like image 737
Sameer Avatar asked Jan 16 '23 02:01

Sameer


2 Answers

The ordering of statements matters.

b = c;
a = b;

When this runs, b and a will both be equal to the original value of c, and the old value of b has been lost. This is probably not what you wanted.

a = b;
b = c;

When this runs, a will equal the old value of b, and b will equal the original value of c.

like image 147
Simon Nickerson Avatar answered Jan 24 '23 15:01

Simon Nickerson


In Fibonacci series, a new number is generated as sum of previous two numbers.

Lets say previous two numbers were A and B and the newly generated number is C. Now for the next iteration you need to forget A and B & C are your new previous numbers.

To make B and C you new A and B you need to do:

A = B   // B becomes the new A
B = C   // C becomes the new B

what you are doing is:

B = C   // C becomes the new B, but you've not saved the old value of B!!!
A = B   // Old value of B gone..B is now C, which is assigned to A
like image 42
codaddict Avatar answered Jan 24 '23 16:01

codaddict