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

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?

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);
}
}

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).

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);

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;
}

Related

How to first examine the input before proceed the program? or shouldn't I? why?

So today I am learning the "while" loop in c#,
the task was simple:
you can keep input score between 0~100;
when you in put "-1", the program ends;
it'll output the sum and the average.
here is our teacher's answer:
#include <stdio.h>
int main(void) {
int score = 0;
int sum = 0;
int count = 0;
while(score != -1) {
printf("輸入分數(-1結束):");
scanf("%d", &score);
count++;
sum =sum + score;
}
printf("加總:%d 平均:%f\n",sum+1, (double) sum / count );
return 0;
}
here is my code:
#include <stdio.h>
int main(void)
{
int score = 0;
int sum = 0;
int count = -1;
while ( score > 0 || score <=100)
{
printf("輸入一個介於0~100的整數(-1結束):");
scanf("%d", &score);
count++;
sum = sum + score;
if ( score == -1)
{
break;
}
}
printf("加總: %d 平均: %f", sum+1, (double)sum / count);
return 0;
}
I know I'm just learning from the beginning,
my teacher said that let's not think too much about the user could input score over 100 or less than -1,
But I just can't help to think about we should first examine whether the input score is within 0~100, if it is then proceed the program,
and then the program will keep asking the user to input more, until the user input -1 and print the result of sum and the average.
so that's why I choose to wrote
while ( x >= 0 || x <= 100)
I can't figure out what is missing in the thought process.
Am I thinking the right direction?
How can I better fix the code?
I think you were on the right path, but you did miss something
#include <stdio.h>
int main(void)
{
int score = 0;
int sum = 0;
int count = -1;
while ( 1 )
{
printf("輸入一個介於0~100的整數(-1結束):");
scanf("%d", &score);
if ( score == -1 || score > 100 )
{
break;
}
count++;
sum = sum + score;
}
printf("加總: %d 平均: %f", sum+1, (double)sum / count);
return 0;
}
The important thing is to immediately exit the loop, without using the value of score, if it is not a valid score. Note that the while loop just runs indefinitely. It is only the break that stops looping. Also, note the logic in the if statement: we want to exit if the value is too low OR too high. This is the opposite of the way you'd written the code, because you wanted the loop to continue as long as the value was less than 100 AND more than -1.
You need to update your while loop condition.
while (score > 0 && score <= 100)
This is C code not C#
you can try this:
int main()
{
int score;
do {
printf("Enter a number between 0 and 100: ");
scanf("%d", & score);
} while (score > 0 && score <=100);
return 0;
}

multiply numbers untill the user enters 0

I don't know why but the loop doesn't stop even when I enter 0. can someone help me with this?
int main(void)
{
float number,product = 1;
printf("Provide floats separated by a line: \n");
scanf("%f" , &number);
while(number != 0)
{
product *= number;
if(number == 0)
break;
}
printf("The product of your values is: %.2f" , product);
printf("\n");
}
You'll need to place the scanf call inside the loop to repeatedly ask the user for input. As it is you only ask once, and then loop forever on the same value.
Here we place the call in the predicate itself:
#include <stdio.h>
int main(void) {
float number = 0,
product = 1;
puts("Provide floats separated by a line:");
while (scanf("%f" , &number) == 1 && number)
product *= number;
printf("The product of your values is: %.2f\n" , product);
}
You should always check the return values of your I/O functions. scanf returns the number of conversions that took place, which here should be 1. On error, EOF, or number being 0 we do not continue the loop.

Why are my values for sum and count being lost each loop?

