Jump to content

C not reading an if statement inside a while loop

Go to solution Solved by 79wjd,

Initialize fib3=0

I'm trying to answer this question: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

 

I made this program to solve the problem: 

#include <stdio.h>int main (void){        int fib1, fib2, fib3;        fib1 = 1;        fib2 = 2;        int sum = 0;        while (fib3 < 4000000)        {                fib3 = fib1 +fib2;                fib1 = fib2;                fib2 = fib3;                if (fib3 % 2 == 0)                        sum += fib3;        }        printf("%i\n", sum);}

The problem is that it just prints 0 every time.   It doesn't even run through the if statement, and if i put a printf in the while loop it doesn't execute it.  What is my problem?

Link to comment
Share on other sites

Link to post
Share on other sites

Initialize fib3=0

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to comment
Share on other sites

Link to post
Share on other sites

Initialize fib3=0

I feel like an idiot, thanks.  I'm new to C, and I started off with Java.  Would this work in Java, or am I just a total idiot?

 

Edit: Never mind I see why it doesn't work.  It doesn't go through the while loop at all because fib3 doesn't equal anything, so it doesn't meet the condition, where as in Java it would be automatically initialized to 0.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×