How to find the maximum value in an array of structures? - c

How to get the max value in a structure? I have tried to create a simple program but I'm having issues with the if statement or variable, since I cannot determine the winner or candidate number which has the highest score.
#include<stdio.h>
#include<conio.h>
struct Candidate{
float Score;
short Number;
}candidate1[5];
main(){
int i,n,highest;
for(i=0;i<5;i++){
printf("Candidate Number: ");
scanf("%i",&candidate1[i].Number);
printf("Score: ");
scanf("%i",&candidate1[i].Score);
highest=candidate1[i].Score;
for (n=0;n<5;n++)
if (candidate1[i].Score>highest);
}
printf("Highest Number: %i\n",highest);
system("pause");
}

fix like this
#include <stdio.h>
#include <stdlib.h>
struct Candidate {
float Score;
short Number;
}candidate1[5];
int main(void){
int i, n, highest = 0;
n = sizeof(candidate1)/sizeof(*candidate1);
for(i=0;i<n;++i){
printf("Candidate Number: ");
scanf("%hi", &candidate1[i].Number);
printf("Score: ");
scanf("%f",&candidate1[i].Score);
if(candidate1[highest].Score < candidate1[i].Score)
highest = i;
}
printf("Highest Number: %f\n", candidate1[highest].Score);
system("pause");
return 0;
}
,

The most common idiom for finding the max of type <T> (double, int, whatever) from an array of structs <S> goes as follows
<S> array[numElements]; //defined and allocated earlier. Has a score `<T> score`
<T> bestScore = array[0].score;
int bestIndex = 0;
int i;
for(i=1;i<numElements;i++) {
if(array[i].score>bestScore) {
bestIndex = i;
bestScore = array[i].score;
}
}
//do things with bestScore and array[bestIndex];
If you have a 2D array you can replace the single for-loop with a double for loop, and use an additional bestIndex variable for the second dimension.
If the array may contain 0 elements it is sometimes common to set bestScore to a minimum possible value and loop from 0 to numElements.

Related

Error: expected expression in C — Can't define a variable as a length of an array

