Nested Structures in C
Write a C program using a nested structure to store student information along with address details.
- Two structures are defined: Address for location data and Student which includes Address as a nested structure.
- A Student variable named student is declared to store both personal and address information.
- User input is collected for all fields using scanf, including accessing nested fields like student.address.city.
- All stored data is printed using dot notation for both direct and nested structure members.
Example : pgm.c
#include <stdio.h> // Nested Structure struct Address { char city[50]; char state[50]; int pincode; }; // Outer Structure struct Student { int id; char name[50]; float marks; struct Address address; // Nested structure }; int main() { struct Student student; // Input student data printf("Enter student ID: "); scanf("%d", &student.id); printf("Enter student name: "); scanf(" %[^\n]", student.name); printf("Enter student marks: "); scanf("%f", &student.marks); printf("Enter city: "); scanf(" %[^\n]", student.address.city); printf("Enter state: "); scanf(" %[^\n]", student.address.state); printf("Enter pincode: "); scanf("%d", &student.address.pincode); // Output student data printf("\nStudent Details:\n"); printf("ID: %d\n", student.id); printf("Name: %s\n", student.name); printf("Marks: %.2f\n", student.marks); printf("City: %s\n", student.address.city); printf("State: %s\n", student.address.state); printf("Pincode: %d\n", student.address.pincode); return 0; }
Output :
Enter student ID: 101
Enter student name: Alex
Enter student marks: 88.5
Enter city: Salem
Enter state: Tamil Nadu
Enter pincode: 636001
Student Details:
ID: 101
Name: Alex
Marks: 88.50
City: Salem
State: Tamil Nadu
Pincode: 636001
Enter student name: Alex
Enter student marks: 88.5
Enter city: Salem
Enter state: Tamil Nadu
Enter pincode: 636001
Student Details:
ID: 101
Name: Alex
Marks: 88.50
City: Salem
State: Tamil Nadu
Pincode: 636001