LearnFrenzy
Sign in Take a free test

Declarations and Initializations · Declaration Programs · Question 1

Student record with designated initializers in C Solution, output & explanation

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

Declare a student record with designated initializers (leaving one member out) and print it with the average of the marks.

Solution
main.c
#include <stdio.h>

struct student {
    const char *name;
    int roll;
    double cgpa;
    int marks[3];
};

int main(void) {
    struct student s = {.name = "Asha", .marks = {88, 92, 79}, .roll = 12};   /* cgpa not given: 0.0 */
    double avg = (s.marks[0] + s.marks[1] + s.marks[2]) / 3.0;
    printf("%s (roll %d): cgpa %.1f, average %.2f\n", s.name, s.roll, s.cgpa, avg);
    return 0;
}

Output Verified by compiling and running

Asha (roll 12): cgpa 0.0, average 86.33

Designated initializers can name members in any order, even nested arrays. Members left out start at zero, which makes the default explicit and safe.

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