-1

The following code should prompt the user for prices and add that to a total. If the user inputs -1 the adding loop must terminate and the program should print a total and exit. But for some reason this is not happening.

#include <stdio.h>
int main()
{
  int price;
  int sum;
  int exit;

  do
  {
    printf(" Enter a price(-1 to exit)");
    scanf("%d", & price);
    sum = sum + price++;

    printf("the sum of prices is % d ", sum);
  }
  while (exit != -1);

  return 0;
}

Q: Why does my program not add numbers until -1 is given?

Ente
  • 2,301
  • 1
  • 16
  • 34
sweet
  • 11
  • 3

4 Answers4

1

You aren't assigning exit to anything. If you want the user to enter the string -1, the check if price is -1 and break from the loop. If you meant for the user to enter a character with a value of -1, then use fgetc(stdin), and check if the character is -1.

Also, to calculate the sum correctly, you shouldn't be incrementing price with sum = sum + price++;. If this was meant to circumvent the situation where price is -1 and you don't want to subtract from the sum, you should check if exit is -1 inside the loop, and use the break keyword.

It isn't the largest issue, but you should be formatting your code according to conventions (e.g. indenting properly, address-of-operator next to the identifier, etc).

reeeee
  • 139
  • 10
1

You should use if-else statement to resolve it. Like shown below:

while(price != -1)
{
    printf(" \nEnter a price(-1 to exit)");
    scanf("%d", &price);
    if (price == -1)
    {
      break;
    }
    else{
        sum = sum + price;
        printf(" \ntotal sum till now is %d", sum);
    }
}
Himanshu Singh
  • 2,117
  • 1
  • 5
  • 15
0

Hello man look now in what is the problem u named a int exit right ? But you only make exit only int varible and the memory is unfiltered so the computer get a memory from something else and its not a -1 you need to put the %d price in the wile

int price;
do
{
 block_of_command
}
While(price!=-1);

Or

int exit;
int price
do
{
scanf("%d",&price);
exit=price;
}
while(exit!=-1);
World
  • 49
  • 7
0

i updated the code but i dont know how to add all the user inputted prices before exiting. here is my code.

#include<stdio.h>
int main()
{
int price;
int sum = 0;

while(price != -1)
{
    printf(" Enter a price(-1 to exit)");
    scanf("%d", & price);


    if (price == -1)
    {
      sum = sum + price;
      printf(" adds is %d", sum);
      break;
    }

   }



  return 0; 
  }
sweet
  • 11
  • 3
  • Use if-else to differentiate the two cases. 1) to add user input 2) to break loop and exit. Just for reference I have added coffee snippet in answer below. – Himanshu Singh Nov 13 '19 at 05:05