I'm having trouble ending a loop in C - c

I'm in school learning C. (I am not asking for anyone to write this for me).
Assignment
This program will calculate the miles per gallon MPG for you for three tanks of gas after you have entered the gallons used and miles driven.
I can get my program to start a loop, but I can't figure out how to make it end the loop after 3 runs and give me the Average MPG in 3 tanks. Running the program give me the average, but will keep asking forever.
#include <stdio.h>
int main(void) {
int miles;
float gallons = -1, mg, overall = 0, avg = 0;
while(gallons != 0) {
printf("Enter the gallons used: ");
scanf("%f", &gallons);
if (gallons == 0) {
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;
}
return 0;
}

Try this small changes. Use an iterator to get average of 3 tanks.
Modify like
i=0;
while(i < 3) {
i++;
#include <stdio.h>
int main(void) {
int miles, **i=0;**
float gallons = -1, mg, overall = 0, avg = 0;
**while(i < 3)** {
printf("Enter the gallons used: ");
scanf("%f", &gallons);
if (gallons == 0) {
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;
**i++;**
}
return 0;
}

Sorry: I did not see how is gallons being assigned/initialized in your code, I saw float galons and while (gallons != 0) and then thought that gallons was at some point the result of a computation.
This answer is still useful in my opinion.
Don't use float values to check conditions, floats are not accurate because their machine representation cannot be, so gallons != 0 will probably hardly ever be true, use int instead and your loop control will work correctly. Only use float for the average value.
But in fact, because your specific problem can be solved with a for loop, you should use
for (int i = 0 ; i < 3 ; ++i)
instead, that way you know that it will only loop 3 times.
SIDE NOTE: learn more about scanf() and why you MUST check the value that it retuns in programs like yours.

Your program, as written, does not stop at 3 tanks. It will continuously ask for tanks until you answer 0 to the number of gallons used.
To make it read at most three tanks, replace while (gallons != 0) with for (int i = 0; i < 3; i++). That will make the main loop run three times only.
But then it won't print the overall average. It will simply quit after running three times. The code that shows the overall average is inside that if test that checks if you typed 0 gallons. Remove that if test and move the printf statement which shows the overall average near the end of the program, right before the return statement. This way it will run after the for loop runs 3 times.

float gallons = -1;
It doesn't make any sense;
And you need to notice one thing that is
while(gallons!=0){
//code
}
You are asking the user to enter the value if gallons to input and your not changing it's value so this value will always be true in while and loop will go infinite.
If you need to run the loop three times then you can do it by using variable.
`
int i=3;
while(i>0){//code
i--;
}
Here I have edited your program ;
#include <stdio.h>
int main(void) {
int miles,i=3;
float gallons, mg, overall = 0, avg = 0;
while(i>0) {
printf("Enter the gallons used: ");
scanf("%f", &gallons);
if (gallons == 0) {
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;i--;
}
return 0;
}
`

Related

How to add a running total after each pass in the while loop

I need to figure out how to continuously add to the running total of avg mpg and divide by how many times it goes through.
#include <stdio.h>
int main() {
int miles;
int gallons;
int mpg;
int avg;
while (miles != -1) {
printf("Enter number of miles driven(-1 to quit): ");
scanf("%d", &miles);
printf("Enter gallons used: ");
scanf("%d", &gallons);
mpg = miles / gallons;
avg = mpg;
printf("MPG this trip: %d\n", mpg);
printf("Avg MPG(so far): %d\n", avg);
}
}
Okay so I think I got what you are trying to say, so first of all you should initialize avg = 0; and instead of changing avg = mpg; every time the loop runs you should do avg += mpg; so that it will add the previous values to next time the loop runs, Take another int to find the total average, initialize from 0 int t_avg = 0; and for next thing, dividing how many times it goes through you should take a variable and initialize it t = 0; and just increment t every time the loop runs so you will get the time loop goes on and you just have to divide it with avg.
And I would suggest you to use do while loop instead of while so that would be much better.
Hope this is what you were looking for.
#include <stdio.h>
int main() {
int miles;
int gallons;
int mpg;
int avg = 0, t = 0,t_avg = 0;
do {
t++;
printf("Enter number of miles driven(-1 to quit): ");
scanf("%d", &miles);
printf("Enter gallons used: ");
scanf("%d", &gallons);
mpg = miles / gallons;
avg += mpg;
t_avg = avg/t;
// adding average every time and diving every time the loop runs
printf("MPG this trip: %d\n", mpg);
printf("Avg MPG(so far): %d\n", t_avg);
}while(miles != -1);
}

C: 2 User input fields when requesting 3

From what I understand I should be getting 3 user input prompts, Trip Distance, Car MPG, and Gas Dollars Per Gallon to calculate total trip cost. Whenever I run the code, I only get prompted to input trip distance and car mpg, it skips gas dpg. How do I get it to recognize 3 user inputs?
int main() {
int miles;
double milesPG;
double dollarsPG;
double gasCost = (miles * (1.0 / milesPG) * dollarsPG);
printf("Input trip distance: ", miles);
scanf("%d", &miles);
printf("\nInput car miles per gallon: ", milesPG);
scanf("%0.2lf", &milesPG);
printf("\nInput gas dollars per gallon: ", dollarsPG);
scanf("%0.2lf", &dollarsPG);
printf("\nTotal trip cost is %0.2lf \n", gasCost);
return 0;
}
There are multiple problems in your code:
you do not include <stdio.h>
you compute gasCost before the values of miles, milesPG and dollarsPG are input. Since these variables are uninitialized, this has undefined behavior.
passing the uninitialized values to the printf() statements for prompting is useless and actually has undefined behavior as these variables are uninitialized.
the conversion format "%0.2lf" is invalid for scanf(). You cannot specify how many places to input, just the maximum number of bytes to read, which is not useful in your case.
Here is a modified version:
#include <stdio.h>
int main() {
int miles;
double milesPG;
double dollarsPG;
printf("Input trip distance: ");
if (scanf("%d", &miles) != 1)
return 1;
printf("\nInput car miles per gallon: ");
if (scanf("%lf", &milesPG) != 1)
return 1;
printf("\nInput gas dollars per gallon: ");
if (scanf("%lf", &dollarsPG) != 1)
return 1;
double gasCost = (miles * (1.0 / milesPG) * dollarsPG);
printf("\nTotal trip cost is %.2f\n", gasCost);
return 0;
}

Incorrect output for a particular code. (Maximum, minimum, grade_scanner)

I've been trying to figure this out the last few days, but no luck. The objective is to find the sum, average, minimum, and maximum grades and display them.
Here is my code, everything except minimum, maximum and grade input seem to work
// Includes printf and scanf functions
#include <stdio.h>
int main(void) {
unsigned int counter; // number of grade to be entered next
int grade; // grade value
int total; // sum of grades entered by user
float average; // average of grades
int maxi; // Max grade
int mini; // min grade
int i;
int max;
int min;
maxi = 1;
mini = 1;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
//scanf("%d%d", &min, &max);
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
//scanf("%d",&counter);
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
break;
}
else {
total = total + grade;
average = (float)total / counter; // NOTE: integer division, not decimal
}
}
max = (grade < maxi) ? maxi : grade;
min = (grade > mini) ? mini : grade;
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
Output:
Enter number of grades: 2
5
7
Enter grade 1: 4
Enter grade 2: 3
Class average is: 3.500
Your maximum grade is 3
Your minimum grade is 1
Sum: 7
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade" then from there it calculates everything. Also, it seems that the Maximum is always the last grade that I enter and shows 1 as the minimum when no where in the input is 1. I am supposed to use a conditional operator for the max/min, I tried looking it up and reading the book, but they just use letters like a,b,c, etc. Which just confused me so I'm not sure if I did it wrong.
Could that be what is messing everything up? If it isn't what am I doing wrong?
Another thing is I'm thinking I need a While loop if I want to make the counter have an input from 1-100, is that right?
Edit: just realized I had to remove the scanf for max and min. Taht's why I had to inptu 2 nubmers first
There are two major problems, as I see it
The variable total is not initialized, so the first occurrence of total = total + grade; would invoke undefined behaviour.
You have to initialize it explicitly to 0.
The same variable grade is used for holding the repeated input. After the loop, grade will only hold the last input value.
You need to either use an array for storing inputs and comparison, or, compare and update the min and max as you go, inside the loop.
For future references, please seperate your code in different functions or add comments, since analyzing an unfamiliar code always takes much time.
min: Your problem here lies, that you're initializing your min value with 1. That value is most of the time below your input grades. If you want to initialize it, you should use a high number.
For example:
#include <limits.h>
int min = INT_MAX;
max: Your "grade" will be always the last typed grade, which you scanned. That's not what you want. It would be good, to save all values, which you get as input in an array or a list.
Also your codesnippet at the end
max = (grade<maxi) ? maxi : grade;
min = (grade>mini) ? mini : grade;
will just compare one grade. You need to compare all values, which you entered.
You could just put them in the for-loop.
gradeinput: You need to temporarily save your inputs in a datastructure like an array/list to use them in your program.
int x[counter];
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i);
x[i]=scanf("%d", &grade);
}
.. have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
This happens because OP's stdout is buffered and not one character at a time.
To insure output is seen before the scanf(), use fflush().
See What are the rules of automatic flushing stdout buffer in C?
printf("Enter number of grades: ");
fflush(stdout); // add
scanf("%d", &counter);
Rather than set the min = 1, set to a great value
maxi = 1;
mini = 1;
maxi = 0;
mini = 100;
// or
maxi = INT_MIN;
mini = INT_MAX;
Move the test for min/max in the loop to test each value and fold maxi, max into the same variable.
if (max > grade) max = grade;
if (min < grade) min = grade;
The first total + grade is a problem as total is uninitialized.
// int total; // sum of grades entered by user
int total = 0; // sum of grades entered by user
Unnecessary to calculate average each time though the loop. Sufficient to do so afterward.
Style: After the break; the else is not needed.
Good that code tests user input range. Yet the i-- is incorrect. If code is to break, just break. If code it to try again, the i-- makes sense, but then code should continue.
The comment // NOTE: integer division, not decimal is incorrect as (float) total / counter is FP division.
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n");
i--;
continue;
}
total = total + grade;
} // end for
average = (float) total / counter;
In general, casting should be avoided.
Advanced issue: Consider the situation if later on code was improved to handle a wider range of integers and used higher precision FP math.
The 1st form causes total to become a float (this could lose precision) and perhaps use float to calculate the quotient, even if average was a double. Of course the (float) cast could be edited to (double) as part of the upgrade, but that is a common failure about updates. Types may be changed, but their affected object uses are not fully vetted.
The 2nd form below causes total to become the same type as average and use the matching math for the type. Reduced changed needed as the types change. This form is also easier to review as one does not need to go back and check the FP type of average to see if a cast to float, double or even long double was needed.
average = (float) total / counter;
// or
average = total;
average /= counter;
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
You have two scanf before "Enter grade"
scanf("%d", &counter);
scanf("%d%d", &min, &max);
#include <stdio.h>
int main(void) {
int counter; // number of grade to be entered next
int grade; // grade value
int total=0; // sum of grades entered by user
float average; // average of grades
int i;
int max;
int min;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
} else {
if(i==1){
max = grade;
min = grade;
}
else{
max = (grade < max) ? max : grade;
min = (grade > min) ? min : grade;
}
total = total + grade;
average = (float) total / counter; // NOTE: integer division, not decimal
}
}
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
I've edited your Code as there were some mistakes. First, you were not initialising the total, which may make it take some garbage value. The second one is no need of using break as you are reducing the value of i.The third one is that you are updating the min and max outside the for loop, where the value of grade will be the last entered grade. And maxi and mini are not at all needed. The code was running perfectly without waiting for dummy values. Cheers!

