Skip to content

Wondering about while loop

An answer to this question on Stack Overflow.

Question

I started learning C 3 weeks ago, and while learning while loops I tried to build an addition program, basically you keep adding numbers it additions them and after 2nd number it gives you a subtotal for every addition, and if you press 0 to quit It gives you a final sum then quits. Now I have one main, one additional question. The main question is, I had to use sum = 0 before the while functions, if I use it after "the while" it gives me the number I entered as the result. Now I really wonder what is the idea behind it. When I write it like below does it equates "sum with 0" for the start and changes the value as I enter another number, or there is some other idea behind it.

And the additional question is , why do I need to use 2 getchar(); to make my program stay on the screen, why not one?

#include <stdio.h>
int main(void)
{
	float num;
	float sum;
    printf(" please enter a number +0 to start the program (0 to quit): \n");
    scanf(" %f", &num);
    sum =0; //THIS HERE**********************
    while (num  > 0)
	{	
		printf("please enter integer:\n");
		scanf("%f", &num);
		sum = sum + num;
		printf("current sum is = %f\n", sum);
	}
	printf("final sum is = %f\n", sum);
	getchar();
    getchar();
    return 0;
}

Answer

If you put sum=0 inside the while loop it will be called each time the while loop loops.

This means when you reach sum=sum+num, you will actually be calculating sum=0+num.

You have two use two getchar() calls because the first one is sucking up an additional character that was not absorbed by your scanf. Probably this character is a newline, so you cannot see it. The second getchar() then keeps your terminal open because it is waiting for a character.

To figure out if my hypothesis is correct about the first getchar() you could try this:

char temp = getchar();
printf("%d",(int)temp); //Print out the character number from the first getchar
getchar(); //This keeps the window open