Download as pdf
Download as pdf
You are on page 1of 14
OOB6ea NOTES CL Pokhara Ctucversityy Unit VII: Structure and Unions — C Programming Definition of Structur: In real application, we need to group different types of logically related data. For example: If we want to create a record of student that consists of name, roll no and marks. Then to store such record we use structure. Structure is a collection of heterogeneous data types which are grouped together under a single name. A structure can contain any valid data types like int, char, float or even arrays and other structures. Each variable in structure is called structure member. To define a structure, we use ‘struct’ key word. Syntax: struct student ( data_type member 1; data_type member 2; data type member nj } variables; Example: struct student ‘ char nane [50]; int rolino; Float marks; } studenti, student2; Structure Initialization Like standard data type, the members of a structure variable can be initialized. The values to be initialized must appear in order as in the definition of structure within brace and separated by comma. C does not allow initialization of individual structure member within its definition, Syntax: struct structure_nane = (variable, variable, variable]; ckundan.com.np 1 OOB6ea NOTES (DQ) Proetara Diuiversity Struct student {char name[]; int roll; float marks:): ‘The structure of this type can be initialized as: Struct student 5 = {"Ramesh", 101, 65.5); 0: S.name = "Ramesh", s.roll = 101, s.marks = 85.5; Processing Structure and Accessing Member of Structure: For accessing any members of structure we use dot operator (.), which is also known as period/membership operator. The dot operator has highest precedence and associatively from leftto right. Since, itis an operator of highest precedence, dot operator will take first precede over various arithmetic, relational and logical assignment and unary operator. ‘Thus ++s.marks is equivalent to ++(s.marks), implying that the dot operators acts first and then unary operator. Syntax: structus! ._variable.member; Example: s-r0lly s-marks; Tag Nam ‘Tag name is optional, but it is always better to specify a tag name for the structure. If we deciare variable without tag name, we will not be able to declare other variables of this structure type anywhere on the program nor can we send these structures to the function. Write A Program to Display the Values of Structure Members. #includecstdio b> #include #include struct student { int roll; char nane[50]; float marke; 1 main() ‘ struct student stul = (101,"Ramesh", 85.5 www.ckundan.com.np OOBea NOTES OO) Pokhara Cuiversity D struct student stu2, stu3; stu2.roll = 102; strcpy(stu2-name, "Shyan") ; stu2.marks = 95; print£(*\ninter roll number of student3 => scant ("ta", cetu3.roll) 7 printr(*\nsnter name of students => scanf("$s",stu3.name) printé(*\nEnter marks of student3 => "); scanf("$", gstu3.marks); print£("\nRoll number of student1 => sd", stul.roll); print£("\ntlame of etudentl => ¢e",etul.name); print£("\nMarks of studentl => $.2£",stul.marks); print£("\n"); printf(*\nRoll number of student? => $d",stu2.roll): printf("\nName of student2 => $s", stu2.name); printf ("\nNarks of student? => $.2£",stu2.marks); print£("\n"); print£("\nRoll number of student3 => $d", otu3.roll); print£("\nllane of student3 => $s",stu3.name); print€("\nMarke of student3 => ¢.22",ctu3 marks); getcny; Array of Structure: We know thatarray is a collection of elements of same data type. We can declare array of structure which is of structure type. If we want to keep record of 50 students, we have to make 50 structures variable like stu1, stu2 and so on. But this technique is not good. At this situation we can use array of structure to store record of 50 students. ‘Syntax: struct student stuf50); Write A Program to Understand Array of Structure. #include finclude struct student ‘ int roll; char nano[50]; float marks; }s(101; www.ckundan.com.np 3 Pokhara Cuiversity D OOBCa NOTES L main() int i; fox (i=0;4<3;4+4) ( print£(*\nEnter roll number of student $d => ",it1); scanf ("$d", &s[i].r011); printf("\nEnter name of student $d = scant ("$s",s{i]-name); printf(*\nEnter marks of student $d £", 65 [4] -marks) ; scant for (i=0;i<3;i++) ‘ printr(*%d\t\tss\t\ts.22",s[i].roli,s[i] .name, s[1] marks); print£(*\n"); ? getch(); Structure Within Another Structure/Nested Structure: ‘Sometime one structure is defined inside another structure that type ofstructure is called nested structure. Syntax: Struct structure nane 1 ‘ Data_type member 1; Data type member 2; Data_type member ny Struet structure nane 2 ‘ Data_type member Data type membor Data_type member } variable 1; } variable 2; Write A Program to Demonstrate Nested Structure. #include #include struct date ‘ www.ckundan.com.np 4 OOBea NOTES OO) Pokhara Cuiversity D char day (201; char month (25) 7 int year; Vy struct employee ‘ char nane [23]; int id float salary; struct date sdate: Jemp; main() printf ("Enter details of employee\n\n"); prine£(*Nane:\e")7 scani("$s",emp.name) ; printe(*Td:\e"); scant ("sd", 6emp.id) ; print£(*Day of birth:\t") ; scant ("3s",enp.sdate day) ; print£(*Wonth of birth:\t"); scant ("$5",enp.sdate month); print£ ("Year off birth:\t"); scant ("$a", cenp. adate. year) print£(*Salary:\t") ; scant ("¢2", comp. salary]? prints ("the information is \n*); printe( prints (*Name: \ tr birth:\tsalary:\n") ; peints( print£(*Ss\téd\tss\tis\ted\t\ts.2£",emp.name,emp. id, emp.sdate.day,enp -edate.month, enp.edate.year, emp.2alary) getch (); \tMonth of bird mannne=\n"); ) Pointer to Structure: Pointer can be used with structure to store address of structure variable; we can define a structure with pointer object as normal way. Let us consider a structure book that has members name, page and price. It can be declared as: struct book ‘ char nane[45]; int pag float page; » struct book b; // this is normal variable sturct book *bptr; //this is pointer variable www.ckundan.com.np 5 OOBCa NOTES L CPothara Le aity) To use structure members through pointer, memory must be allocated for a structure by using function call malloc() or by adding declaration and assignment as: bptr = &b; An individual structure member can be accessed in terms of its corresponding pointer object with arrow (->) operator. As: object -> member. Here -> is called arrow operator and there must be structure on left side of this operator. Normal Structure PointerStructure _ Pointer structure bname bptr -> name (*bptr).name b.page bptr-> page (*bptr).page bprice bptr -> price (*bptr).price Here b is normal structure object and bptr is pointer structure objects of name, page and price members. However last two columns are same procedure. Write A Program To Demonstrate Pointers To Structure. #include #include struct book ‘ char nane [40]; int page: float price; a main() { struct book b, *bpt pptr = ab; printf ("Enter details of a book:\n"); inte (*Name:\t") j gets (b.name print£ ("Pag NE") scant ("$d", &b.page) ; até ("Price:\t"); £", 5b.price); scant (" inte (™ ace ("Nam inte (* nte("Ss\t\tad\e\ts. \t\tpage: \t\terice:\n"); nt) = (*hpte) -name, (*bptr) -page, (*bptr) -price) ; ntf("$s\t\téd\t\ts.2£", bptr->name, bptr->page, bptr->price); getch (0s Passing Structure Members to Function: Structure variable can also be passed to a function we may either pass individual structure elements or the entire structure. A structure member can be treated just as www.ckundan.com.np 6 OOBCa NOTES (JD) Pottara Cur normal variable of structure type. For example, integer structure variable can be treated aity) just as integer. Thus, structure members can be passed to function like ordinary variables Write A Program to Illustrate Passing Structure Member to Functions. #include #include void display (char name{], int id, float salary) ate (* nté (*Name: \tID:\tSalary") ; inte (*\n=: ntf("$s\ttd\ts. =\n"); An"): name, id, salary) ; struct employee ‘ char nane [25]; int id float salary; struct employee emp; ntf ("Enter details of employee: \n"); até (*Name:\t") 7 gets (emp.name) ; int£(*ID:\t") scant ("$d", gemp.id) ; print£(*Salary:\t"); scan (" print£("\nEntered Information: \n") ; display (omp-name, emp.id,emp. salary); getch(); £", emp. salary); Passing Whole Structure to Function: It is possible to send entire structures functions as arguments. In the functions call, structure variable is treated as any ordinary variable. Write A Program to Illustrate Passing Whole Structure to Function. #include finclude struct employee ‘ int id; char nane[25]; char address[40]; float salar www.ckundan.com.np 7 OOBCa NOTES OO) Pokhara Cuiversity D Jemp: void display(struct employee e) ‘ peinte(" print£(*ID: \tlame prints (" printf ("$d\tés\tss\t\ts.2!",e.id,e.nane, e.address,e. salary); printf ("Enter Details of employee:\n"); print£(*ID:\t"); scant ("$d", gemp.id) ; printf (*Name:\t") scant ("$a",emp.name) print£("Address:\t") > scant ("$s",omp address); printt(*salary:\t"); scanf("$f", Genp. salary}; printf ("\ngntered Information:\n) ; display(emp); getch(); Passing Structure Pointer to Function: ‘The structure pointer can be passed to function. If the pointer to a structure is passed as an argument to a function, then any changes that are made in the function are visible in the caller. Write A Program to Illustrate Passing Structure Pointer to Function. #include #include struct employes ‘ int id? char nane[25]; char address{401; float salary; demp; void display (struct employee e} { printf ("\nEntered Employee Detaile:\n")? printe(" printf (*TD: \tlame:\taddress:\tSalary:\n") printr(” printf ("Sd\t#s\tss\ts.2£",e. id, e.name,e.address,e.salary): ) void increasesalary (struct employee ‘ee) www.ckundan.com.np 8 CPothara uiversity ) OOB6ea NOTES L ‘ (tee) salary = (*ee) salary + 1000; ) main() { ntf ("Enter Detaila of Employee: \n"); inte (*ID:\t"); scant ("sd", cemp.id) ; printt(*Name:\t"); scanf("$s",emp name) > inte ("Address:\t") 7 scanf("$s",emp.address}; inté(*Salary:\t"); scanf("$£", Gemp. salary}; increasesalary (semp) display (emp); getch(): ) Passing Array of Structure to Function: Passing an array of structure to function involves same syntax and properties as passing array to a function. The passing is done using a pointer array structure in function, ifany changes made in function to structure, the structure also visible in caller. Create a structure student that has name, rollno, marks and remarks as members to read and display records of 2 students. Create two functions read information and display information which pass array of structure to these functions. #include #include fdefine size 2 int iz struct student { int roll? char nane[45]; Float marks? char renarks(20); void display (struct student st/]) ‘ for (i=0;i<2 ‘ ++) rintf ("8d\tes\tt.2f\t$s\n", st{i]. roll, st [i] .name, st [i] .marks, st [i] .r CPothara uiversity ) OOBCa NOTES L > ) void read (struct student stu(]) ( float temp; fox (in0;4<2;i+4) print£(*\nEnter $d:\n", iti); printzr(*Rollno:\t") ; scant ("$a", astu[i].roll): print£(*Nane:\t"); scanf ("$s", stu (il .name) ; printf (*Marks:\t"); scant ("$£", stu[i].marks) ; print£(*Renarke:\t! scanf ("$s", stu[i] -remarks); ) main() ‘ struct student s{sizel; inté("Enter Students Details: \n"); read(s); print£("\nEntered Student Detaile:\n"); display(s); getch(); Linked Lis Alinked listis a linear collection of data components whose order is determined by their physical location in memory, rather than by their physical location in memory. Rather, each piece serves as a stepping stone to the next. It's a data structure made up of a group of nodes that constitute a sequence when put together. its most Each node includes data and a connection to the next node in the sequence basic form. During iteration, this structure enables efficient insertion and removal of items at any point in the sequence. Additional connections are added in more complicated versions, allowing for more efficient insertion and removal of nodes at random places. Syntax: struct node ‘ data_type member 1; data_type member data_type member struct node *link; // "pointer to next node of the list www.ckundan.com.np 10 OOB6ea NOTES L nktiara Luiversity D 1 +2 [3 aN Applications of Linked List in Computer Science: Implementation of stacks and queues Implementation of graphs: Adjacency list representation of graphs is most popular which uses linked list to store adjacent vertices is. Dynamic memory allocation: We use linked list of free blocks. Maintaining directory of names Performing arithmetic operations on long integers Manipulation of polynomials by storing constants in the node of linked list representing sparse matrices + o eee Applications of Linked List in Real World: Image viewer ~ Previous and next images are linked, hence can be accessed by next and previous button. ‘ Previous and next page in web browser - We can access previous and next U searched in web browser by pressing back and next button since, they are linked as linked list. ‘Music Player - Songs in music player are linked to previous and next song. We can play songs either from starting or ending of the list. Applications of Circular Linked Lists: + Useful for implementation of queue. Unlike this implementation, we don't need to maintain two pointers for front and rear if we use circular linked list. We can maintain a pointer to the last inserted node and front can always be obtained as next of last. “ Circular lists are useful in applications to repeatedly go around the list. For example, when multiple applications are running on a PC, it is common for the operating system to put the running applications on a list and then to cycle through them, giving each of them aslice of time to execute, and then making them wait while the CPU is given to another application. It is convenient for the operating system to use a circular list so that when it reaches the end of the list it can cycle around to the front of the list * Circular Doubly Linked Lists are used for implementation of advanced data structures like Fibonacci Heap. www.ckundan.com.np 11 BCA NOTES Pokhara Ctucversityy C O Union: Union like structure contains members whose individual data types may differ from one another. However the members that compose a union share the same storage area within the computer memory whereas each member within a structure is assigned its own unique storage area. Thus unions are used to conserve memory. They are useful for application involving multiple members, where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows: Union union name ‘ Data_type member 1; Data_type member 2; Data_type member nj } variables; ‘The member of the union can be used only one ata time. If there exit three members and we place three values in it then every storing value replace previous stored value of the member defined within union. The memory size taken by the union is the highest member size only. Union is rarely used in modern programming but it is highly preferable when only one value can be stored in its member and these devices having lower memory. Although structure and union look similar to each other from their definition point of view, the main differences are as follows: Structure Union Structure is designed by using ‘struct’ Union is designed by using ‘union’ keyword. keyword. The syntax to design structure is as The syntax to design union is as follows: follows: union union name struct structure name { data type member 1; data_type member 2; data type member n; } variables; The amount of memory required to store a structure variable is the sum of the size of all the members. For Example: Struct student i Char name{30]://char = 1 byte * 30 char address {10];//char = 1 byte * 10 ( data_type nember 1; data_type nember 2; data_type nember n; ) variables; ‘The amount of memory required to store a union variable is equal to the size required by the largest member of the union. For Example: Union student ( char name[30]; //char = Char nane{10]: //char 1 byte * 30 1 byte * 10 www.ckundan.com.np 12 C O ‘The size of the above structure sis the sum ofthe two membersi.e. 40 bytes All the members of the structure variable can be processed ata given time. We use structure variable if memory is large and have to store values all of the variables. Structures are programming. Structures declaration takes large amount of spaces to store data and values. broadly used in BCA NOTES CPothara uiversity ) The size of the above union variable u is equal to the size of the largest member i.e. 30 bytes, Only one member of the union variable can be processed at a time because only one member of the union variable can be active ata time. We use union variables if memory is less and have to store one variable in one of the declared variables or members. Unions are not broadly used as much as structures. Union declaration shares the same area of memory to save storage space. Write A Program to Demonstrate Working Process of Union. #include finclude union student { int roll: char nane[45]; float marks; }stu; main() i printr("enter student Details:\n\n"); print£(*Rollno:\t") ; scanf("sd",estu. roll)? printf (*Nane:\t"); Scant ("$s",stu.name) 7 printf ("Marks:\t"); pecans (" £",sstu.marks); www.ckundan.com.np 13

You might also like