C program for bowling game - c

I need to write a program for a game of bowling. Ask the user to enter the number of games and the number of bowlers. For each bowler, get the score for each game. Display the score. Calculate the average for each bowler and display the average. Finally display the team average.
I wrote a code, it doesn't have errors but the problem is that it doesn't count average score for players and total score for team. Need help with these calculations.
#include <stdio.h>
int main()
{
int playerTotal = 0;
int teamTotal = 0;
int score;
int numgames, player, bowler, game;
printf ("How many games?\n");
scanf ("%d", &numgames);
printf ("How many players?\n");
scanf ("%d", &player);
for (bowler = 1; bowler <= 3; bowler++)
{
for (game = 1; game <= 2; game++)
{
printf ("\nEnter the score for game %d for bowler %d: ", game, bowler);
scanf ("%d", &score);
playerTotal += score;
}
printf ("\nThe average for bowler %d is: ", bowler, playerTotal/2);
printf ("\nThe total for the game is:", teamTotal);
teamTotal += playerTotal;
}
return 0;
}

It's nothing to do with "not counting" - you're just not printing them. This:
printf ("\nThe average for bowler %d is: ", bowler, playerTotal/2);
printf ("\nThe total for the game is:", teamTotal);
should be:
printf ("\nThe average for bowler %d is: %.1f", bowler, playerTotal / 2.0);
printf ("\nThe running team total is: %d", teamTotal);
Note the change from 2 to 2.0, since playerTotal is an int, but if the total is odd then the average will (or should) have a .5 on the end.
You're also going to want to set playerTotal = 0; at the start of your outer for loop, otherwise each player is going to get the scores of all the bowlers who entered their scores previously, which is probably not all that fair of a scoring system. You should change:
for (bowler = 1; bowler <= 3; bowler++)
{
for (game = 1; game <= 2; game++)
{
to:
for (bowler = 1; bowler <= player; ++bowler) {
playerTotal = 0;
for (game = 1; game <= numgames; ++game) {
which will also loop for the same number of times that you had the user enter. If you do this, you'll also need to change:
printf ("\nThe average for bowler %d is: %.1f", bowler, playerTotal / 2.0);
to:
printf ("\nThe average for bowler %d is: %.1f", bowler,
playerTotal / (double) numgames);
to divide your average by the correct number of games.
Other than those things, you made a pretty nice attempt.

Related

What am I doing wrong with for loop?

Please help. I am supposed to Calculate 3 MPG for 3 tanks. I am able to do it without using a loop. However, I am supposed to use a for-loop to replace one section of code. I think I have the proper code but I just don't know if I placing it correctly.
So, instead of writing "Enter the number of miles driven", 3 times, it's supposed to be replaced by for (miles = 1; miles <=3; miles = miles+1) {
miles = miles + 0;. IS this right? I asked my professor do we use counters, or nested loops, and I was told no. What am I doing wrong?
#include <stdio.h>
int main (void)
{
/*Variable Delclarations*/
/*----------------------*/
float gallons = 0;
float miles = 0;
float mpg = 0;
float avg = 0;
printf ("\nEnter the number of gallons used in tank #1: ");
scanf ("%f/n", &gallons);
for (miles = 1; miles <=3; miles = miles+1) {
miles = miles + 0;
printf ("Enter the number of miles driven: ");
}
scanf ("%f/n", &miles);
printf ("/nThe miles per gallon for this tank is: %.1f\n miles per gallon",
(float)miles/gallons);
printf("\n\n"); /* new line */
printf ("Enter the number of gallons used in tank #2: ");
scanf ("%f/n", &gallons);
for (miles = 1; miles <=3; miles = miles+1)
miles = miles + 0;
printf ("Enter the number of miles driven: ");
scanf ("%f/n", &miles);
printf ("The miles per gallon for this tank is: %.1f\n", (float)miles/gallons);
printf("\n\n"); /* new line */
printf ("/nEnter the number of gallons used in tank #3: ");
scanf ("%f/n", &gallons);
for (miles = 1; miles <=3; miles = miles+1)
miles = miles + 0;
printf ("Enter the number of miles driven: ");
scanf ("%f/n", &miles);
printf ("The miles per gallon for this tank is: %.1f\n", (float)miles/gallons);
printf("\n\n"); /* new line */
printf ("Your overall average miles per gallon for three tanks is %.1f\n")
scanf ("%f/n", &avg);
}
So in this case there is no need for three separate loops, everything can be handled in one. What you're trying to do in this exercise is get three separate inputs for your tanks. these inputs can be gathered using the scanf command. For each loop your gallons and miles variable should be assigned to a value of 0;
this would result in the following code for the inside of the loop:
miles = 0;
gallons = 0;
printf ("Enter the number of gallons used in tank #%i: ", tank);
scanf ("%f", &gallons);
printf ("Enter the number of miles driven: ");
scanf ("%f", &miles);
printf ("The miles per gallon for this tank is: %.1f miles per gallon", (float)(miles / gallons));
avg += (miles / gallons);
printf("\n\n");
you can add the result of miles / gallons onto average and at the end divide this by the total amount of tanks.
If you do all of this you should end up with something that looks like this:
#include <stdio.h>
int main (void)
{
float gallons = 0;
float miles = 0;
float avg = 0;
int tank_amount = 3;
for (int tank = 1; tank <= tank_amount; tank++) {
miles = 0;
gallons = 0;
printf ("Enter the number of gallons used in tank #%i: ", tank);
scanf ("%f", &gallons);
printf ("Enter the number of miles driven: ");
scanf ("%f", &miles);
printf ("The miles per gallon for this tank is: %.1f miles per gallon", (float)(miles / gallons));
avg += (miles / gallons);
printf("\n\n");
}
printf ("Your overall average miles per gallon for three tanks is %.1f\n", (avg / tank_amount));
}
Also be sure to indent your code in a nice and readable way and use {} brackets for your loops, this makes it a lot easier to read, which also helps if u need to debug it :)
You have three for() loops. The first one contains two statements: a print statement that will therefore be printed three times, and "miles = miles + 0", which does exactly nothing. The other two for loops (since they don't have braces) include only one statement, the same "miles = miles + 0", which does nothing.
Always use braces with your loops, and make sure that whatever you want to happen multiple times is inside the braces. And indent your code so that you can see at a glance what's inside and outside. Finally, if you use a variable like "miles" in the for() statement, don't also modify it inside the loop.

Calculating the Positive scores only AND changing the result of the Average from Integer to Float

Here is my code in C, I need help with how to ignore the negative numbers in the printf("You entered %d scores.\n", i); and in the average result.Also how to change int average; to float average; because I don’t get the right average when I change it to float.
Here is my code:
int main()
{
int i, score, sum=0, n;
int average;
for(i=0; score>0; i++)
{
printf("Enter score (4-10) :");
scanf("%d", &score);
if(score>0){
sum = sum + score;
}
}
printf("You entered %d scores.\n", i);
average = sum / i;
printf("the average is: %d", average);
}
The required Output:
The program calculates the average of scores you enter.
End with a negative integer.
Enter score (4-10):7
Enter score (4-10):8
Enter score (4-10):9
Enter score (4-10):10
Enter score (4-10):4
Enter score (4-10):4
Enter score (4-10):5
Enter score (4-10):-1
You entered 7 scores.
Average score: 6.71
It seems that the average, sum, and scores should all be decimal values (floats).
That means you have to change the scanf argument as well and the printf argument.
When dividing the integer i into the float sum, there is no need to multiply by 1.0, as long as sum is a float.
#include <stdio.h>
int main()
{
int i;
float score;
float sum = 0;
float average;
for (i = 0; score > 0; i++) {
printf("Enter score (4-10) :");
scanf("%f", &score); // accept decimals in the scores
if (score > 0) {
sum = sum + score;
} else {
break; /// leave the loop here to prevent incrementing i
}
}
printf("You entered %d scores.\n", i);
average = sum / i; // as sum is a float, this division will now work.
printf("the average is: %2.2f", average); // print 2 decimal places as a float
}
int main()
{
int i, score = 1, n;
float sum = 0.0, average; //<-------------changed to float
for(i=0; score>0; i++)
{
printf("Enter score (4-10) :");
scanf("%d", &score);
if(score>0){
sum = sum + score;
}
else{
break;
}
}
printf("You entered %d scores.\n", i);
average = sum / i;
printf("The average is: %f", average); //<--- changed to %f you can use &.2f to print 2 digits after .
return 0;
}

Outputting the maximum and minimum value from an array in C

I have written a program that asks the user the input the high and low temperature over the course of four days. Following this, the program calculates the mean temperature using the inputs from all four days. Everything is working fine however, I need to have the program determine and output the greatest high temperature and the day it occurred on as well as the smallest low temperature and the day it occurred on. Here's my code so far
#include <stdio.h>
#define NUMS 4
int main (void)
{
int high[NUMS];
int low[NUMS];
const int MAX = 40;
const int MIN = -40;
int totalhigh;
int totallow;
int sum;
float avg;
printf ("---===IPC Temperature Analyzer ===---\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
while (high[0] > MAX || low[0] < MIN || high[0] < low[0]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
}
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
while (high[1] > MAX || low[1] < MIN || high[1] < low[1]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
}
printf ("Enter the high value for day 3: ");
scanf ("%d", &high[2]);
printf ("Enter the low value for day 3: ");
scanf ("%d", &low[2]);
}
printf ("Enter the high value for day 4: ");
scanf ("%d", &high[3]);
printf ("Enter the low value for day 4: ");
scanf ("%d", &low[3]);
while (high[3] > MAX || low[3] < MIN || high[3] < low[3]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day 4: ");
scanf ("%d", &high[3]);
printf ("Enter the low value for day 4: ");
scanf ("%d", &low[3]);
}
totalhigh = high[0] + high[1] + high[2] + high[3];
totallow = low[0] + low[1] + low[2] + low[3];
sum = totalhigh + totallow;
avg = sum/8.0;
printf ("The average (mean) temperature was: %.2f\n", avg);
if (high[0] > high[1] || high[0] > high[2] || high[0] > high[3]) {
printf ("The highest temperature was %d, on day 1\n", high[0]);
}
else if (high[1] > high[0] || high[1] > high[2] || high[1] > high[3]) {
printf ("The highest temperature was %d, on day 2\n", high[1]);
}
else if (high[2] > high[0] || high[2] > high[1] || high[2] > high[3]){
printf ("The highest temperature was %d, on day 3\n", high[2]);
}
else {
printf ("The highest temperature was %d, on day 4\n", high[3]);
}
return 0;
}
Your current code can use a loop and a helper function, which would shorten your code by reducing all those scanf() calls. You could also abstract a lot more, by using more functions, but it will show the general idea.
It is also good to check the result of scanf(), just in case the user enters a non-integer.
Your current code could look like this:
#include <stdio.h>
#include <stdlib.h>
#define NUMS 4
/* takes a pointer to a number */
void get_input(int *temp) {
if (scanf("%d", temp) != 1) {
printf("Invalid temp entered\n");
exit(EXIT_FAILURE);
}
}
int main(void) {
int high[NUMS];
int low[NUMS];
const int MAX = 40;
const int MIN = -40;
int day = 1, totalhigh = 0, totallow = 0, sum;
float avg;
for (size_t i = 0; i < NUMS; i++) {
printf ("Enter the high value for day %d: ", day);
/* takes the address of the pointer given by get_input() */
get_input(&high[i]);
printf ("Enter the low value for day %d: ", day);
get_input(&low[i]);
while (high[i] > MAX || low[i] < MIN || high[i] < low[i]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day %d: ", day);
get_input(&high[i]);
printf ("Enter the low value for day %d: ", day);
get_input(&low[i]);
}
day++;
}
for (size_t i = 0; i < NUMS; i++) {
totalhigh += high[i];
totallow += low[i];
}
sum = totalhigh + totallow;
avg = sum/8.0;
printf ("The average (mean) temperature was: %.2f\n", avg);
return 0;
}
In terms of finding the largest and smallest temperatures, here is a method you can use:
Set max and min to the first element of your array, array[0].
loop from i=1 to i=n.
If and element if bigger than max, set max to array[i]. If an element is smaller than min, set min to array[i].
The day for the highest and lowest temperatures will be i+1.
Since doing something like this will help you understand loops better, I decided to just describe the steps. The above code was just an improvement on your current code, and showing you a easier way to do it will show you a different perspective on how to do problems like these.
I updated my code to have the if statement mentioned in my above code to function correctly. Here it is:
if (high[0] > high[1] && high[0] > high[2] && high[0] > high[3]) { // Check to see if day 1 has the highest temperature against days 2,3 and 4.
printf ("The highest temperature was %d, on day 1\n", high[0]); // Output day 1 as the highest temperature and indicate the temperature value.
}
else if (high[1] > high[0] && high[1] > high[2] && high[1] > high[3]) { // Same function as the above function for day 1 except this is used for day 2.
printf ("The highest temperature was %d, on day 2\n", high[1]); // Refer to day 1 printf
}
else if (high[2] > high[0] && high[2] > high[1] && high[2] > high[3]){
printf ("The highest temperature was %d, on day 3\n", high[2]);
}
else {
printf ("The highest temperature was %d, on day 4\n", high[3]);
}
// Switch out high values with low values in order to determine lowest temperature and its corresponding day.

for/while loop memory clearing in C

In my program I'm messing around with, it simply asks for how many tests one has written and then returns an average. However I've modified it a bit so that it asks if the marks entered are correct.
Problem 1: It doesn't let you input your marks for all your tests
Problem 2: If the marks are wrong it starts over but keep the previous inputs in it's memory? How do I fix the?
Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
//int variables for grade
unsigned int counter; //number of grades to be entered next
int grade;
int total;
float average;
// user input
int userInput; // amount of tests
int yesNo;
//amount of test passed
unsigned int pass = 0;
unsigned int fail = 0;
int doCount = 1;
//unsigned int test;
//---------------------------------------------------------------------------------------------------//
//standards for program to abide to
total = 0; //Total amount of test to be set to zero, until while statement
counter = 1; //Loop counter to start from one
//---------------------------------------------------------------------------------------------------//
printf ("Please enter amount of test you've written so far: ");
scanf ("%d", &userInput);
//printf ("%d", userInput);
//---------------------------------------------------------------------------------------------------//
do {
//Body of calculations of program
for(counter = 0; counter <= userInput; ++counter) { //for loop that correlates to userInput for amount of passes and test marks
printf ("Please enter percentage mark: "); //prompt for test mark
scanf("%d", &grade);
total = total + grade;
counter = counter + 1;
if (grade >= 40) { //if statement for pass or fail
pass = pass + 1;
} else {
fail = fail + 1;
}
}//end of for loop
printf ("Are the grades entered correct? (1 = yes, 2 = no): "); // user input for yesNo - are inputs correct
scanf ("%d", &yesNo);
if (yesNo == 2) {
} else {
average = ((float)total / userInput); //Getting average for tests so far
//if statement to clarify if you're passing
if (average < 40) {
printf ("\nYou are below sub minimum!\n");
printf ("Your overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
} else if (average >= 75){
printf ("\nYou have a distinction agregate!\n");
printf ("Your overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
} else {
printf ("\nYour overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
}
doCount = 2;
}
} while (doCount == 1);
average = ((float)total / userInput); //Getting average for tests so far
//---------------------------------------------------------------------------------------------------//
getch ();
return 0;
}
In your do while loop, when you come around for your second pass you need to reset your variables. Specifically the total variable should be reset to zero. You do it for the first time outside the do while loop but once it's in the loop for the second pass it doesn't get reset to 0.
As for not reading all test inputs, if it asks for 9 but you need 10 then it likely is a problem with the for loop. I typically use counter++ and not ++counter as it increments the counter after the operation and not before the operation. That may or may not be the reason as I did not run your code, but it is worth looking at.
I've edited your code and commented the changes:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
//int variables for grade
unsigned int counter; //number of grades to be entered next
int grade;
int total;
float average;
// user input
int userInput; // amount of tests
int yesNo;
//amount of test passed
unsigned int pass = 0;
unsigned int fail = 0;
int doCount = 1;
//unsigned int test;
//---------------------------------------------------------------------------------------------------//
//standards for program to abide to
total = 0; //Total amount of test to be set to zero, until while statement
counter = 0; //Loop counter to start from zero, It's always better to start from zero
//---------------------------------------------------------------------------------------------------//
printf("Please enter amount of test you've written so far: ");
scanf("%d", &userInput);
//printf ("%d", userInput);
//---------------------------------------------------------------------------------------------------//
do {
//Body of calculations of program
total = 0; //You need to reset total pass and fail
pass = 0;
fail = 0;
for (counter = 0; counter < userInput; ++counter) { //for loop that correlates to userInput for amount of passes and test marks
printf("Please enter percentage mark: "); //prompt for test mark
scanf("%d", &grade);
total = total + grade;
//counter = counter + 1; You DON't need that
if (grade >= 40) { //if statement for pass or fail
pass = pass + 1;
}
else {
fail = fail + 1;
}
}//end of for loop
printf("Are the grades entered correct? (1 = yes, 2 = no): "); // user input for yesNo - are inputs correct
scanf("%d", &yesNo);
if (yesNo == 2) {
}
else {
average = ((float)total / userInput); //Getting average for tests so far
//if statement to clarify if you're passing
if (average < 40) {
printf("\nYou are below sub minimum!\n");
printf("Your overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
else if (average >= 75) {
printf("\nYou have a distinction agregate!\n");
printf("Your overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
else {
printf("\nYour overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
doCount = 2;
}
} while (doCount == 1);
average = ((float)total / userInput); //Getting average for tests so far
//---------------------------------------------------------------------------------------------------//
getch();
return 0;
}

Loop with rolling total in c

I am trying to get a c program to ask me how many items i am buying than to ask the price for each item while keeping a rolling total and than ask again in a loop. I have the loop working fine but am having problems getting it to give me proper output.
here is the output i am getting when i run it.
http://i119.photobucket.com/albums/o134/halodude808/assignment2_zpsd46e84b8.jpg
#include <stdio.h>
#include <math.h>
int main(void)
{
//variables used
float penny = .01;
float nickel = .05;
float dime = .1;
float quarter = .25;
int items = 0;
float paid= 0.0;
float total = 0.0;
float price =0.0;
int counter =0.0;
for (;;)
{
printf("Please enter the number of grocery items:");
scanf("%d", &items);
for (counter = 1; counter <= items; counter++)
{
printf("Please enter the price for item #%d:", counter);
scanf("%f", &price);
total += price;
}
printf("items = %d total = %f \n", &items, &total);
getchar();
getchar();
}
}
Change
printf("items = %f total = %f \n", &items, &total);
to
printf("items = %i total = %f \n", items, total);
Also, you might want to consider checking for invalid values (zeroes, negative, characters, etc).

Resources