Fibonacci

This is a discussion on Fibonacci within the C Programming forums, part of the General Programming Boards category; Hey guys, I'm fairly new to coding, in fact, this is the second program I've ever tried haha. I can't ...

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    1

    Fibonacci

    Hey guys, I'm fairly new to coding, in fact, this is the second program I've ever tried haha. I can't quite work out why my loop is terminating early in this program:

    Code:
    #include <stdio.h>
    
    int main () {
        int fibonacci, fib3, fib2, fib1;
    	printf("What number would you like the series to go to?");
    	
    	scanf("%d", &fibonacci);
    	printf("%d\n", fibonacci);
    	fib2=1;
    	fib1=0;
    	
    	if (fibonacci = 0) {
    		printf("The series is 0");
    		return 0;
    	}
    	do {
    			fib3 = fib2 + fib1;
    			printf("%d+\n",fib3);
    			fib1=fib2;	
    			fib2=fib3;	
    	}
    	while (fib3 <= fibonacci);
    		
    	
    	
    return 0;
    }
    All I get as an output, when say putting in 9 as the input, is this:

    What number would you like the series to go to?9
    9
    1+
    Obviously it's going through the loop once, before deciding it's ready to terminate without going through again. I can't work out why it wants to terminate without looping through twice. Any help you could offer would be great, thanks!

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    What does this bit of code do?
    Code:
    fib1=0;
    That's right, it sets the value of fib1 to be zero. Now what about this bit:
    Code:
    fibonacci = 0

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,480
    Code:
    if (fibonacci = 0)
    Add a second = in there. With a single equals, you actually assign 0 to fibonacci, and the result is the value of fibonacci, which is 0. This causes your if statement to skip the special zero case.

    You should have caught that if you had all the warnings turned up on your compiler, which is a very, very good idea to do, especially if you're new.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Fibonacci
    By saria777 in forum C Programming
    Replies: 25
    Last Post: 06-16-2010, 07:26 AM
  2. fibonacci prime
    By dbzx in forum C Programming
    Replies: 5
    Last Post: 04-17-2009, 11:13 AM
  3. fibonacci using recursion?
    By n3cr0_l0rd in forum C Programming
    Replies: 12
    Last Post: 02-25-2009, 07:49 AM
  4. Recursive Fibonacci, some help needed
    By cwafavre in forum C Programming
    Replies: 8
    Last Post: 11-04-2007, 01:20 PM
  5. void fibonacci() - Is This Possible?
    By Not Yet in forum C++ Programming
    Replies: 3
    Last Post: 11-25-2002, 09:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21