I'm taking CS courses, and wrote a simple program to find an average of the given (input) amount of inputs.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n = get_int("Please enter the number of scores: ");
int scores = [n];
for(int i=0; i<n; i++)
{
int scores[i] = get_int("Please, enter the score: ");
}
printf("Average: %f\n", average(n, scores));
}
float average(int length, int array[])
{
int sum = 0;
for(int i = 0; i < length; i++)
{
sum += sum + array[i];
}
return sum / (float)length;
}
When compiling, "expected expression" error occurs on line 10 (i.e. {int scores = [n];} —
any help or suggestions would be appreciated!!
This is invalid syntax:
int scores = [n];
If you want to define scores as an array of size n you want:
int scores[n];
Also, this doesn't do what you might expect:
int scores[i] = get_int("Please, enter the score: ");
This creates an array called scores of size i, masking the array defined previously, and attempts to initialize it with a single value instead of a list of values. If you want to assign to the existing array you want:
scores[i] = get_int("Please, enter the score: ");

Using structures in C with user defined functions

I had came across a problem that I have tried so many times with different ways but still not able to obtain the required solution please do help me.
PROBLEM: Define a structure to store students’ details. Pass them to a function where the student with HIGHEST CGPA is calculated from a set of 5 students. And display the result.(Here we have to store name, age and CGPA obtained of each student)
Here is my try at the problem:
#include <stdio.h>
void highCGPA(float b,struct detst D[4]);
struct detst
{
int age;
float CGPA;
char name[30];
};
int main()
{
struct detst D[4];
int i;
float h;
for(i=0;i<=4;i++)
{
printf("Enter the name of student %d:\n",i+1);
scanf("%s",&D[i].name);
printf("Enter the age of student %d:\n",i+1);
scanf("%d",&D[i].age);
printf("Enter the CGPA obtined by student %d:\n",i+1);
scanf("%f",&D[i].CGPA);
}
highCGPA(h,D);
}
void highCGPA(float b,struct detst D[4])
{
int i,max;
max = D[0].CGPA;
for(i=0;i<=4;i++)
{
if(D[i].CGPA > max)
{
max = D[i].CGPA;
}
}
printf("Highest CGPA obtained is:\n%f",max);
}
There is more than one problem. You're trying to store the data of 5 students in an array of struct with size 4. So:
struct detst D[5]; // fixed size
int i;
float h;
for(i=0;i<5;i++) { // EDIT (comments suggestion): for loop fix following standard convetions
/* take input */
}
Lastly, if you declare max as an int, you can't try to print it with a format specifier for float. So:
printf("Highest CGPA obtained is: %d\n",max); // format specifier for int is %d (not %f)
There are couple of other problems.
your declaration of funtion highCGPA is above your struct detst definition
you should have got error
error: array type has incomplete element type ‘struct detst’
declare your function after the structure definition.
your max variable is int in the function highCGPA , but you are trying to store a float value in it.
With a sligth change to program functionallity can be improved:
#include <float.h> // FLT_MAX
#include <stdio.h>
struct detst
{
int age;
float CGPA;
char name[30];
};
// Return offset of student with highest CGPA
int highCGPA(struct detst const (*D)[5]); // Using pointer to array
// to avoid degeneration
int main()
{
struct detst D[5];
int i;
for(i = 0; i < 5; i++)
{
printf("Enter the name of student %d:\n", i + 1);
scanf("%29s", D[i].name); // Make sure we don't overwrite the buffer
printf("Enter the age of student %d:\n", i + 1);
scanf("%d", &D[i].age);
printf("Enter the CGPA obtained by student %d:\n", i + 1);
scanf("%f", &D[i].CGPA);
}
int bestStudentOffset = highCGPA(&D); // By asking for best student
// we can obtain a lot more
printf(
"Best student is %d year old %s with\n",
D[bestStudentOffset].age,
D[bestStudentOffset].name);
printf("Highest CGPA obtained is:\n%f\n", D[bestStudentOffset].CGPA);
}
// Return offset of student with highest CGPA
int highCGPA(struct detst const (*D)[5])
{
int i, maxOffset = -1;
float max = -FLT_MAX;
for(i = 0; i < 5; i++)
{
if((*D)[i].CGPA > max)
{
max = (*D)[i].CGPA;
maxOffset = i;
}
}
return maxOffset;
}

Function gives me a wrong answer

I'm new to C. I've been tasked to run a program that calculates the percentage of students that passed an exam,based on N grade inputs.I don't really understand how functions work in though.This is what I came up with
#include <stdio.h>
#define MAX_N 300
main()
{
int N,grade,i;
float success(N)
{
float sum=0.0;
for (i=0;i<N;i++) {
if (grade>=5) {
sum+=1;
}
float success=sum/N;
return(success);
}
}
printf("How many students? ");
scanf("%d",&N);
printf("Enter grades(0-10) of %d students ",N);
for (i=0;i<N;i++){
scanf("%d",&grade);
}
printf("%f percent of students have passed the exam ",success(N);
return(0);
}
It looks like it should work, however I always get the wrong result.It is stuck on displaying 0.2 or 0.25 for any input I give.Can somebody help?
The problem is that in grade only the last entered data is being stored. Make grade as an array so that all data can be stored.
I guess you are taking multiple value for grade and not taking array for it.
grade should be an array and in loop scanf("%d",&grade[i]); should be implement.
grade should be an array of N integers so that each and every value is stored. You also forgot to multiply success by 100 to get the percentage.
I think I fixed the code:
#include <stdio.h>
#define MAX_N 300
float success(int grade[],int N)
{int i;
float sum=0.0;
for (i=0;i<N;i++) {
if (grade[i]>=5) {
sum+=1;
}
}
float success=sum/N;
return(success*100);
}
int main(){
int N, i;
printf("How many students? ");
scanf("%d",&N);
int grade[N];
printf("Enter grades(0-10) of %d students ",N);
for(i=0;i<N;i++){
scanf("%d", &grade[i]);
}
printf("%f percent of students have passed the exam ", success(grade, N));
return(0);
}
I think you should examine the code I wrote. A little bad code. But it can help.
#include <stdio.h>
int students_success(int *);
int main() {
int n;
printf("How many students?\n");
scanf("%d", &n);
printf("Enter grades(0-10) of %d students\n", n);
int grade;
int pass_std = 0;
for(int i = 0; i < n; ++i) {
scanf("%d", &grade);
pass_std = students_success(&grade);
}
printf("%.2f percent of students have passed exam.\n", (double)pass_std / n);
}
int students_success(int *grade) {
static int pass_std = 0;
if(4 < *grade) {
++pass_std;
}
return pass_std;
}

confusion comparing structures

the question is to calculate the average of each student separately and then show the id and the average of rank one student. how to compare members of structure
#include<stdio.h>
typedef struct student
{
int id;
float math,physics;
float av;
}std;
int main()
{
int i;
std p[5];
for(i=0;i<5;i++)
{
printf("enter student(%d) id: ",i+1);
scanf("%d",&p[i].id);
printf("grade of math over 100: ");
scanf("%f",&p[i].math);
printf("grade of physics over 100: ");
scanf("%f",&p[i].physics);
printf("average=%.3f\n\n",(p[i].math+p[i].physics)/2);
}
}
To compare on element with another you would take either
p[index]->av {comparaision} p[index]->av
Example p[0]->av > p[1]->av
Don't forget printf("average=%.3f\n\n",(p[i].math+p[i].physics)/2); will print you the result of av but will not save it in p. Save it in p[index].av to be able to do comparaisons.
Then afterward just do a loop where you compare each of them and save their id in an array. The array should be based on a decreasing average with the matching id. Then just print the array and you will be good to go.
#include<stdio.h>
typedef struct studentd
{ int id;
float math,physics;
float av;
} std;
int main()
{
int i,a;
std p[5];
for(i=0; i<5; i++)
{
printf("student(%d) id: ",i+1);
scanf("%d",&p[i].id);
printf("grade of math over 100: ");
scanf("%f",&p[i].math);
printf("grade of physics over 100: ");
scanf("%f",&p[i].physics);
printf("average=%.3f\n\n",p[i].av=(p[i].math+p[i].physics)/2);
}
int max=p[0].av;
for(i=0; i<5; i++)
{
if(p[i].av<=p[i+1].av)
{
max=p[i].av;
}
}
printf("the highest average is for student: %d ",p[i].id);
return 0;
}
/*END*/
/now this is the updated code my problem is how to link the id of student to the max to show the id of student whi got the highest mark/
Well one of two things,
Either add an integer to track the index of the structure containing the max,
Or instead of
max =p[i].avg
Use max = p[i]
Of course let max be a struct not float or int

Calculating Size of the Array

I'm trying to calculate the size of the file . The process I've followed is to read the file and store it in an array and calculate its size. However,I really don't know ... I tried n number of ways..I've to pass this size as an attribute to the frequency function.along with the name of the array.
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int ??????, int x)
{
int count = 0;
int u;
for (u = 0; u < ??????; u++)
{
if ( theArray[u]==x)
{
count = count + 1 ;
/*printf("\n%d",theArray[u]);*/
}
else
{
count = count ;
}
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int r = 0;
int num;
int theArray[100];
int there[100];
int n;
int g;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",(integers[i]));
there[r] = integers[i];
i++;
}
//printf("%d",there[r]);
//printf("\n%d",file);
//fclose(file);
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf("\n%d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,????????,x);
getch();
fclose(file);
}
?????? is the size of the integer array from where i read the file and stored it.
I could not find a way to calculate the size of the array into which i copied my file. My idea is to calculate the frequency of a number in that file and calculate the probability of it's occurrence and thereby calculating entropy..Suggestions please!
I don't know why you are initializing so many variables and some of them with awkward names like ??????.
Your main problem is that the call to function should be
frequency(integers, i, x);
Your code with the awkward irrelevant parts removed will look like
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int number, int x)
{
int count = 0;
int u;
for (u = 0; u < number; u++)
{
if ( theArray[u]==x)
count++;
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int num;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",integers[i]);
i++;
}
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf(" %d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,i,x);
getch();
fclose(file);
}
There are a lot of parts of this code that don't make sense, but I assume it is your debugging trying to figure out what is wrong. The answer to your specific question is:
For each value read from the file you set integers[i] to the value and then increment i. Thus i is the count of items in integers. You then pass integers to frequency(), so i should be passed to the second parameter as the count.
Note that if there are more than 100 values in the file, you will over index integers and cause unpredictable behavior.
To calculate length of array:
int len= sizeof(arr)/sizeof(arr[0]);
It will give length of array without looping.

Resources