John Smith John Smith - 2 months ago 7
C Question

Looping the Sum of numbers (Inputs) in C

Give the c code for a loop that computes and displays a sum of numbers that the user enters. The loop should prompt the user for input until the user enters -335 and then exit and display the final sum.

This is what I have. Why does it not print (exit the loop) when I enter -335? It just keeps asking me to input a number.

#include <stdio.h>


int main(void)
{

int userNum;
printf("Please enter an integer:\n");
scanf("%d", &userNum);

while (userNum != -335){
printf("Please enter an integer:\n");
scanf("%d", &userNum);
userNum += userNum;

}

printf("%d", userNum);


return 0;
}

Answer

You need an additional variable to keep track of the sum instead. Your current method keeps overwriting it:

So add a line:

int userNum;
int sum = 0; // sum holds total variable

and you add and change here:

while (userNum != 335){
    printf("Please enter an integer:\n");
    scanf("%d", &userNum);
    sum += userNum;
}

 printf("%d", sum);