PPS
Unit – 8STRUCTURE/UNION Q1. Define structure? Explain how to access elements in structures?A1. A structure can be considered as a template used for defining a collection of variables under a single name. Structures help programmers to group elements of different data types into a single logical unit (Unlike arrays which permit a programmer to group only elements of same data type).Why Use Structures • Ordinary variables can hold one piece of information• arrays can hold a number of pieces of information of the same data type.For example, suppose you want to store data about a book. You might want to store its name (a string), its price (a float) and number of pages in it (an int). If data about say 3 such books is to be stored, then we can follow two approaches: Construct individual arrays, one for storing names, another for storing prices and still another for storing number of pages. Use a structure variable.Suppose we want to create a employee database. Then, we can define a structurecalled employee with three elements id, name and salary. The syntax of this structure is asfollows:struct employee { int id; char name[50]; float salary; }; Q2. Explain structure variable declaration?A2. We can declare the variable of structure in two waysDeclare the structure inside main function Declare the structure outside the main function. 1. Declare the structure inside main functionFollowing example show you, how structure variable is declared inside main functionstruct employee { int id; char name[50]; float salary; }; int main(){struct employee e1, e2; return 0;}In this example the variable of structure employee is created inside main function that e1 ,e2. 2. Declare the structure outside main functionFollowing example show you, how structure variable is declared outside the main function struct employee { int id; char name[50]; float salary; }e1,e2; Q3. Explain memory allocation for structure?A3. Memory is allocated to the structure only when we create the variable of structure.Consider following example
Q4. How do you declare structures for multiple variables?A4. struct student{char name[20];int roll;float marks;}std1 = {"Poonam" ,67, 78.3};std2 = {"Vishal",62, 71.3};In this example, we have declared two structure variables in above code. After declaration of variable we have initialized two variable.std1 = {"Poonam" ,67, 78.3};std2 = {"Vishal",62, 71.3}; Q5. How do you access structure elements in the array?A5. Structure is collection of different data type. An object of structure represents a single record in memory, if we want more than one record of structure type, we have to create an array of structure or object. As we know, an array is a collection of similar type, therefore an array can be of structure type.Syntax for declaring structure arraystruct struct-name{datatype var1;datatype var2;- - - - - - - - - -- - - - - - - - - -datatype varN;};struct struct-name obj [ size ];Example for declaring structure array#include<stdio.h>struct Employee{int Id;char Name[25];int Age;long Salary;};void main(){int i;struct Employee Emp[ 3 ]; //Statement 1for(i=0;i<3;i++){printf("\nEnter details of %d Employee",i+1);printf("\n\tEnter Employee Id : ");scanf("%d",&Emp[i].Id);printf("\n\tEnter Employee Name : ");scanf("%s",&Emp[i].Name);printf("\n\tEnter Employee Age : ");scanf("%d",&Emp[i].Age);printf("\n\tEnter Employee Salary : ");scanf("%ld",&Emp[i].Salary);}printf("\nDetails of Employees");for(i=0;i<3;i++)printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);}Output :Enter details of 1 EmployeeEnter Employee Id : 101Enter Employee Name : SureshEnter Employee Age : 29Enter Employee Salary : 45000Enter details of 2 EmployeeEnter Employee Id : 102Enter Employee Name : MukeshEnter Employee Age : 31Enter Employee Salary : 51000Enter details of 3 EmployeeEnter Employee Id : 103Enter Employee Name : RameshEnter Employee Age : 28Enter Employee Salary : 47000Details of Employees101 Suresh 29 45000102 Mukesh 31 51000103 Ramesh 28 47000In the above example, we are getting and displaying the data of 3 employee usingarray of object. Statement 1 is creating an array of Employee Emp to store the recordsof 3 employees.Array within StructureAs we know, structure is collection of different data type. Like normal data type, It canalso store an array as well.Syntax for array within structurestruct struct-name{datatype var1; // normal variabledatatype array [size]; // array variable- - - - - - - - - -- - - - - - - - - -datatype varN;};struct struct-name obj;Example for array within structurestruct Student{int Roll;char Name[25];int Marks[3]; //Statement 1 : array of marksint Total;float Avg;};void main(){int i;struct Student S;printf("\n\nEnter Student Roll : ");scanf("%d",&S.Roll);printf("\n\nEnter Student Name : ");scanf("%s",&S.Name);S.Total = 0;for(i=0;i<3;i++){printf("\n\nEnter Marks %d : ",i+1);scanf("%d",&S.Marks[i]);S.Total = S.Total + S.Marks[i];}S.Avg = S.Total / 3;printf("\nRoll : %d",S.Roll);printf("\nName : %s",S.Name);printf("\nTotal : %d",S.Total);printf("\nAverage : %f",S.Avg);}Output :Enter Student Roll : 10Enter Student Name : KumarEnter Marks 1 : 78Enter Marks 2 : 89Enter Marks 3 : 56Roll : 10Name : KumarTotal : 223Average : 74.00000In the above example, we have created an array Marks[ ] inside structure representing3 marks of a single student. Marks[ ] is now a member of structure student and toaccess Marks[ ] we have used dot operator(.) along with object S.Q6. Write a program to obtain the details of the 3 employees?A6. #include <iostream>using namespace std; struct employee { string ename; int age, phn_no; int salary;}; // Function to display details of all employees void display(struct employee emp[], int n) { cout<< "Name\tAge\tPhone Number\tSalary\n"; for (int i = 0; i< n; i++) { cout<< emp[i].ename<< "\t" << emp[i].age << "\t"<< emp[i].phn_no<< "\t" << emp[i].salary << "\n"; } } // Driver code int main() { int n = 3; // Array of structure objects struct employee emp[n]; // Details of employee 1 emp[0].ename = "Chirag"; emp[0].age = 24; emp[0].phn_no = 1234567788; emp[0].salary = 20000; // Details of employee 2 emp[1].ename = "Arnav"; emp[1].age = 31; emp[1].phn_no = 1234567891; emp[1].salary = 56000; // Details of employee 3 emp[2].ename = "Shivam"; emp[2].age = 45; emp[2].phn_no = 1100661111; emp[2].salary = 30500; display(emp, n); return 0;} Output :Name Age Phone Number SalaryChirag 24 1234567788 20000Arnav 31 1234567891 56000Shivam 45 8881101111 30500Q7. Define union.A7. Unions are quite similar to the structures in C. Union is also a derived type asstructure. Union can be defined in same manner as structures just the keywordused in defining union in union where keyword used in defining structure was struct.union car{char name[50];int price;};Union variables can be created in similar manner as structure variable.union car{char name[50];int price;}c1, c2, *c3; OR;union car{char name[50];int price;};-------Inside Function-----------union car c1, c2, *c3;In both cases, union variables c1, c2 and union pointer variable c3 of type unioncar is created. Q8. How do you access the members of the union?A8.Array elements are accessed using the Subscript variable , Similarly Union members are accessed using dot [.] operator. (.) is called as “union member Operator”. Use this Operator in between “Union variable”&“member name” union employee { int id; char name[50]; float salary; } ;void main() { union employee e1= { 1, “ABC”, 50000 }; printf(“%d”, e. id);printf(“%s”, e. name); }O/P- garbage value, ABC Q9. Compare structure and union?A9.
Q10. Write a program to store information of students and display it?A10.#include <stdio.h>#include <string.h>union Student { int age; char Name[50]; char Department[20];};int main() { union student stud1; union Employee stud2; stud1.age = 28;strcpy(stud1.Name, "Chris");strcpy(stud1.Department, "Science");printf("\nDetails of the First Student \n");printf(" Student Age = %d \n", emp1.age);printf(" Student Name = %s \n", emp1.Name);printf(" Student Department = %s \n", emp1.Department); printf("Details of the Second Student \n" ); stud2.age = 30;printf(" Student Age = %d \n", stud2.age );strcpy(stud2.Name, "David");printf(" Student Name = %s \n", stud2.Name );strcpy(stud2.Department, "Technology" );printf(" Student Department = %s \n ", stud2.Department ); return 0;}OUTPUT:Details of the first student Student Age = 28Student Name = ChrisStudent Department = ScienceDetails of the Second Student Student Age =30Student Name = DavidStudent Department= Technology
Structure | Union |
struct keyword is used | union keyword is used |
size of structure variable is the addition of all members of structure | size of union variable is the maximum size of among all members of union |
At a single time more than one member can accessible | At a single time only one member is accessible |
0 matching results found