Structures and Unions

 Structures and Unions


Structures and unions are used to create user-defined data types that can hold different types of data. Structures group related data together, while unions allow multiple variables to share the same memory location.



#include <stdio.h>


struct Person {

    char name[50];

    int age;

    float height;

};


union Data {

    int intValue;

    float floatValue;

    char stringValue[20];

};


int main() {

    struct Person person;

    strcpy(person.name, "John");

    person.age = 25;

    person.height = 175.5;


    printf("Name: %s\n", person.name);

    printf("Age: %d\n", person.age);

    printf("Height: %.2f\n", person.height);


    union Data data;

    data.intValue = 10;

    printf("Integer Value: %d\n", data.intValue);


    data.floatValue = 3.14;

    printf("Float Value: %.2f\n", data.floatValue);


    strcpy(data.stringValue, "Hello");

    printf("String Value: %s\n", data.stringValue);


    return 0;

}

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...