cgcc

c program returning different answers


I just started C and wanted to try out a euler problem.

For Euler #2

#include <stdio.h>
int main(){
  int sum;
  int prev = 0;
  int curr = 1;
  int next;

  do{
   if(curr % 2 == 0 ){
     sum = sum + curr;
   }
   next = curr + prev;
   prev = curr;
   curr = next;

  } while (curr <= 4000000);
  printf("%d\n", sum);
  return 0;
}

When I compile this program and run it, I get a completely different number. I don't care right now that I'm not getting the right answer as much as the numbers I am getting are varying by 1,000,000 at times.

The only 2 things I can think of is that running linux in a vm is making it crazy or somehow gcc is messing up.

Is g++ euler2.c -o euler2 correct for compiling c? Yes euler2.c is the name of my file.

SOLVED: Thanks for the replies. Definitely a lot of useful, and extremely quick information. And yes I should have added the possibility that "I might have messed up" =)


Solution

  • int sum = 0;
    

    If it is not initialized (in c) it contains random-garbage value. hence the random output

    and

    gcc -o euler2 euler2.c
    

    g++ is for c++, but this does not have anything to do with your problem.

    You might find this interesting : http://gcc.gnu.org/onlinedocs/gcc/Invoking-G_002b_002b.html