I am trying generate even fibonacii numbers less than four million, but I keep getting negative numbers at some point and eventually it converges to a positive answer, which is obviously wrong. Can anyone please help me out?

#include <conio.h>
#include <stdio.h>
void main (void)
{
clrscr();
int f1=1;
int f2=1;
long temp=0;
long total=0;

while (temp<4000000))
{
temp=f1+f2;
f1=f2;
f2=temp;
    if (temp%2==0)
    {
    printf("\n %d",temp);
    }
}
getch();
}

Dani AI

Generated

Short answer: the weird negative outputs are almost certainly undefined behavior from a format/type mismatch and nonportable code, not a mysterious Fibonacci bug. As hinted, printing a value with the wrong printf specifier (and compiling on an old/odd toolchain where int might be 16-bit) will show garbage, including apparent negatives. Also avoid nonstandard helpers like conio.h/clrscr()/getch() and use int main().

Why this happens: printf uses the format string to decide how many bytes to read from the argument list. If the format doesn't match the actual type, printf will read the wrong bytes and produce nonsense. That is undefined behavior — it can look like overflow, sign flips, or anything. Modern, portable fixes are to use C++ iostreams (std::cout) or to use fixed-width integer types and the correct format macros from <inttypes.h>/<cinttypes>.

A compact, robust approach (no parity checks, no printf pitfalls) is to iterate only the even Fibonacci terms using the recurrence E(n) = 4*E(n-1) + E(n-2). That both simplifies the loop and avoids large intermediate counts:

#include <iostream>

int main() {
    unsigned long long e_prev = 2;   // 2 is the first even Fibonacci
    unsigned long long e_curr = 8;   // 8 is the second
    unsigned long long sum = 0;

    while (e_prev < 4000000ULL) {
        sum += e_prev;
        unsigned long long next = 4 * e_curr + e_prev; // E_next = 4*E_curr + E_prev
        e_prev = e_curr;
        e_curr = next;
    }

    std::cout << sum << '\n';
    return 0;
}

Quick checklist for debugging: compile with warnings enabled (e.g. -Wall -Wextra), prefer std::cout in C++ to avoid printf mismatches, pick integer types that fit the range you need (int32_t/uint64_t), and test small limits first. Thanks to and for the integer-range discussion — for this problem a 32‑bit signed int can hold values up to ~2.1e9, but unsigned long long is a safer, portable choice.

Recommended Answers

All 6 Replies

Major mistakes:

1>Using conio.h its an extinct header man.
2>Using clrscr() its also an extinct call.
3>Problem here is with :

printf("\n %d",temp);

You are printing the long int temp as a signed integer so after it crosses the limit of 32767 it goes on to the negative side.So use use it as:

printf("\n %ld",temp);

Thanks CsurFer!!

u r talking about four million,thats completly out of range for an int declaration...........whether u take long int it will not work,becouse
long int don't have that much range in 32 bit processor..........
but it might work in 64 bit
u may try

I don't expect febonacci numbers to be negative, so why not use unsigned, it will give you twice the amount you can go.
And %d calls an integer, not a long (so it will only show what an integer would show if it was at that value)
I would also recomend using int main() instead of void main().

commented: It's not a recommendation, it's the law! +36

u r talking about four million,thats completly out of range for an int declaration...........whether u take long int it will not work,becouse
long int don't have that much range in 32 bit processor..........
but it might work in 64 bit
u may try

the max of a 32 bit unsigned int is 4294967296 or 2147483648 for signed which is more than he needs. the formatting issue is the only problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.