I'm getting a consistent divide by zero error, even though each loop should be populating the variables. Code below:
#include <stdio.h>
void calculateAverage()
{
int grade, count, sum;
double average;
sum = 0;
count = 0;
grade = 0;
average = 0.0;
int coolvalue = 0;
while (coolvalue==0)
{
scanf("%d", &grade);
if (grade == -1)
{
sum, sizeof(double);
count, sizeof(double);
average = (sum / count);
printf("%lf", &average);
break;
}
else
{
if ((grade > 100) || (grade < -1))
{
printf("Error, incorrect input.\n");
break;
}
else
{
sum = +grade;
count = count + 1;
return count;
return sum;
}
}
}
coolvalue = 1;
}
int main(void)
{
while (1)
calculateAverage();
while (1) getchar();
return 0;
}
Even while using return, I'm not able to properly increment the value of sum or count.
There are multiple issues in your code.
scanf("%d", &grade); - you don't check the value returned by scanf(). It returns the number of values successfully read. If you enter a string of letters instead of a number, scanf("%d") returns 0 and it does not change the value of grade. Because of this the code will execute the rest of the loop using the previous value of grade. You should restart the loop if the value returned by scanf() is not 1:
if (scanf("%d", &grade) != 1) {
continue;
}
Assuming you enter 10 for grade this block of code executes:
sum = +grade;
count = count + 1;
return count;
return sum;
sum = +grade is the same as sum = grade. The + sign in front of grade doesn't have any effect. It is just the same as 0 + grade.
You want to add the value of grade to sum and it should be sum += grade. This is a shortcut of sum = sum + grade.
return count makes the function complete and return the value of count (which is 1 at this point) to the caller. The caller is the function main() but it doesn't use the return value in any way. Even more, your function is declared as returning void (i.e. nothing) and this renders return count incorrect (and the compiler should warn you about this).
return sum is never executed (the compiler should warn you about it being dead code) because the function completes and the execution is passed back to the caller because of the return count statement above it.
Remove both return statements. They must not stay here.
If you enter -1 for grade, this block of code is executed:
sum, sizeof(double);
count, sizeof(double);
average = (sum / count);
printf("%lf", &average);
break;
sum, sizeof(double) is an expression that does not have any effect; it takes the value of sum then discards it then takes the value of sizeof(double) (which is a constant) and discards it too. The compiler does not even generate code for it.
the same as above for count, sizeof(double);
average = (sum / count);:
the parenthesis are useless;
because both sum and count are integers, sum / count is also an integer (the integral result of sum / count, the remainder is ignored).
you declared average as double; to get a double result you have to cast one of the values to double on the division: average = (double)sum / count;
if you enter -1 as the first value when the program starts, count is 0 when this code is executed and the division fails (division by zero).
printf("%lf", &average); - you want to print the value of average but you print its address in memory. Remove the & operator; it is required by scanf() (to know where to put the read values). It is not required by printf(); the compiler generates code that passes to printf() the values to print.
break; - it passes the execution control after the innermost switch or loop statement (do, while or for). It is correct here and makes the variable coolvalue useless. You can simply remove coolvalue and use while (1) instead.
All in all, your function should look like:
void calculateAverage()
{
int sum = 0;
int count = 0;
int grade = 0;
double average = 0.0;
while (1) {
if (scanf("%d", &grade) != 1) {
// Invalid value (not a number); ignore it
continue;
}
// A value of -1 signals the end of the input
if (grade == -1) {
if (count > 0) {
// Show the average
average = (double)sum / count;
printf("Average: %lf\n", average);
} else {
// Cannot compute the average
puts("You didn't enter any value. Cannot compute the average.\n");
}
// End function
return;
}
if ((grade < -1) || (100 < grade)) {
puts("Error, incorrect input.\n");
// Invalid input, ignore it
continue;
}
sum += grade;
count ++;
}
}
Quite a few corrections need to be made.
The while loop in the calculateAverage() function. That's an infinite loop buddy, because you are not changing the value of that coolValue variable anywhere inside, instead you make it 1 only when it exits the loops, which it never will.
So, use while(1) {...}, and inside it, check for the stopping condition, i.e, if (grade == -1) { ... } and inside it calculate and print the average and return. This will automatically break the while.
You're not checking if the input grade is actually a valid integer or not. Check the value of scanf for that, i.e, use if (scanf("%d", &grade) != 1) { ... }
The expression sum = +grade; is just another way of writing sum = 0+grade which in turn is nothing but sum = grade. Replace this with sum += grade;. This is the right way to write a shorthand for addition.
Two return statements..a very wrong idea. First of all, a function can have just one return(in an obvious way I mean, at once). Secondly, the function calculateAverage() is of return-type void. there's no way how you can return double value from it. So remove these two statements.
I have attached the code below which works. Also do go through the output which I have attached.
CODE:
#include <stdio.h>
void calculateAverage()
{
int grade, count = 0, sum = 0;
double average;
printf("\nenter the grades... enter -1 to terminate the entries\n.");
while (1) {
printf("\nEnter the grade: ");
if (scanf("%d", &grade) != 1) {
printf("\nInvalid characters entered!!!");
continue;
}
else if(((grade > 100) || (grade < -1))) {
printf("\nInvalid grade entered!!!");
continue;
}
else {
if (grade == -1) {
average = sum/count;
printf("\nAverage value of grades: %.3lf",average);
return;
}
else {
sum += grade;
count++;
}
}
}
}
int main(void)
{
calculateAverage();
return 0;
}
OUTPUT:
enter the grades... enter -1 to terminate the entries.
Enter the grade: 50
Enter the grade: 100
Enter the grade: 60
Enter the grade: -1
Average value of grades: 70.000
Perhaps it is better for the function to be of type double instead of void. Although it is not my favorite solution it is close to what you want.
#include <stdio.h>
double calculateAverage(void)
{
double average;
int sum = 0, count=0, grade;
while (1)
{
scanf("%d", &grade);
if ((grade > 100) || (grade < -1))
printf("Error, incorrect input.\n");
else if (grade != -1)
{sum = sum+ grade; count = count + 1;}
else
break;
}
if (count==0)
average=-1.0; //none valid input. Notify the main()
else
average=(double)sum/count;
return average;
}
int main(void)
{
double result;
result= calculateAverage();
if (result!=-1.0)
printf("\n average= %lf",result);
else
printf("No grades to calculate average");
getchar();
return 0;
}

