Variable In While Loop
I'm writing a program to sum up the even numbers in between 1 and 100, using a while loop. At the beginning of my program, I initialize a variable "sum" to 0, and a variable "temp" to 1. Afterwards I enter a loop where I determine if "temp" is even or not, and if so add it to sum. However, at the end of my program, when I print "sum", I get a result of 0. Below is my code.
int sum = 0, temp = 1;
while(temp <= 100)
if(temp % 2 == 0)
sum += temp;
temp = temp + 1;
printf("Sum is %i", sum);
I compiled and ran your program to get the output:
It might help to write a blank line at the end, e.g.,
printf("Sum is %i\n", sum);
Nevermind, it works. I just ran the program and got the right output.
How can I get rid of the extra blank lines when I post my code within tags?
You sure you're actually compiling that code? It should give a value of 2550. It does so on my system.
Try deleting the executable, object files, and rebuild from scratch. In an IDE, do a "Build Clean", then "Build All" (noting those processes may have slightly different names, depending on IDE).
Note that some IDE's will output an additional line reporting that the program exits with return value zero. With those IDE's you need to scroll up one line. It would help if the printf() statement appended a '\n' at the end (i.e. printf("Sum is %i\n", sum)) to avoid output being overwritten.