C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Structures in C

Array of Nested Structures (Multiple Employees with Address)

C Program: Array of Nested Structures (Multiple Employees with Address)

C

#include <stdio.h>

 

#define MAX 3   // Number of employees

 

// 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[MAX];

    int i;

 

    printf("Enter details for %d employees:\n", MAX);

   

    for (i = 0; i < MAX; i++) {

        printf("\n--- Employee %d ---\n", i + 1);

        printf("Enter ID: ");

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

       

        printf("Enter Name: ");

        scanf(" %[^\n]", e[i].name);

       

        printf("Enter Salary: ");

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

       

        printf("Enter City: ");

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

       

        printf("Enter State: ");

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

       

        printf("Enter Pincode: ");

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

    }

 

    // Display Employee Details

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

    for (i = 0; i < MAX; i++) {

        printf("\nEmployee %d:\n", i + 1);

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

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

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

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

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

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

    }

 

    return 0;

}

Output

 
OUTPUT :
Enter details for 3 employees:

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

--- Employee 2 ---
Enter ID: 102
Enter Name: Sita Verma
Enter Salary: 50000
Enter City: Mumbai
Enter State: Maharashtra
Enter Pincode: 400001

--- Employee 3 ---
Enter ID: 103
Enter Name: Rajesh Singh
Enter Salary: 47000
Enter City: Jaipur
Enter State: Rajasthan
Enter Pincode: 302001


--- Employee Details ---

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

Employee 2:
ID       : 102
Name     : Sita Verma
Salary   : 50000.00
City     : Mumbai
State    : Maharashtra
Pincode  : 400001

Employee 3:
ID       : 103
Name     : Rajesh Singh
Salary   : 47000.00
City     : Jaipur
State    : Rajasthan
Pincode  : 302001


Explanation

Concept

Description

#define MAX 3

Defines how many employees to input (can change easily).

struct Employee e[MAX]

Array of structures, each with nested address.

Nested access

Example: e[i].addr.city accesses the city of employee i.

Loops

Used for both input and output.