I can't for the life of me figure out why C is ignoring my if statement.
I'm trying to skip all the procedures in the while statement when the input is -1000 (so that it doesn't print before exiting the program). Here is my code:
int main()
{
int count = 1;
int grade1;
int grade2;
double sum;
double average;
printf("Please input a number of grades: \n");
scanf("%d", &grade1);
printf("Sum is: %d.000000 \n", grade1);
printf("Average is: %d.000000 \n", grade1);
count++;
sum = grade1;
while(grade2 != -1000)
{
if(grade2 != -1000)
{
scanf("%d", &grade2);
sum = sum + grade2;
average = sum / count;
printf("Sum is: %lf \n", sum);
printf("Average is: %lf \n", average);
grade1 = sum; //Converting the sum back into an int
count++;
}
}
return 0;
}
Here is a link to an image of my output. As you can see, even when grade2 is given -1000, the if statement is ignored, and another 2 lines are printed to the screen before the program exits. How can I fix this? Is this some sort of oddity of how C works?
When you do this the first time
while(grade2 != -1000)
the variable grade2 is uninitialized.
Consequently your code has undefined behavior
Make sure to initialize it like:
int grade2 = 0; // To zero or whatever you want
Further - always check the value returned by scanf. So instead of
scanf("%d", &grade1);
do
if (scanf("%d", &grade1) != 1)
{
// Add error handling here
}
Your next problem is that you don't scan grade2 before checking whether it is -1000. Move the scan before the if-statement.
Maybe what you want to do is:
int grade2 = 0;
while(grade2 != -1000)
{
if (scanf("%d", &grade2) != 1)
{
// Add error handling here
}
if(grade2 != -1000)
{
...
so that you scan for the first grade2 before you do the if(grade2 != -1000) and enters the calculation code
Written differently this could be:
while(1)
{
if (scanf("%d", &grade2) != 1)
{
// Add error handling here
}
if(grade2 == -1000) break; // Terminate the while
sum = sum + grade2;
....
While it's true that grade2 should be initialized and the return for scanf() should be checked, that's not the main problem the poster is running into. The problem is that he checks
if(grade2 != -1000)
AFTER he has already processed grade2. He should move
scanf("%d", &grade1);
before
if(grade2 != -1000)
The if statement in your while loop is redundant because, the loop will not iterate unless the condition that controls it is true, and the if statement comes directly after that, checking for the same condition, whilst grade2 is unchaged.
Instead, you need to move it to after the scanf() call because that will modify the variable grade2, and don't forget to initialize your variables before using them or else you'll have undefined behavior.
int main(void)
{
//....
int grade2 = 0; // initialized...
//....
while (grade2 != -1000)
{
scanf("%d", &grade2);
if (grade2 != -1000)
{
sum = sum + grade2;
average = sum / count;
printf("Sum is: %lf \n", sum);
printf("Average is: %lf \n", average);
grade1 = sum; //Converting the sum back into an int
count++;
}
}
}
Related
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;
}
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;
}
#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!)
So my program asks for name and numbers, then tallies up the number of even entries and odd entries, then giving a total of all the even entries and a total for all the odd.
It all works except the calculations, it tells me I have all odd entries and only values them as 1 when adding them up.
I feel like it has something to do with my variables and referencing in my calc function
#include <stdio.h>
int number = 1;
int evencount, oddcount;
int eventotal, oddtotal;
int main () {
char name[256];
printf("Enter your name \n");
scanf("%s", name);
printf("Enter numbers within 1-100 \n");
printf("Enter 0 to quit\n");
calc(number);
printf("%s,the numbers you have entered are broken down as follows: \n", name);
printf("%d odd entries \n", oddcount);
printf("%d even entries\n", evencount);
printf("You entered even numbers with a total value of %d \n", eventotal );
printf("You entered odd numbers with a total value of %d \n", oddtotal);
return 0;
}
int calc (int input) {
while (number != 0) {
scanf("%d", &number);
if (input%2 == 1) {
oddcount++;
oddtotal += input;
}
else {
evencount++;
eventotal += input;
}
};
}
scanf("%d", &number);
if (input%2 == 1) {
{
oddcount++;
oddtotal += input;
}
I think you probably want number % 2 rather than input % 2,
oddtotal += number rather than oddtotal += input, etc.
In your calc function, you're mixing up input, which is a parameter, and number, which is a global.
Using a global here for your input variable is bad form, and in fact you don't need to pass anything into this function.
Also, better to use do..while instead of while since the loop must run at least once:
You're also using the function before it's declared, so you should have a function prototype. And since calc doesn't need to return anything, set its return type to void.
#include <stdio.h>
int evencount, oddcount;
int eventotal, oddtotal;
void calc();
int main()
{
...
calc();
...
}
void calc()
{
int number;
do {
scanf("%d", &number);
if (number%2 == 1) {
oddcount++;
oddtotal += number;
} else {
evencount++;
eventotal += number;
}
} while (number != 0);
}
I have a problem, I tried to write a program to show the whole sum from 1 to 22 and after that, to do 2 while loops. The first one is supposed to perform the sum of some numbers given by the user, as an example: you type 10, 30 and 40 then as you enter a 0 the program sums the first three numbers. Unfortunetly the first while loop is not working. It goes directly to the last while loop where it is supposed to type a decimal numbers like (10.20 30.50 40.55) and after you type 0 again it sum those numbers and add and multipli every entry with 1.19. So far the last loop is working properly, unfortunately the second loop does not, if I move printf and scanf over the while it let me write but just start writing w/o stopping the number I wrote . Thank You in advance!
Here is the code :
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b;
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
return 0;
}
You don't initialise i to any value before entering the loop with
while(i != 0)
i might very well be zero at this point, so your loop won't be entered even once. Initialising i to a non-zero value should fix this particular problem. The same holds for the variable b.
You should turn on warnings in your compiler, so it can show you problems like this one.
The first time the condition of the second while is evaluated, b has undefined value, since it wasn't initialized. The same applies to the third while.
Whether or not both loops are executed is only a question of chance.
Initialize both variables with non-zero values to ensure both whiles are entering. Or use a do-while:
do {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
} while (b != 0);
Don't test b with while, test it after the user enters the number. Then you can use break to exit the loop.
while (1) {
printf("type a number:");
scanf("%i", &b);
if (b == 0) {
break;
}
sum += b;
printf("%i\n", b);
}
while(1) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
if (i == 0.0) {
break;
}
sum1 += i*1.19;
printf("%lf\n", i);
}
Your only issues are initialization: see edits in the code below. (it compiles and runs)
Did you get any compiler warnings for these? If not, you should change your settings so you do.
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b=-1; //initialize (any non-zero value will work)
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {//a initialized in for(...) statement, (this is good)
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) { //b Needs to be initialized before using (done above)
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
i=-1; //initialize i to any non-zero value
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
getchar();
return 0;
}