Finding average for 2 students - c

I am running a program to calculate average for 2 students. I am having trouble running this. For some reason it says it cannot be found. It's my first time using Visual Studio and I am not sure if my code is the problem or the program.
Please check if there's a mistake and let me know.
#include <stdio.h>
int main(void)
{
int firstGrade1;
int sGrade1;
int tGrade1;
int fGrade1;
int TotalGrade1 = (firstGrade1 + sGrade1 + tGrade1 + fGrade1);
int AveGrade1 = (TotalGrade1 / 4);
printf("Please enter Student 1 first grade:\n");
scanf("%d", &firstGrade1);
printf("Please enter Student 1 second grade:\n");
scanf("%d", &sGrade1);
printf("Please enter Student 1 third grade:\n");
scanf("%d", &tGrade1);
printf("Please enter Student 1 fourth grade:\n");
scanf("%d", &fGrade1);
int firstGrade2;
int sGrade2;
int tGrade2;
int fGrade2;
int TotalGrade2 = (firstGrade2 + sGrade2 + tGrade2 + fGrade2);
int AveGrade2 = (TotalGrade2 / 4);
printf("Please enter Student 2 first grade:\n");
scanf("%d", &firstGrade2);
printf("Please enter Student 2 second grade:\n");
scanf("%d", &sGrade2);
printf("Please enter Student 2 third grade:\n");
scanf("%d", &tGrade2);
printf("Please enter Student 2 fourth grade:\n");
scanf("%d", &fGrade2);
printf("1. Student 1 grades:");
printf("%d", firstGrade1, sGrade1, tGrade1, fGrade1);
printf(". Average is ");
printf("%d\n", AveGrade1);
printf("2. Student 2 grades:");
printf("%d", firstGrade2, sGrade2, tGrade2, fGrade2);
printf(". Average is ");
printf("%d", AveGrade2);
system("pause");
return (0);
}

This here
int TotalGrade1 = (firstGrade1 + sGrade1 + tGrade1 + fGrade1);
Doesn't tell it that TotalGrade1 will just always be the value of those 4 variables added up. It assigns to TotalGrade1 the sum of those variables' current values. Since those are uninitialized, that's undefined behavior. Move the calculation of TotalGrade1 and AveGrade1 to after you read in those values, and likewise for TotalGrade2 and AveGrade2, of course.
Also, consider this print:
printf("%d", firstGrade1, sGrade1, tGrade1, fGrade1);
You are printing four int, why is there only one format specifier? The format string should be "%d %d %d %d".
I suggest always paying attention to your compiler's warnings. Usually your compiler should warn you about incorrect printf format strings as well as using uninitialized variables.
On a side note, you have a lot of code duplication. What if you didn't have two students and four grades, but a hundred students with ten grades each? Imagine the amount of code, and the amount of work copy/pasting the code. Instead, try something like this:
int main(void)
{
int Grade[2][4];
int AveGrade[2];
int TotalGrade[2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
printf("Please enter Student %d j. grade:\n", i + 1, j+1);
scanf("%d", &Grade[i][j]);
}
TotalGrade[i] = 0;
for (int j = 0; j < 4; j++)
TotalGrade[i] += Grade[i][j];
AveGrade[i] = (TotalGrade[i] / 4);
}
for (int i = 0; i < 2; i++) {
printf("%d. Student %d grades:", i+1, i+1);
for (int j = 0; j < 4; j++)
printf("%d ", Grade[i][j]);
printf(". Average is ");
printf("%d\n", AveGrade[i]);
}
system("pause");
return (0);
}

Related

Displayed number deleted in array is not correct

