Alright so I've having trouble on the next step of my c program. Basically, it is a database that accepts user input and then uses a switch-statement to retrieve or calculate the individual or group statistics. Note that:
A student whose EUID (roll number) is stored in location i of the EUID array will have his or her homework average, exam 1 grade, and exam 2 grade stored in location i of the appropriate arrays.
So far the code is able to run but I'm stumped when it comes to the switch statement.
I only really need advice on the first case of the switch statement but included the rest just in case.
In short for case 1, how can I get the program to print out a student's grades and average using a specific EUID. The output should look something like this:
1
Please enter student EUID:
1893839
EUID: 1893839 Homework: 84.34 Exam 1: 84 Exam 2: 76
Here's what I have so far:
#include <stdio.h>
#include <math.h>
struct Grade
{
int euid;
double hwavg;
double exam1;
double exam2;
};
int main()
{
struct Grade record[200];
int input, i;
printf("Input each student's EUID, homework average, exam 1 grade, and exam 2 grade: \n\n");
printf("To terminate input '-1' as the student EUID, along with throwaway values for the average and grades.");
for(i=0; i<200; ++i)
{
scanf("%d %lf %lf %lf", &record[i].euid, &record[i].hwavg, &record[i].exam1, &record[i].exam2);
if(record[i].euid == -1)
{
break;
}
}
while(1)
{
printf("Select one of the following:\n 1. Student grade data \n 2. Student grade average \n 3. Class average for assignment \n 4. Exit\n");
scanf("%d\n",&input);
switch(input)
{
case 1:
printf("Enter the student's EUID:\n");
/*The output here should be the EUID, homework avgerage, exam 1 grade and exam 2 grade. */
break;
case 2:
printf("Enter the student's EUID:\n");
/*Finds and prints the the students average and letter grade. */
/* (HW * 0.5) + (EXAM1 * 0.25) + (EXAM2 * 0.25) */
break;
case 3:
/* Finds total class average. */
break:
case 4:
printf("Terminating program: Bye-bye!\n");
return 0;
break;
default:
printf("Error! Invalid input.\n\n");
}
}
}
Basically, it seems what you're looking for is something along the line...
printf("EUID:%d Homework: %.2f Exam 1:%.0f Exam2: %.0f\n", record[i].euid, record[i].hwavg, record[i].exam1, record[1].exam2);
Note: The %.0f makes an output of 0 decimals.
In order to calculate the average, this can be done in your first for-loop, which reads and fills in the array.
You may want to search the net for "printf double"; here's an example reference.
-What I almost never see mentioned is that you can choose argument numbers using %2$f (where 2 denotes argument number 2).
To find the index of the EUID, you could use something like this:
i = 0;
while(record[i].euid != -1 && record[i].euid != euid)
{
i++;
}
-You'll of course need to scanf to get the euid.
Related
I am trying to make a loop where I enter 30 or less student's GPA and get: the average gpa, highest and lowest gpa, adjusted average, see if a specific gpa was entered and display the contents of the array. But when I run the code I have, I can only enter one gpa...
#include <stdio.h>
#include <stdlib.h>
#define GPA_COUNT 30
main(){
int gpa [GPA_COUNT];
int total = 0, i;
double average;
for(i = 0; i < GPA_COUNT; i++){
printf("Enter student %i's GPA: \n", i + 1);
scanf("%i", &gpa[i]);
}
for(i = 0; i < GPA_COUNT; i++){
total += gpa[i];
if(gpa[i] > 2.0){
printf("You need to study harder! \n");
}
else if(gpa[i] < 3.5){
printf("Nice work! \n");
}
}
average = (double)total / GPA_COUNT;
printf("The average GPA is: %.2lf \n", average);
system("pause");
}
I would like to be able to enter the rest of the gpa's.
As Antii Haapala says in his comment, your problem is that you've initialized gpa as an integer, and are using printf to scan in an integer -- but are actually entering a double.
To fix it, you simply need to expect a double instead:
double gpa [GPA_COUNT];
// -- snip --
scanf("%lf", &gpa[i]);
I'm assuming you're a student, so here are a couple of other notes to help you improve your code:
Take a look at your conditional when checking the student's GPA (what happens if a student scores a 1.0? A 4.0?)
You can remove the \n from this line (printf("Enter student %i's GPA: \n" i + 1);) to have the inputs on the same line.
Consider what will happen if someone throws garbage input at your program -- sanitizing user inputs is important! A safer, but still simple, method would be to read the user input as a string, and then attempt to convert the input with something like strtod.
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!
First off, how can I implement a #define in this code? I'm fairly lost when it comes to defining and calling of that #define. Also, if there are any ways to make this code look better it would be greatly appreciated! I'm new to coding so any help would be awsome. This is technically homework but I met all the requirements for the assignment so now this is simply exploratory.
#include <stdio.h>
#include <math.h>
int main() {
int studentID;
int count= 0;
char course1[10]={};//issue with storing user input, used an array
char course2[10]={};
float coursecost1;
float coursecost2;
float credithour = 120.25;
float healthID=35.00;
float totalcost;
// Asks for student ID
printf("Enter the Students Id: \n");
scanf("%d",&studentID);
// Enter CRN/Credit hrs for first course
printf("Enter crn/credit hours for the first course: \n");
scanf("%s", &course1);
// Enter CRN/Credit hrs for Second Course
printf("Enter crn/credit hours for the second course: \n");
scanf("%s", &course2);
// Closing statement
printf("\nThank you!\nPRESS ANY KEY TO CONTINUE...\n\n");
// Calculates Cost of Class
int i = course1[5]-'0'; // Bad version of type casting from char to int.
int k = course2[5]-'0'; // Bad version of type casting from char to int.
coursecost1 = i*credithour;
coursecost2 = k*credithour;
totalcost= healthID+coursecost1+coursecost2;
// Printout
printf("\t\tVALENCE COMMUNITY COLLEGE\n\t\tORLANDO FL 10101\n\t\t");
do{
count++;
printf("*");
}while(count<26);
printf("\n\t\tFee Invoice Prepared for Student V%d\n",studentID);
printf("\t\t1 Credit Hour = %.2f\n",credithour);
printf("\t\tCRN\t CREDIT HOURS\n");
printf("\t\t%c%c%c%c\t %c\t\t $
%.2f\n",course1[0],course1[1],course1[2],course1[3],course1[5],coursecost1);
printf("\t\t%c%c%c%c\t %c\t\t $
%.2f\n",course2[0],course2[1],course2[2],course2[3],course2[5],coursecost2);
printf("\t\t\t Health & id fees $ %.2f\n",healthID);
printf("\t\t");
count=0;
do{ //could define a function to clean up code
count++;
printf("-");
}while (count < 39);
printf("\n\t\t\t Total Payments $ %.2f",totalcost);
return 0;
"define" is basically creating a shortcut for stuff you write often in your code, or stuff you want to change often in order to test your code.
An example:
#define fail printf("You did something wrong")
int main (void)
{
int number;
printf("Insert a number between 1 and 3");
scanf("%d", &number);
if (number>3||number<1)
{
fail;
return -1
}
else
{
printf("Insert a number between 4 and 6");
scanf("%d", &number);
if (number<4||number>6)
{
fail;
return -1;
}
else return 0;
}
}
When this program is read by the compiler, every "fail" gets substituted by "printf("you did something wrong").
This is the main use of define, and if you are beginning now, that's what I'd consider important.
About your code, when you do scanf for strings, don't use "&", or use the "gets" function. I could try to explain why to you, but I'm not the best person for this job. My tip is, keep studying and when you start seeing pointers, you'll understand better why this happens.
Also, when you use arrays without a starting value, you don't need to do the "={ }" thing, just call them without "=".
Now, as you asked, this is how I'd write your code, with the corrections done:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int studentID, intcount = 0; // Count is a function, better not mix things up, that's why I called it "intcount"
char course1[10], course2[10];
float coursecost1, coursecost2, totalcost;
float credithour = 120.25;
float healthID=35.00;
// Asks for student ID
printf("Enter the Students Id: \n");
scanf("%d",&studentID);
// Enter CRN/Credit hrs for first course
printf("Enter crn/credit hours for the first course: \n");
scanf("%s", course1);
// Enter CRN/Credit hrs for Second Course
printf("Enter crn/credit hours for the second course: \n");
scanf("%s", course2);
// Closing statement
// printf("\nThank you!\nPRESS ANY KEY TO CONTINUE...\n\n");
/* Decided not to delete this one, so you can
compare this printf with the new one and the system pause */
printf("\nThank you!\n");
system("pause");
// Calculates Cost of Class
// I'm not sure what you were trying to do in these lines, so I won't touch them
int i = course1[5]-'0';
int k = course2[5]-'0';
coursecost1 = i*credithour;
coursecost2 = k*credithour;
totalcost= healthID+coursecost1+coursecost2;
// Printout
printf("\t\tVALENCE COMMUNITY COLLEGE\n\t\tORLANDO FL 10101\n\t\t");
do
{
intcount++;
printf("*");
}
while(intcount<26);
printf("\n\t\tFee Invoice Prepared for Student V%d\n",studentID);
printf("\t\t1 Credit Hour = %.2f\n",credithour);
printf("\t\tCRN\t CREDIT HOURS\n");
printf("\t\t%c%c%c%c\t %c\t\t $%.2f\n",course1[0],course1[1],course1[2],course1[3],course1[5],coursecost1);
printf("\t\t%c%c%c%c\t %c\t\t $%.2f\n",course2[0],course2[1],course2[2],course2[3],course2[5],coursecost2);
printf("\t\t\t Health & id fees $ %.2f\n",healthID);
printf("\t\t");
intcount=0;
do
{ //could define a function to clean up code
intcount++;
printf("-");
}
while (intcount < 39);
printf("\n\t\t\t Total Payments $ %.2f",totalcost);
}
Basically just try to avoid placing too much information on the same line, even split single printfs into multiple ones if neccessary.
Hope I could be of some use!
int main(){
char students_number[30], students_grade[30];
char *number, *value;
int flag=0, students, i, grade, a=0, b=0, c=0, d=0, f=0;
float sum=0;
while(flag==0) // This while loop exist just because to run program until the number of students will be given correct..
{
printf("Please enter the number of students (It must be between 1-100): ");
scanf("%s",&students_number); // This scanf gets the number of students as an array instead of integer because the number which was given needs to be checked..
students = strtol(students_number, &number, 10); // strtol is a function of stdlib.h and checks the variable is whether int or not for this program..
if(students<=100 && students>0)
{
for(i=1;i<=students;i++)
{
printf("Please enter %d. student's grade (in integer form):",i);
scanf("%s",&students_grade);// This scanf gets the number of students as an array instead of integer because the number which was given needs to be checked..
grade = strtol(students_grade, &value, 10); // This line checks the grade which was given is integer or not by using strtol which is in the stdlib.h..
if(grade<0 || grade>100 || grade=='\0')
{
printf("The grade of the student was given incorrect!\n");
i--; // To make the for loop which is on the 25th line work again until the grade will be given correct..
}
else
{
if(grade<=50 && grade>=0) // This if and else if commands work for to count how many f,d,c,b and a are exist..
f++;
else if(grade<=60 && grade>=51)
d++;
else if(grade<=73 && grade>=61)
c++;
else if(grade<=85 && grade>=74)
b++;
else if(grade<=100 && grade>=86)
a++;
sum += grade;
}
}
sum /= students; // This command divides the sum of the grades to number of the students to get the average results in the class..
printf("\nThe average result of the class is %.2f..\n",sum);
printf("\nThe letter form of the all results are:\nNumber of F: %d\nNumber of D: %d\nNumber of C: %d\nNumber of B: %d\nNumber of A: %d\n",f,d,c,b,a);
flag = 1; // As it was mentioned before, this commands exist to break the while loop because the program was done successfully..
}
else // This if command controls the number of students wheter was given right or not..
{
printf("Please enter a proper number of students.\n");
flag = 0;
}
}
return 0;
}
Hello, this is my first question. I had to create a program which calculates the average of the results. But when i enter 0(zero) as a grade then it doesn't allow it just because i tried to exclude the every types except int type.
How can i make this correct?
You can use scanf to read a number and check that scanf done correctly its work:
from man scanf:
Return Value
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
So you can check that you've read an integer with scanf, without writing if (value == '\0'), which prevents you to read 0 grades...
for(i=1;i<=students;i++)
{
int ok;
printf("Please enter %d. student's grade (in integer form):",i);
/* read line from input. Why using fgets instead of scanf directly? See http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html*/
if (NULL == fgets(students_grade, sizeof students_grade, stdin))
{
perror("fgets");
exit(1);
}
/* **try** to parse what have been read */
ok = sscanf(students_grade, "%d", &value);
/* check that scanf has done its work */
if (1 != ok)
{
printf("The grade of the student was given incorrect!\n");
i--; // To make the for loop which is on the 25th line work again until the grade will be given correct..
}
else
{
if(grade<=50 && grade>=0) // This if and else if commands work for to count how many f,d,c,b and a are exist..
f++;
/* ... */
}
I also advice you to read this article: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html.
The question
A maths teacher asks her students to give 3 examples for positive odd numbers. When the student specifies a correct answer, his/her score is incremented by 1. When the student specifies a positive even number, his/her score is decremented by 0.5. When the student specifies a negative number, he/she will not be given any more chances to correct his or her mistake and his/her score will be decremented by 1. So a student's turn comes to an end when he/she has correctly specified 3 positive odd numbers or when the student has specified a negative number.
Few students didn't know the difference between odd numbers and even numbers and they made many mistakes and so it was difficult for the teacher to maintain the scores. The teacher asks for your help.
Can you please help her by writing a program to calculate the score?
Sample Input 1:
1
3
5
Sample Output 1:
3.0
Sample Input 2:
1
2
5
6
7
Sample Output 2:
2.0
Sample Input 3:
2
-4
Sample Output 3:
-1.5
Sample Input 4:
3
3
3
Sample Output 4:
3.0
Problem:
here i am not getting how to input multiple variables through single scanf
here is my code
#include<stdio.h>
int main()
{
int a,i;
float b=0;
for(i=1;i<=3;i++)
{
scanf("%d",&a);
do
{
if(a%2==0)
{
b=b-0.5;
}
if(a<0)
{
b--;
}
else if(a%2!=0)
{
b++;
}
printf("%.1f",b);
}
while(a%2!=0);
break;
}
return 0;
}
Look, the following for loop will just iterate only 3 times:
for(i=1;i<=3;i++)
whereas you input can be more than 3 times (see Sample Input 2)!
There are some syntactical issues besides some logical error in your code.
Instead of float b=0; use float b = 0.0;
Note that, if the input is negative even number then the following code will reduce b by 0.5
if(a%2==0)
{
b=b-0.5;
}
Where the immediate if condition will again reduce b by 1.
if(a<0)
{
b--;
}
that will make your result more reduced by 0.5, which is not correct.
As per your problem definition, the Sample Input is variable so that you have to implement your loop as well. Try something like this:
int input, correctResultCount = 0;
float result = 0.0;
while (true) {
scanf("%d", &input);
if (input < 0) {
result--;
break;
}
if (input % 2 == 0) {
result = result - 0.5;
}
if (input % 2 != 0) {
result++;
correctResultCount++;
}
if (correctResultCount == 3)
break;
}
printf("%.1f", result);
Run Live.
**NOTE**
THIS LINE IS IMPORTANT
"A Student's turn comes to an end when he/she has correctly specified 3 positive odd numbers or when the student has specified a negative number"
i.e HE CAN GIVE ANY NUMBER OF EVEN NUMBERS (2,4,6,8,10...) BUT THIS WILL HALT ONLY WHEN A TOTAL OF 3 ODD NUMBERS ARE GIVEN OR A SINGLE NEGATIVE NUMBER.
#include <iostream>
using namespace std;
int main()
{
int num;
float marks=0.0 ;
for(int i=0;i<3;)
{
cin>>num;
if(num<0)
{
marks=marks-1;
break;
}
else if(num%2==0)
{
marks=marks-0.5;
}
else{
marks=marks+1;
i++;
}
}
cout<<"Final MArks Are :"<<marks<<endl;
}
SAMPLE INPUT & OUTPUT 1:
1 3 5 ->3.0
SAMPLE INPUT & OUTPUT 2:
1 2 5 6 7 -> 2.0