C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Structures in C

Nested structures (employee with address)

C Program: Nested structures (employee with address)

C

#include <stdio.h>

 

// Structure for Address

struct Address {

    char city[50];

    char state[50];

    int pincode;

};

 

// Structure for Employee containing Address

struct Employee {

    int id;

    char name[50];

    float salary;

    struct Address addr;  // Nested structure

};

 

int main() {

    struct Employee e;

 

    // Input employee details

    printf("Enter Employee ID: ");

    scanf("%d", &e.id);

 

    printf("Enter Employee Name: ");

    scanf(" %[^\n]", e.name); // reads name with spaces

 

    printf("Enter Employee Salary: ");

    scanf("%f", &e.salary);

 

    printf("Enter City: ");

    scanf(" %[^\n]", e.addr.city);

 

    printf("Enter State: ");

    scanf(" %[^\n]", e.addr.state);

 

    printf("Enter Pincode: ");

    scanf("%d", &e.addr.pincode);

 

    // Display employee details

    printf("\n--- Employee Details ---\n");

    printf("ID       : %d\n", e.id);

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

    printf("Salary   : %.2f\n", e.salary);

    printf("City     : %s\n", e.addr.city);

    printf("State    : %s\n", e.addr.state);

    printf("Pincode  : %d\n", e.addr.pincode);

 

    return 0;

}

Output

 
OUTPUT :
Enter Employee ID: 101
Enter Employee Name: Ramesh Kumar
Enter Employee Salary: 45000
Enter City: Delhi
Enter State: Delhi
Enter Pincode: 110001

--- Employee Details ---
ID       : 101
Name     : Ramesh Kumar
Salary   : 45000.00
City     : Delhi
State    : Delhi
Pincode  : 110001

Explanation

Concept

Description

struct Address

Defines an address with city, state, and pincode.

struct Employee

Contains employee info and an Address structure.

struct Address addr;

Nested structure used inside Employee.

Dot notation

Access nested members as e.addr.city, e.addr.state, etc.