I have this program where it lets the user input an array of numbers.
For example, I would input an array size of 4 and input the numbers 40, 20, 1, and 8 as the elements in the array.
Input array size: 4
Input array elements: 40 20 1 8
The program also lets the user delete any elements from the array and the output should also show the element that was deleted.
For example, I would delete the number 40 from the elements. The output should be like this:
Enter the position of the element that you would like to delete: 1
The element 40 is completely deleted!
But instead of showing 40, the output goes like this:
Enter the position of the element that you would like to delete: 1
The element 20 is completely deleted!
Here is my source code:
int a[100];
int arraySize, elementPosition;
printf("\n Input Array Size: ");
scanf("%d", &arraySize);
printf("\n Input Array Elements: ");
for(i = 0; i < arraySize; i++)
{
scanf("%d, ", &a[i]);
}
printf("\n Enter the position of the element you would like to delete: ");
scanf("%d", &elementPosition);
int deletedElement = a[elementPosition];
if (elementPosition >= arraySize + 1)
{
printf("\n \n \t Invalid position! Enter numbers from 1 to %d only.\n", arraySize);
getch();
del();
}
else
{
for (i = elementPosition; i < arraySize - 1; i++)
{
a[i] = a[i+1];
}
printf("\n \The element %d is completely deleted!", deletedElement);
arraySize = arraySize - 1;
getch();
}
It would be a very big help if someone can point out where did I go wrong.
Array index starts from 0. This deletedElement = a[elementPosition]; should be changed to deletedElement = a[elementPosition - 1];.
Additionally, you need to make sure that subtracting 1 does not cause deletedElement to become less than 0.
Could you test it, the index begin from 0 the position from 1.
int a[100];
int arraySize, elementPosition;
printf("\n Input Array Size: ");
scanf("%d", &arraySize);
printf("\n Input Array Elements: ");
for(i = 0; i < arraySize; i++)
{
scanf("%d, ", &a[i]);
}
printf("\n Enter the position of the element you would like to delete: ");
scanf("%d", &elementPosition);
int deletedElement = a[elementPosition - 1 ];
if (elementPosition >= arraySize)
{
printf("\n \n \t Invalid position! Enter numbers from 1 to %d only.\n", arraySize);
getch();
del();
}
else
{
for (i = elementPosition - 1; i < arraySize - 2; i++)
{
a[i] = a[i+1];
}
printf("\n \The element %d is completely deleted!", deletedElement);
arraySize = arraySize - 1;
getch();
}

How to find percent from a loop and return a float

