LearnFrenzy
Sign in Take a free test

Structures, Unions, Enums · Structure Programs · Question 1

Student records: find the topper using structures in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Store student records in an array of structures and print the student with the highest CGPA.

Solution
main.c
#include <stdio.h>

struct student {
    char name[20];
    int roll;
    double cgpa;
};

const struct student *topper(const struct student *s, int n) {
    const struct student *best = &s[0];
    for (int i = 1; i < n; i++)
        if (s[i].cgpa > best->cgpa)
            best = &s[i];
    return best;
}

int main(void) {
    struct student cls[] = {{"Asha", 1, 8.7}, {"Ravi", 2, 9.4}, {"Meera", 3, 9.1}};
    const struct student *t = topper(cls, 3);
    printf("Topper: %s (roll %d), CGPA %.1f\n", t->name, t->roll, t->cgpa);
    return 0;
}

Output Verified by compiling and running

Topper: Ravi (roll 2), CGPA 9.4

Returning a pointer to the best record avoids copying the struct. const shows the function only reads the array.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links