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 namedAddress
containing three members:city
,street
, andzipcode
.struct Person
: Defines a structure namedPerson
containing membersname
,age
, and a nestedaddress
of typeAddress
.main()
: Entry point of the program.struct Person people[3];
: Declares an arraypeople
of typePerson
with a size of 3 to store details of three persons.for
loop (1st): Loops through each person to input their details usingscanf
.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 thepeople
array.- Second
for
loop: Displays the stored details of each person usingprintf
. - 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.