I'm stuck on trying to figure out how to take a multiple candidate data from a loop and figure out a winner from them by stating their name, ID, and total percent of votes within the same function. I also need to return the winning candidates ID from the function. For example: candidate 1 - is named Stevens with ID 13.07 and total votes of 1500, candidate 2 - is named George with ID 17.49 and total votes of 2000. I need to output the winner which is George with ID 17.49 and his percent of the total 3500 votes. This is what I have so far but I'm new to programming and have no idea how to figure this out. Any help would be greatly appreciated!
float CandidateData(int N, int X) {
char candName[21];
int i;
double candID;
int candVotes;
int voteSum;
int j = 0;
double max = 0;
double first;
for (i = 0; i < N; i++) { //N is the number of candidates
printf("Enter candidates name (20 characters max): ");
scanf("%s", &candName);
printf("Candidate name: %s\n\n", candName);
printf("Enter candidate ID (float 01.01-52.99): ");
candID = CandidateID(52.99);
printf("Candidate ID is: %g\n\n", candID);
printf("Enter %d precinct votes (int 1-1000): ", X);
voteSum = 0;
for (j = 0; j < X; j++) { //X is number of precincts
candVotes = NumberOfCandidatesAndPrecincts(1000);
printf("Precinct #%d = %d\n", j + 1, candVotes);
voteSum = voteSum + candVotes;
}
printf("Total candidate votes = %d\n", voteSum);
printf("Average votes for county = %d\n\n", voteSum / X);
if (voteSum > max) {
max = voteSum;
}
}
printf("The winning candidate is %s with ID %g with %d% of total votes", candName, candID, )
return (candID);
}
I see few mistakes in your code.
First of all, it should be :
scanf("%s", candName);
not
scanf("%s", &candName);
Because candName is already the address of the first element of the array.
Another issue, suppose a user types Whoever President for candName. Then try this:
printf("Candidate name: %s\n\n", candName);
You will see that only Whoever is printed because scanf("%s",candName) takes input until a white space comes. It can be a blank space (' '), new line (\n) or tab (\t).
Instead, I strongly suggest you to use fgets.
fgets (candName, 21, stdin);
where 21 is the maximum buffer length that you want to have.
Now, you can print candName with printf and observe that fgets puts extra new line ('\n') at the end of your string. You can easily remove it by:
if ((strlen(candName) > 0) && (candName[strlen (candName) - 1] == '\n')){
candName[strlen (candName) - 1] = '\0';}
Keep in mind that using fgets and scanf together is problematic because scanf function leaves \n in the input buffer, after fgets reads input from buffer, you will encounter unexpected results. Use getchar(); after each scanf. It consumes \n. The problem disappears!
The next mistake you made is return_type of CandidateData function. Its return_type is float but type of candID variable is double so make a change for just one of them. In your task, it is sufficient to use float type for candID.
There are also some typos in the last printf function. It should be:
printf("The winning candidate is %s with ID %f with %d of total votes", candName, candID, voteSum);
Let's come to your question. To store the candidate who takes maximum vote, you can declare a struct and fill related fields when number of votes of a candidate exceeds current max value.
I add the final code:
#include <stdio.h>
#include <string.h>
struct President{
char candName[21];
float candID;
int candVotes;
};
float CandidateData(int N, int X) {
struct President winnerCandidate = {.candVotes = 0};
char candName[21];
float candID;
int candVotes;
int voteSum;
int i,j;
for (i = 0; i < N; i++) { //N is the number of candidates
printf("Enter candidates name (20 characters max): ");
fgets (candName, 21, stdin);
if ((strlen(candName) > 0) && (candName[strlen (candName) - 1] == '\n')){
candName[strlen (candName) - 1] = '\0';}
printf("Candidate name: %s\n", candName);
printf("Enter candidate ID (float 01.01-52.99): ");
scanf("%f",&candID);
getchar();
printf("Candidate ID is: %.2f\n", candID);
voteSum = 0;
printf("Enter %d precinct votes (int 1-1000):\n", X);
for (j = 1; j <= X; j++) { //X is number of precincts
scanf("%d",&candVotes);
getchar();
printf("Precinct #%d = %d\n", j , candVotes);
voteSum = voteSum + candVotes;
}
printf("Total candidate votes = %d\n", voteSum);
printf("Average votes for county = %.3f\n\n", voteSum/(float)X);
if(voteSum > winnerCandidate.candVotes){
winnerCandidate.candVotes = voteSum;
winnerCandidate.candID = candID;
strcpy(winnerCandidate.candName,candName);
}
}
printf("The winning candidate is %s with ID %.2f with %d of total votes", winnerCandidate.candName, winnerCandidate.candID, winnerCandidate.candVotes);
return winnerCandidate.candID;
}
int main(){
float winner_candID = CandidateData(3,2);
printf("\nWinner Candidate ID is: %.3f",winner_candID);
return 0;
}
If you have any question, let me know!

Printing the average of combined student marks using C

