I am currently in the process of learning C and one of the challenge questions at the end of a chapter has me building a GPA Calculator. Here is the Challenge:
Create a student GPA average calculator. The program should prompt the user to enter up to 30 GPAs, which are stored in a single-dimension array. Each time he or she enters a GPA, the user should have the option to calculate the current GPA average or enter another GPA. Sample data for this program:
GPA: 3.5
GPA: 2.8
GPA: 3.0
GPA: 2.5
Hint: Be careful to not calculate empty array elements into your student GPA average.
I have the program appear to somewhat work but when it calculates the GPA average it calculates wrong. Will someone please take a look at my source code and let me know what I did wrong?
Source Code
#include <stdio.h>
int main()
{
float fGrades[30] = {0};
float fAverage = 0;
int x;
int y = 0;
float fSum = 0;
char cResp = '\0';
printf("\nGPA Calculater");
printf("\nYou can enter up to 30 grades");
do
{
printf("\nPlease enter a grade and press enter: ");
scanf("%f", &fGrades[x]);
printf("\nDo you want to calculate the GPA? (Y or N): ");
scanf("\n%c", &cResp);
} while (x < 30 && cResp != 'Y' && cResp != 'y');//end do while loop
for (x = 0; x < 30; x++)
{
fSum += fGrades[x];
}//end for loop
fAverage = fSum / x;
printf("\nYour final GPA is: %.2f\n", fAverage);
return 0;
}//end main function
Output I get is as follows:
GPA Calculater
You can enter up to 30 grades
Please enter a grade and press enter: 3.22
Do you want to calculate the GPA? (Y or N): n
Please enter a grade and press enter: 3.13
Do you want to calculate the GPA? (Y or N): n
Please enter a grade and press enter: 2.89
Do you want to calculate the GPA? (Y or N): n
Please enter a grade and press enter: 3.05
Do you want to calculate the GPA? (Y or N): y
Your final GPA is: 0.10
A few things to suggest:
initialize x to 0
in the initial do/while loop, increment x after you have scanf'd in the array
in the loop that calculates fSum, use another counter and go from counter = 0; counter < x; ++counter and use fSum += fGrades[counter];.
Your problem is, that you always sum up 30 elements no matter what.
You should only add as many items that have been entered by the user.
So something like:
#include <stdio.h>
int main()
{
float fGrades[30] = {0};
float fAverage = 0;
int x;
int y = 0;
int counter = 0;
float fSum = 0;
char cResp = '\0';
printf("\nGPA Calculater");
printf("\nYou can enter up to 30 grades");
do
{
printf("\nPlease enter a grade and press enter: ");
scanf("%f", &fGrades[counter]);
counter++;
printf("\nDo you want to calculate the GPA? (Y or N): ");
scanf("\n%c", &cResp);
} while (counter < 30 && cResp != 'Y' && cResp != 'y');//end do while loop
for (x = 0; x < counter; x++)
{
fSum += fGrades[x];
}//end for loop
fAverage = fSum / x;
printf("\nYour final GPA is: %.2f\n", fAverage);
return 0;
}//end main function
change the loop that calculated fSum to work with another variable instead of x
int i;
for ( i = 0; i < x; i++)
{
fSum += fGrades[ i ];
}//end for loop
There are multiple problems
1) x is not initialized, so scanf in do-while may crash your code
2) x in not incremented in do-while
3) while calculating average, you should sum only entered values, not all 30 values, else your average calculation will be wrong
Modified code as below, please check
int main()
{
float fGrades[30] = {0};
float fAverage = 0;
int x;
int y = 0;
float fSum = 0;
char cResp = '\0';
printf("\nGPA Calculater");
printf("\nYou can enter up to 30 grades");
x = 0;
do
{
printf("\nPlease enter a grade and press enter: ");
scanf("%f", &fGrades[x]);
printf("\nDo you want to calculate the GPA? (Y or N): ");
scanf("\n%c", &cResp);
x++;
} while (x < 30 && cResp != 'Y' && cResp != 'y');//end do while loop
for (y = 0; y < x; y++)
{
fSum += fGrades[y];
}//end for loop
fAverage = fSum / x;
printf("\nYour final GPA is: %.2f\n", fAverage);
return 0;
}//end main function
You can remove the 'for' loop to calculate the sum of all values. You can calculate the sum into the 'do while' loop. It will make your code more efficient.
#include <stdio.h>
int main()
{
float fGrades[30] = {0};
float fAverage = 0;
int x;
int y = 0;
float fSum = 0;
char cResp = '\0';
int count = 0;
printf("\nGPA Calculater");
printf("\nYou can enter up to 30 grades");
do
{
printf("\nPlease enter a grade and press enter: ");
scanf("%f", &fGrades[x]);
fSum += fGrades[x];
count++;
printf("\nDo you want to calculate the GPA? (Y or N): ");
scanf("\n%c", &cResp);
} while (x < 30 && cResp != 'Y' && cResp != 'y');//end do while loop
fAverage = fSum / count;
printf("\nYour final GPA is: %.2f\n", fAverage);
return 0;
}//end main function
Related
I'm currently trying to create a C program for a class assignment that takes the average of an arbitrary amount of test scores. However, I've run into some problems.
My professor has provided an outline to help get started. I also can only add code where indicated, so no extra variables and such.
This is what I have so far:
#include <stdio.h>
void calculateAverage()
{
int grade, count, sum;
double average;
/* add code to input grades, calculate average, and print it */
/* --> between here */
printf("Enter the amount of test scores.\n");
scanf("%d", &count);
grade = 0;
sum = 0;
while (grade != -1 && grade <= 100 && grade >= 0)
{
printf("Enter the grade. Enter -1 when you are done entering grades.\n");
scanf("%d", &grade);
if (grade != -1 && grade <= 100 && grade >= 0)
{
sum = sum + grade;
}
else
{
average = (sum / count);
printf("average is %.2lf \n", &average);
}
}
/* --> and here */
}
int main(void)
{
while (1)
calculateAverage();
return 0;
}
So the problem I've ran into is that with what I have so far, the average will always be calculated as 0. Why exactly is this happening, and how would I fix it so it gives me the correct average?
UPDATE
So I tried casting the average to double so I can avoid a type mismatch, which did get rid of my compiler warnings but the average is still coming out to 0 for all inputed values.
#include <stdio.h>
void calculateAverage()
{
int grade, count, sum;
double average;
/* add code to input grades, calculate average, and print it */
/* --> between here */
printf("Enter the amount of test scores.\n");
scanf("%d", &count);
grade = 0;
sum = 0;
while (grade != -1 && grade <= 100 && grade >= 0)
{
printf("Enter the grade. Enter -1 when you are done entering grades.\n");
scanf("%d", &grade);
if (grade != -1 && grade <= 100 && grade >= 0)
{
sum = sum + grade;
}
else
{
average = (double)(sum / count);
printf("average is %.2f \n", &average);
}
}
/* --> and here */
}
int main(void)
{
while (1)
calculateAverage();
return 0;
}
#include <stdio.h>
void calculateAverage()
{
int grade, count, sum;
double average;
/* add code to input grades, calculate average, and print it */
/* --> between here */
printf("Enter the amount of test scores.\n");
scanf("%d", &count);
grade = 0;
sum = 0;
while (grade != -1 && grade <= 100 && grade >= 0)
{
printf("Enter the grade. Enter -1 when you are done entering grades.\n");
scanf("%d", &grade);
if (grade != -1 && grade <= 100 && grade >= 0)
{
sum = sum + grade;
}
else
{
average = (double)(sum / count);
printf("average is %.2lf \n", average); # <---- Please fix this!
}
}
/* --> and here */
}
int main(void)
{
while (1)
calculateAverage();
return 0;
}
There are a few problems in your code:
One is you are printing the address of average using & operator.
Another thing you can change is to use the correct format specifier when printing double.
Here I have created a compounding interest calculator. The user inputs principal, interest% and duration (in quarters). I have used a for loop for the initial calculation. But, I don't know how to get the total to rollover to the next quarter's principal.
Say the user inputs 1000, 5% and 2 quarters. The output should look like, Q1 Principal=$1000, Interest=0.05, Total=$1012.50, Q2 =$1012.50 =0.05 =$1025.16
Also my last Do while is giving me some issues. The ouput is spitting out a couple extra lines before letting the user start over.
Any advice would be greatly appreciated.
Thank you
#include <stdio.h>
int main (void)
{
int a = 0, b=0;
double interest, prin, total=0;
char check = ' ';
do{
do{
do{
printf (" Please enter principal:\n");
scanf ("%lf", &prin);
}while(prin <=0);
do{
printf ("Please enter desired interest greater
than 0 less than 20 :\n");
scanf ("%lf", &interest);
}while(interest <=0 || interest >20);
interest = interest/100;
do{
printf ("For how many quarters would you like
to deposit: (more than 0, less than 40) \n");
scanf ("%d", &b);
}while(b <=0 || b >40);
printf ("Is this information correct? Press X
to continue" );
scanf ("\n%c", &check);
}while(check != 'x' && check != 'X');
total = prin * (1+(interest *.25));
printf ("Quarter Principal Interest
Total\n");
for(a=1; ;++a){
printf ("%2d $%.2f %.2lf
$%.2lf\n", a, prin, interest, total);
if(a == b)
break;
}
printf ("Do you want to start over (Y/N)?");
scanf ("%c\n", &check);
}while(check != 'y' || check != 'Y');
return 0;
}
The are some problem with indentation and logic in your code. You need to updade principle in for loop statement. Then print it out .Here is my solution
#include <stdio.h>
int main(void)
{
int a = 0, b = 0;
double interest, prin, total = 0;
char check = ' ';
do {
do {
do {
printf(" Please enter principal:\n");
scanf("%lf", &prin);
} while (prin <= 0);
do {
printf("Please enter desired interest greater than 0 less than 20 :\n");
scanf("%lf", &interest);
} while (interest <= 0 || interest > 20);
interest = interest / 100;
do {
printf("For how many quarters would you like to deposit : (more than 0, less than 40) \n");
scanf("%d", &b);
} while (b <= 0 || b > 40);
printf("Is this information correct? Press X to continue" );
scanf("\n%c", &check);
} while (check != 'x' && check != 'X');
printf("Quarter Principal Interest Total\n");
for (a = 1; a<=b; ++a) {
total = prin * (1 + (interest *.25));
printf("%2d $%.2f %.2lf $%.2lf\n", a, prin, interest, total);
prin = total;
}
printf("Do you want to start over (Y/N)?");
scanf("%c\n", &check);
} while (check != 'y' || check != 'Y');
return 0;
}
i am trying to get this program to repeat when prompted Y or N and i cant seem to get it to work right for some reason and this is the last thing i have left and im pretty sure the rest of the code is right i think all i need is it to repeat the whole program if the user enters a "Y" or just exits if the user enters "N"
int main(void)
{
// Constant and Variable Declarations
const int MPH_SPEED_MIN = 1;
const int MPH_SPEED_MAX = 100;
const int HOURS_TRAVLED_MIN = 1;
int mphSpeed = 1;
int hoursEntered = 0;
int distanceTraveled = 0;
int counterNum = 0;
int distanceNum = 0;
char ch = 'y';
// *** Input ***
do {
printf("What is the speed of the vehicle in MPH? ");
scanf("%d", &mphSpeed);
while ((mphSpeed < MPH_SPEED_MIN) || (mphSpeed > MPH_SPEED_MAX)) {
printf("\tThe speed entered must be between %d and %d inclusive
\n",MPH_SPEED_MIN, MPH_SPEED_MAX);
printf("\tPlease re-enter the speed of the vehicle in MPH: ");
scanf("%d", &mphSpeed);
}
printf("How many hours has it traveled? ");
scanf("%d", &hoursEntered);
while (hoursEntered < HOURS_TRAVLED_MIN) {
printf("\tThe hours traveled must be a positive number.\n");
printf("\tPlease re-enter the number of hours traveled: ");
scanf("%d", &hoursEntered);
}
printf("\n");
printf("Hour\tDistance Traveled\n");
distanceTraveled = hoursEntered * mphSpeed;
for (counterNum = 1; counterNum <= hoursEntered; counterNum++) {
distanceNum = distanceTraveled * counterNum;
printf("%d\t%d miles\n", counterNum, distanceNum);
}
printf("\n");
printf("Run the program again (Y/N)? ");
scanf("%c", &ch);
printf("\n");
} while (ch == 'Y' || ch == 'y');
; return 0;
When reading in with scanf(%c..., the statement very likely reads in a new line character left in the buffer from previous inputs. Read in a string instead, because %s ignores any leading white spaces (including such a new line character left in the buffer).
Try ...
char exitYN[2];
if (scanf("%1s",exitYN) != 1) {
exitYN[0]='N';
}
char ch = exitYN[0];
} while (ch == 'Y' || ch == 'y');
The one small yet, the most effective change that can be made here is adding a <space> before the %c while accepting the Y or N, i.e, scanf(" %c, &ch");
And I don't know if the following are errors while typing the code in StackOverflow, or are they originally errors in your code, but definitely are worth making changes:
Header file missing: #include<stdio.h>,
Unwanted and extra semicolon (;) before the return statement at the end,
missing closing bracket (}) at the end, after the return.
Here is the working code:
#include<stdio.h>
int main(void)
{
// Constant and Variable Declarations
const int MPH_SPEED_MIN = 1;
const int MPH_SPEED_MAX = 100;
const int HOURS_TRAVLED_MIN = 1;
int mphSpeed = 1;
int hoursEntered = 0;
int distanceTraveled = 0;
int counterNum = 0;
int distanceNum = 0;
char ch = 'y';
// *** Input ***
do {
printf("What is the speed of the vehicle in MPH? ");
scanf("%d", &mphSpeed);
while ((mphSpeed < MPH_SPEED_MIN) || (mphSpeed > MPH_SPEED_MAX)) {
printf("\tThe speed entered must be between %d and %d inclusive\n",MPH_SPEED_MIN, MPH_SPEED_MAX);
printf("\tPlease re-enter the speed of the vehicle in MPH: ");
scanf("%d", &mphSpeed);
}
printf("How many hours has it traveled? ");
scanf("%d", &hoursEntered);
while (hoursEntered < HOURS_TRAVLED_MIN) {
printf("\tThe hours traveled must be a positive number.\n");
printf("\tPlease re-enter the number of hours traveled: ");
scanf("%d", &hoursEntered);
}
printf("\n");
printf("Hour\tDistance Traveled\n");
distanceTraveled = hoursEntered * mphSpeed;
for (counterNum = 1; counterNum <= hoursEntered; counterNum++) {
distanceNum = distanceTraveled * counterNum;
printf("%d\t%d miles\n", counterNum, distanceNum);
}
printf("\n");
printf("Run the program again (Y/N)? ");
scanf(" %c", &ch);
printf("\n");
} while (ch == 'Y' || ch == 'y');
return 0;
}
I have also attached the output just in case you need to verify.
OUTPUT:
What is the speed of the vehicle in MPH? 12
How many hours has it traveled? 1
Hour Distance Traveled
1 12 miles
Run the program again (Y/N)? y
What is the speed of the vehicle in MPH? 6
How many hours has it traveled? 6
Hour Distance Traveled
1 36 miles
2 72 miles
3 108 miles
4 144 miles
5 180 miles
6 216 miles
Run the program again (Y/N)? n
I'm very new to programming (so I apologize in advance), and I am having trouble figuring out how to make a for loop that will do the following:
I'm asking the user to input two variables (i'll call them x & y), which I then am calculating x/y = z. I want to pose this two variable input question 3 times, and then add up the 3 z to find the average. (The later part about accumulating/averaging I can figure out, but getting a for loop to repeat and give z three times is stumping my extremely novice mind. So far I can only get the for loop to ask for the two variable inputs one time, spit out z, and then terminate (I haven't attempted the averaging of z yet, because I don't have more than one z at this time).
To make things clearer, here's what I've got:
#include <stdio.h>
int main(void)
{
float x, y, z;
int c;
printf ("Enter x: ");
scanf ("%f", &x);
while ( (c = getchar() != '\n') && c != EOF);
printf ("Enter y: ");
scanf ("%f", &y);
while ( (c = getchar() != '\n') && c != EOF);
for (; x <3; x++)
{
z = x / y;
printf("Your average is %f\n", z);
}
printf("Thank you for using the program. Goodbye\n" );
getchar();
return 0;
}
Thanks for your help!!
#include <stdio.h>
int main(void)
{
float z[3];
for (int i = 0; i < 3; ++i)
{
float x, y;
printf ("Enter x: ");
scanf ("%f", &x);
printf ("Enter y: ");
scanf ("%f", &y);
z[i] = x / y;
printf("Your average is %f\n", z[i]);
}
printf("Your overall average is %f\n", (z[0] + z[1] + z[2]) / 3);
printf("Thank you for using the program. Goodbye\n" );
getchar();
return 0;
}
I've been stumped for the past few days trying to modify my current code to be able to input an undetermined number of students.
#include <stdio.h>
int main(void)
{
char StudentName[100];
float ExamValue, Sum, Avg;
int students, exams;
for (students = 0; students < 5; students++)
{
Sum = 0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);
for (exams = 0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum / 3.0;
printf("Average for %s is %f\n", StudentName, Avg);
}
return 0;
}
As it is now, I have to manually input the amount of students. Does anyone know how I can modify this code in order to enter an undetermined amount of students? I'm starting to think that it is impossible to do and maintain the integrity of the rest of the code. Any help is greatly appreciated, thanks!
You can do something like while (stillAdding) instead of the for loop, and prompt the user with Enter student name or QUIT to stop, or even Would you like to enter a new student [Y/n]. You'd modify the stillAdding variable accordingly. In short, you leave it up to the user to specify when they want to stop inputting more data.
You can ask for the number of users before the for and then use that number as upper bounds of the for. Something like this:
int students, exams, nr;
printf("Enter Student Number \n");
scanf("%d", &nr);
for (students = 0; students < nr; students++)
{
//your code
}
You can ask the user whether there are more students per loop:
#include <stdio.h>
int main(void)
{
char StudentName[100];
float ExamValue, Sum, Avg;
int students, exams;
char stop;
for (;;)
{
Sum = 0.0;
printf("Enter Student Name \n");
scanf(" %s", StudentName);
for (exams = 0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum / 3.0;
printf("Average for %s is %f\n", StudentName, Avg);
puts("More students?(Y/N)");
scanf("%*[^yYnN]%c%*[^\n]%*c", &stop); // read one of 'y', 'Y', 'n', 'N', then discard that line, including '\n'.
if (stop == 'N' || stop == 'n')
break;
}
return 0;
}
You can prompt the user to supply the number of inputs. Once the user tells you how many inputs will be given, then you can simply use a for loop to read that many inputs