how we can strore a nested structure values in arrays

#include <stdio.h>

#define MAX_LEN 50

struct Address {
    char city[MAX_LEN];
    char street[MAX_LEN];
    int zipcode;
};

struct Person {
    char name[MAX_LEN];
    int age;
    struct Address address;
};

int main() {
    struct Person people[3];

    // Storing values in the nested structure within arrays
    for (int i = 0; i < 3; i++) {
        printf("Enter details for person %d:\n", i + 1);

        printf("Name: ");
        scanf("%s", people[i].name);

        printf("Age: ");
        scanf("%d", &people[i].age);

        printf("City: ");
        scanf("%s", people[i].address.city);

        printf("Street: ");
        scanf("%s", people[i].address.street);

        printf("Zipcode: ");
        scanf("%d", &people[i].address.zipcode);

        printf("\n");
    }

    // Displaying the stored values
    printf("Details of people:\n");
    for (int i = 0; i < 3; i++) {
        printf("Person %d:\n", i + 1);
        printf("Name: %s\n", people[i].name);
        printf("Age: %d\n", people[i].age);
        printf("Address: %s, %s, %d\n", people[i].address.street, people[i].address.city, people[i].address.zipcode);
        printf("\n");
    }

    return 0;
}

Explanation:

  • struct Address: Defines a structure named Address containing three members: city, street, and zipcode.
  • struct Person: Defines a structure named Person containing members name, age, and a nested address of type Address.
  • main(): Entry point of the program.
  • struct Person people[3];: Declares an array people of type Person with a size of 3 to store details of three persons.
  • for loop (1st): Loops through each person to input their details using scanf.
  • printf statements within the loop prompt the user to input details for each person.
  • scanf is used to read user input for name, age, city, street, and zipcode for each person and store them in the respective fields of the people array.
  • Second for loop: Displays the stored details of each person using printf.
  • The program prompts the user for details of three persons, stores them in the array of structures, and then displays the stored information for each person.