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();
}

Edited 3 Years Ago by Reverend Jim: Fixed formatting

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);

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().

Comments
It's not a recommendation, it's the law!

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.

This question has already been answered. Start a new discussion instead.