I've made this program below to calculate the average mark of a student.
Everything works well until I use -1, it is supposed to stop the program as is display the average of all students that have been entered, say Goodbye! and then terminate.
I think my calculations might be wrong though because it is printing the wrong result for the average marks of the students.
Thanks in Advance.
#include <stdio.h>
int main(void)
{
float final_mark(int a_mark1, int a_mark2, int lab_mark, int quiz_mark, int exam_mark);
int i, a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark;
float average_mark = 0.0;
do
{
for (i = 0; i < 2; i++)
{
printf("Enter assignment 1 mark (-1 to quit): ");
scanf("%d", &a_mark1);
if(a_mark1 == -1)
{
average_mark += final_mark(a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark);
if ((average_mark > 1 ) && (average_mark < 100 ))
{
printf("The average student mark is %.2f%% \n", average_mark);
}
printf("Goodbye! \n");
return 0;
}
printf("Enter assignment 2 mark: ");
scanf("%d", &a_mark2);
printf("Enter laboratory mark: ");
scanf("%d", &lab_mark);
printf("Enter quiz mark: ");
scanf("%d", &quiz_mark);
printf("Enter exam mark: ");
scanf("%d", &exam_mark);
printf("Student %d final mark: %.2f \n", i + 1, final_mark(a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark));
}
}
while(a_mark1 != -1);
return 0;
}
float final_mark(int a_mark1, int a_mark2, int lab_mark, int quiz_mark, int exam_mark)
{
float final_mark = a_mark1 * 0.1 + a_mark2 * 0.15 + lab_mark * 0.15 + quiz_mark * 0.1 + exam_mark * 0.5;
return final_mark;
}
I think you need to rethink your logic a little bit. Why not use a while loop to control the flow. Then you can bail out of the program immediately if user inputs -1 right away. You should use an array to store the averages for each student, then you can loop through and find the class average as well.
-Your float final_mark function seems a little sketchy without any parenthesis.
-You should put your function prototype outside of main as well. See below changes.
#include <stdio.h>
#define MAX_STUDENTS 10 //define what the max number of students is
float final_mark(int mark1, int mark2, int lab, int quiz, int exam);
int main()
{
int i = 0, mark1 = 0, mark2 = 0,
lab = 0, quiz = 0, exam = 0;
int num_students;
float students_avg[MAX_STUDENTS] = {0}; //array to hold averages for students
float average = 0;
while (i < MAX_STUDENTS) {
printf("Enter assignment 1 mark (enter -1 to quit):\n");
scanf("%d", &mark1);
if (mark1 == -1)
break; //no more students, break out of while loop
printf("Enter assignment 2 mark: ");
scanf("%d", &mark2);
printf("Enter laboratory mark: ");
scanf("%d", &lab);
printf("Enter quiz mark: ");
scanf("%d", &quiz);
printf("Enter exam mark: ");
scanf("%d", &exam);
average = final_mark(mark1, mark2, lab, quiz, exam);
students_avg[i] = average; //add this average to array
printf("Student # %d average was %.2f\n", i, students_avg[i]);//debug info
i++;
}
num_students = i; //how many students grades did we read?
average = 0; //reset to 0 so we can use below
for (i = 0; i < num_students; i++)
average += students_avg[i];
if (num_students > 0)
printf("Class average is %.2f\n", average/num_students);
else
printf("Goodbye!\n");
return 0;
}
float final_mark(int mark1, int mark2, int lab, int quiz, int exam)
{
//we can just return the calculation
return ((mark1 * 0.1) + (mark2 * 0.15) + (lab * 0.15) + (quiz * 0.1) + (exam * 0.5));
}
Just erase two lines above printf("GOODBYE! \n"); you will get what you want.
maybe you have to initialized mark s variables to 0. and a_mark1 to 0 too if the user enter -1

Fibonacci Series in C Program where FIRST 2 numbers are given by user

When the first number is 1 and second number is 2, and the length is 5, it should be 1 2 3 5 8. But then my output is always 1 2 1 3 4. I can't seem to find the problem.
Another input is 2 and 5. Output is 2 5 1 6 7. The 3rd number which is 1 shouldn't be there. What should I change or add?
*This is already a submitted HW and yes its wrong I got the deductions already. Now I just want to fix this so I can study this.
int main()
{
int i, lenght = 0, fib, sum, sum1, sum2, a, b, c;
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
{
while ((a > b) || ((lenght < 2) || (lenght > 100)))
{
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
}
}
printf("%d\t%d\t", a, b);
printf("%d\t", fib);
for (i = 3; i < lenght; i++) {
if (i <= 1) fib = i;
else {
a = b;
b = fib;
fib = a + b;
}
printf("%d\t", fib);
}
}
The first time you print fib (before the for loop), you haven't assigned it anything yet.
Since this is for study, issues with your code: you don't need to duplicate the calls to scanf(), simply initialize one of the variables to fail (which you did: lenght = 0) and let the loop do its thing; pick one indentation style and stick with it; if you're new to C, always include the curly braces, even when the language says they're optional; you (correctly) allow for a length of 2, but then print three numbers; your if (i <= 1) clause is a no-op as the loop starts with for (i = 3; so i is never less than 3.
Putting it all together, we get something like:
#include <stdio.h>
int main() {
int length = 0, a, b;
while (length < 2 || length > 100 || a > b ) {
printf("\nFirst number: ");
(void) scanf("%d", &a);
printf("\nSecond number: ");
(void) scanf("%d", &b);
printf("\nHow long?: ");
(void) scanf("%d", &length);
}
printf("%d\t%d\t", a, b);
for (int i = 2; i < length; i++) {
int fib = a + b;
printf("%d\t", fib);
a = b;
b = fib;
}
printf("\n");
return 0;
}
Note that the input error checking isn't sufficient to prevent problems. E.g. b can be greater than a, but still mess up the sequence if you input random numbers. You're assuming the user knows to put in two adjacent items from fibonacci sequence which is tricky to test.
just add fib=a+b; before printing fib value.
Its a good coding habit to initialize all variable before using it(especially in C).
Your code seems strange to me. I tried to simplify your code a bit. See this once:
int main()
{
int a,b,next,last,i;
printf("Enter the first Value:");
scanf("%d",&a);
printf("Enter the second Value:");
scanf("%d",&b);
printf("Enter the length of Fab. series:");
scanf("%d",&last);
printf("%d,%d,",a,b);
for (i=3; i<= last; i++)
{
next = a + b;
if(i<last)
printf("%d,",next);
else
printf("%d",next);
a = b;
b = next;
}
return 0;
}
Hope it's Helpful!!

