Search code examples
cstructureuser-defined-functions

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); 
}

Solution

  • 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)