is my code wrong or is my computer slow?

I'm coding in c and have been attempting to make an average calculator, as i am new to coding and only just starting and my code won't work after i input a number for it. the way it should work is you input a number, the code keeps track of the overall number and the amount of numbers entered and prints out the average, doing this all in "do while" loop
my code:
int main()
{
float overall = 0;
float entered = 0;
float times = 0;
float avg = 0;
printf("AVERAGE CALULATOR\n\npress 0 when complete\n\n");
do{
printf("current average: %.2f\n\n", avg);
printf("input number: ");
scanf("%f", entered);
overall += entered;
times++;
avg = overall / times;
}while(entered != 0);
return 0;
}
pleae inform me of incorrect code if you find it
You just forgot the (&) in scanf after the comma.
scanf("%f", &entered);
Scanf needs a pointer to your adress.

C programming nan output

I am very much a beginner to programming in C so please help out here. I am trying to write a program that loops asking the user to enter a number, if the number is positive it adds it to the total, and if it is negative it ends the program and displays the average, lowest input, and highest input. Unfortunately no matter what I change with the low and high things I keep getting 'nan' for the low, and whatever the negative number for the high.. please help!
#include<stdio.h>
int main(void)
{
float input;
float total;
float low;
float high;
float average;
int count=0;
printf("\n\nPlease enter a positive number to continue or a negative number");
printf(" to stop: ");
scanf("%f", &input);
while (input > 0)
{
count = count + 1;
printf("\nPlease enter a positive number to continue or a negative");
printf(" number to stop: ");
scanf("%f", &input);
total = total + input;
if ( low < input )
{
( low = input );
}
else
{
( low = low );
}
}
if (input < high)
{
(high = input);
}
else
{
(high = high);
}
average = total / count;
printf("\n\n\nCount=%d",count);
printf("\n\n\nTotal=%f",total);
printf("\nThe average of all values entered is %f\n", average);
printf("\nThe low value entered: %f\n", low);
printf("\nThe highest value entered: %f\n", high);
return 0;
}
After compiling it with gcc and testing it with the numbers 1, 5, 4, then -1 I get the following output
Count=3
Total=8.000000
The average of all values entered is 2.666667
The low value entered: nan
The highest value entered: -1.000000
You have fallen victim to garbage values - a common mistake for beginners. Specifically, its happening in these lines -
float total;
float low;
float high;
float average;
When you write that, the system assigns the variables a memory location. The computer though, is not infinite, so it just uses a memory location that used to be used by something else, but is no longer being used. Most of the time though, the 'something else' doesnt clean up after itself (because it would take a lot of time), so the information that was there is left there, such as fdaba7e23f. This is totally meaningless to us, so we call it a garbage value.
You can fix this by initializing the variables, like so -
float total=0;
float low;
float high;
float average=0;
Note that you will have to add some extra logic for the low variable. Here is one way to do it -
printf("\n\nPlease enter a positive number to continue or a negative number");
printf(" to stop: ");
scanf("%f", &input);
low=input;
high=input;
while (input > 0)
....
....
As you can see, I just copied your code and added two lines after the first scanf.
For one thing, I don't know if you have noticed it, your count and total are all screwed up.
Please change the order of execution, apart from the initialization answer given by #Drgin
int total = input;
while (input > 0)
{
printf("\nPlease enter a positive number to continue or a negative");
printf(" number to stop: ");
scanf("%f", &input);
count = count + 1;
total = total + input;

Resources