Receiving non-zero exit status when filling an array dynamically from user input

#include <stdio.h>
int main(void){
int inputNumber;
int counter=0;
int totalValue;
int arr[counter];
int avg;
puts("Please enter any number of positive whole numbers you would like to be averaged. Enter ' -1 ' when you are finished for your result.\n");
while(scanf("%d\n", &arr[counter])){
if(arr[counter] = -1){
break;
}
if(arr[counter] > 0){
totalValue += arr[counter];
++counter;
}
else if(arr[counter]<=0){
puts("Please enter a positive number.");
}
else{
}
}
avg = totalValue/counter;
printf("The average of your entered values is: %d", avg);
return 0;
}
I have attempted many things to try and stop it, and although this may come from a lack of knowledge is there really any way to do this other than creating an enormously large array?
I tried using a dynamic array with calloc() but i was met with the same errors. I am unsure what else is available as an option in this method.
The code is supposed to take the average of "n" user inputted values.
You do not need an array.
Quick & dirty but easier that you wanted to do
int number = 0;
int counter = 0;
int total = 0;
while (number != -1)
{
total += number;
++counter;
scanf("%d", &number);
}
printf("average = %d\n", total / (counter - 1) );

Not sure why my program keeps prompting error when I try to close it?

#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main() {
int num, result_odd, result_even, even_count, odd_count;
char name;
printf("What is your name?\n");
scanf("%s", &name);
while (num != 0) {
printf("Enter a number:\n");
scanf("%d", &num);
if (num % 2 == 1) {
printf ("odd\n");
odd_count++;
} else
if (num == 0) {
printf("%s, the numbers you have entered are broken down as follows:\n",
name);
result_even = add_even(num);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(num);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
} else {
printf("even\n");
even_count++;
}
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 != 0) {
return 0;
}
sum += add_even(num);
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 == 0) {
return 0;
}
sum += add_odd(num);
return sum;
}
Can anyone give me some insight as to what I did wrong exactly?
The point of the code is to get inputs from the user until they decide to stop by inputting 0. Separating the evens from the odd. Tell them how many even/odd they put and the total of all the even/odd numbers.
I understand how to separate the evens from the odds. I think my issue is with my function.
There are multiple problems in your code:
scanf() causes undefined behavior when trying to store a string into a single character. Pass an array and specify a maximum length.
you should check the return value of scanf(): if scanf() fails to convert the input according to the specification, the values are unmodified, thus uninitialized, and undefined behavior ensues. In your case, if 2 or more words are typed at the prompt for the name, scanf("%d",...) fails because non numeric input is pending, no further characters are read from stdin and num is not set.
num is uninitialized in the first while (num != 0), causing undefined behavior.
functions add_even() and add_odd() are only called for num == 0, never summing anything.
functions add_even() and add_odd() should always return the sum and add the value of the argument num is it has the correct parity. They currently cause undefined behavior by calling themselves recursively indefinitely.
odd_count and even_count are uninitialized, so the counts would be indeterminate and reading their invokes undefined behavior.
In spite of all the sources of undefined behavior mentioned above, the reason your program keeps prompting without expecting an answer if probably that you type more than one word for the name. Only a single word is converted for %s, leaving the rest as input for numbers, which repeatedly fails in the loop. These failures go unnoticed as you do not verify the return value of scanf().
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main(void) {
int num, result_odd, result_even, even_count = 0, odd_count = 0;
char name[100];
printf("What is your name? ");
if (scanf("%99[^\n]", name) != 1)
return 1;
for (;;) {
printf("Enter a number: ");
if (scanf("%d", &num) != 1 || num == 0)
break;
if (num % 2 == 1) {
printf("odd\n");
odd_count++;
add_odd(num);
} else {
printf("even\n");
even_count++;
add_even(num);
}
printf("%s, the numbers you have entered are broken down as follows:\n", name);
result_even = add_even(0);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(0);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 == 0) {
sum += num;
}
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 != 0) {
sum += num;
}
return sum;
}
You declared:
char name; // One single letter, such as 'A', or 'M'
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", &name); // Not enough space to store the response!
What you really want is more like
char name[31]; // Up to 30 letters, and an End-of-String marker
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", name); // name is the location to put all those letters
// (but not more than 30!)

Resources