C: Array of Structs (Input into int array within array of structs)

Hi I have to create a database that stores students number, name and also stores an array of course marks (1-N) in C Programming Language.
Everything worked until I started coding for the array of course marks. Then every time I compiled the code it kept crashing as soon as it asked to input the course marks.
Can you please tell me where I'm going wrong in my programming for this task? I have attached it to this message.
The program worked for inputting the name, student number, however I could not get the program to input array of marks. I have asked how many course marks to be entered and then used a for loop within the "void insert(void)" function to keep inputting the course marks into the array *marks. I am referring specifically to lines 24 to 30 in my programming code.
Always at this point the program kept crashing and I could not proceed further to enter more names or print the stored student details.
I think there is a problem with this part:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n");
scanf("%d", &(list[num_students].marks[num_marks]));
}
Anyway here is the full code:
#include <stdio.h>
#include <string.h>
struct student{
int number;
char name[10];
int marks[5];
};
struct student list[10];
int num_students = 0;
int num_marks = 0;
int *p;
void insert(void)
{
int student_number;
int i;
printf("Enter number: \n");
scanf("%d", &list[num_students].number);
printf("Enter NAME: \n");
scanf("%s", &list[num_students].name);
printf("Enter NO of courses: \n");
scanf("%d", num_marks);
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
num_students++; // HOW DO WE INPUT ARRAY MARKS??? MARK1: , MARK2: , MARK3 ,
}
void printtest(void)
{
int i;
for (i=0; i < num_students; i++)
{
printf("Name: \n");
puts(list[i].name);
printf("Number: %d \n", list[i].number);
printf("Mark: %d /100 \n", list[i].marks);
printf("\n");
}
}
int main(void)
{
int code;
int opt1;
int courses, i, k, j, counter;
for (;;){
printf("Enter operation code: \n");
printf("(1) ADD NEW STUDENT DETAILS: \n");
printf("(2) DISPLAY REPORT OF ALL STUDENTS: \n");
scanf(" %d", &code);
switch (code){
case 1 :
insert();
break;
case 2 :
printtest();
break;
default:
printf("Illegal code\n");
printf("\n");
}
}
}
Apart from what others pointed out, I'd like to draw your attention towards the following:
void insert(void)
{
int student_number;
int i;
printf("Enter number: \n");
scanf("%d", &list[num_students].number);
printf("Enter NAME: \n");
scanf("%s", &list[num_students].name);
printf("Enter NO of courses: \n");
scanf("%d", num_marks);
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
num_students++;
}
void printtest(void)
{
int i;
for (i=0; i < num_students; i++)
{
printf("Name: \n");
puts(list[i].name);
printf("Number: %d \n", list[i].number);
printf("Mark: %d /100 \n", list[i].marks);
printf("\n");
}
}
There are three problematic statements:
scanf("%s", &list[num_students].name); This is why beginners should use compilers with all warnings enabled.
printf("Mark: %d /100 \n", list[i].marks); What did you declare marks as in the first place?
scanf("%d", num_marks); Seems like you put & operator where not needed and ignore where needed. Read your textbook before asking a question next time.
Seems like you're having a tough time understanding the concept of arrays and pointers. Read your text book thoroughly before venturing into the world of pointers. If you don't use them correctly, even compiler can't help you.
Also, even if I don't expect your program to have a robust input mechanism, at least array bounds checking is expected. Learn good habits from the beginning. They'll save a lot of your time while debugging later.
Seems to be an error in:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
The crash is probably because num_marks as index indexes beyond the array. Change to:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[i]));
}

Resources