Sunday, March 31, 2019

Nested Structure in C

C programming provides important feature called nesting of Structure. A structure can be nested inside another structure. This feature is useful to maintain complex data structure. Following example explains how a Person structure is used in a Student structure.

Nesting of Structure in C

#include<stdio.h>

//Declaring a structure student
struct student
{
    struct person
    {
        char firstname[20];
        char lastname[20];
        char dob[10];
    } p ;

    int rollno;
    float marks;
};

int main()
{
    struct student s1;

    printf("*** READING STUDENT'S DETAILS *** \n\n");

    printf("Enter firstname: ");
    scanf("%s", s1.p.firstname);

    printf("Enter lastname: ");
    scanf("%s", s1.p.lastname);

    printf("Enter DoB(dd-mm-yyyy): ");
    scanf("%s", s1.p.dob);

    printf("Enter roll no: ");
    scanf("%d", &s1.rollno);

    printf("Enter marks: ");
    scanf("%f", &s1.marks);

    printf("\n*** PRINTING DETAILS OF STUDENT FROM STRUCTURE ***\n\n");

    printf("Name: %s %s\n", s1.p.firstname, s1.p.lastname);
    printf("DOB: %s\n", s1.p.dob);
    printf("Roll no: %d\n", s1.rollno);
    printf("Marks: %.2f\n", s1.marks);

    return 0;
}

Output of Program

*** READING STUDENT'S DETAILS ***

Enter firstname: Purv
Enter lastname: Patel
Enter DoB(dd-mm-yyyy): 10-12-2008
Enter roll no: 101
Enter marks: 85

*** PRINTING DETAILS OF STUDENT FROM STRUCTURE ***

Name: Purv Patel
DOB: 10-12-2008
Roll no: 101
Marks: 85.00


* * * * *

Recommended Readings: C Structure



No comments:

Post a Comment