C_Structures_Unions_Exercises_Full
C_Structures_Unions_Exercises_Full
int main() {
struct Student s;
printf("Enter name, roll number, and marks: ");
scanf("%s %d %f", s.name, &s.roll, &s.marks);
printf("\nStudent Details:\nName: %s\nRoll No: %d\nMarks: %.2f\n", s.name, s.roll, s.marks);
return 0;
}
2. Array of Structures
struct Employee {
int id;
char name[50];
float salary;
};
int main() {
struct Employee emp[5], max_emp;
int i;
printf("Enter details of 5 employees (id, name, salary):\n");
for (i = 0; i < 5; i++) {
scanf("%d %s %f", &emp[i].id, emp[i].name, &emp[i].salary);
if (i == 0 || emp[i].salary > max_emp.salary) max_emp = emp[i];
}
printf("\nEmployee with highest salary:\nID: %d\nName: %s\nSalary: %.2f\n", max_emp.id, max_emp.name,
max_emp.salary);
return 0;
}
3. Nested Structures
struct Address {
char city[50];
int ward_number;
};
struct Person {
char name[50];
int age;
struct Address address;
};
int main() {
struct Person p;
printf("Enter name, age, city, and ward number: ");
scanf("%s %d %s %d", p.name, &p.age, p.address.city, &p.address.ward_number);
printf("\nPerson Details:\nName: %s\nAge: %d\nCity: %s\nWard No: %d\n", p.name, p.age, p.address.city,
p.address.ward_number);
return 0;
}
int main() {
struct Distance d1 = {5, 9.5}, d2 = {3, 4.5}, sum;
sum = addDistance(d1, d2);
printf("Sum of distances: %d feet %.1f inches\n", sum.feet, sum.inches);
return 0;
}
5. Union Demonstration
union Data { int i; float f; char ch; };
int main() {
union Data data;
data.i = 10;
printf("Integer: %d\n", data.i);
data.f = 20.5;
printf("Float: %.2f\n", data.f);
data.ch = 'A';
printf("Character: %c\n", data.ch);
printf("Integer after modifying char: %d\n", data.i);
return 0;
}
6. Structure Pointers
struct Book {
char title[50];
char author[50];
float price;
};
int main() {
struct Book b = {"C Programming", "Dennis Ritchie", 299.50};
struct Book *ptr = &b;
ptr->price = 350.75;
int main() {
BookRecord book;
printf("Enter book ID, title, and pages: ");
scanf("%d %s %d", &book.book_id, book.title, &book.pages);
int main() {
union Value val;
val.i = 10;
printf("Integer: %d\n", val.i);
val.f = 25.75;
printf("Float: %.2f\n", val.f);
strcpy(val.str, "Hello");
printf("String: %s\n", val.str);
return 0;
}
int main() {
struct StructExample s;
printf("Size of Structure: %lu\n", sizeof(s));
return 0;
}
union UnionExample {
int x;
float y;
};
int main() {
union UnionExample u;
printf("Size of Union: %lu\n", sizeof(u));
return 0;
}
int main() {
struct Employee e1 = {101, "John", .job.contract_duration = 12, 0};
struct Employee e2 = {102, "Alice", .job.salary = 60000.50, 1};
return 0;
}