You are on page 1of 52
Module 1: Introduction to Data Structures and Algorithns (21CS32) L Module 1 Introduction to Data Structures and Algorithms 1.1 BASIC TERMINOLOGY; ELEMENTARY DATA ORGANIZATION > Data are simply the values or set of values A data item refers to a single unit of values. Data items that are not able to divide into sub-items are called Elementary items. Example: r= {8050262021, 9844329766} is a set of phone numbers. Here 8050262021 a singe unit of values i.e. data item, > : An entity is something that has certain attributes or properties which may be assigned values. The values may be cither numeric or non-numeric > Field is a single elementary unit of informetion representing an attribute of an entity > Record is the collection of field values of « given entity. > File is the collection of records of the entities in a given entity set. Example: Entity — Studentixt | <«—— File name Names Age Sex USN Ramya 34 F 1RN20A1010 Sairam 23 M 1RN20CS005, QD ~~ Record Field Records may also be classified according to length. A file can have fixed-length records or variable-length records. © In fixed-length records, all the records contain the same data items with the same amount of space assigned to each data item. In variable-length records file records may contain different lengths. 1.2 DATA STRUCTURES The above organization of data into fields, records and files may not be enough to maintain and efficiently process on certain collections of data. For this reason, data are organized into more systematic structures. Data may be organized in many different ways; the logical or mathematical model ofa particular organization of data is called data structure, The study of such data structures includes following three steps: (1) Logical or mathematical description of the structure. (2) Implementation of the structure on a computer (3) Quantitative analysis of the structure, which includes determining the amount of memory needed to store the structure and the time required to process the structure. By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 1.2.1 Different Categories of Data Structures Data structures are generally classified into © Primitive data Structures © Non-primitive data Structures > Primitive data structures are the fundamental data types which are supported by a programming language. Basic data types such as integer, real, character and Boolean are known as Primitive data Structures. These data types consists of characters that cannot be divided and hence they also called simple data types Data Structures brmnve aata strucuires "Non pimiave data structures Imeger Real Character Boolean Linear data structure Non-linear data structure FE array [— Trees Ec Linked List L— crapns — Queue > Non-primitive data structures are those data structures which are created using primitive data structures. Examples of non-primitive data structures is the processing of complex numbers, linked lists, stacks, trees, and graphs. Based on the structure and arrangement of data, non- primitive data structures is further classified into i, Linear Data Structure ii, Non-linear Data Structure © Linear Data Structure: A data structure is said to be | car if its elements form a sequence or a linear list. There are basically two ways of representing such linear structure in memory. > One way is to have the linear relationships between the elements represented by means of sequential memory location. These linear structures are called arrays > The other way is to have the linear relationship between the elements represented by means of pointers or links. These linear structures are called linked lists Examples of Linear Data Structures are ; Arrays, Linked Lists, Stack and Queues. The following section briefly explains them. V Arrays: The simplest type of data structure is a linear (or one dimensional) array. An array is used to store a collection of data, it is often more useful to think of an array as a collection of By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: ina:atssooms nanan Module 1: Introduction to Data Structures and Algorithms (21CS32) 3 variables of the same type. An array holds several values of the same kind. A list of a finite number » of similar data referenced respectively by a set of n consecutive numbers, usually 0,1,2,3........1/. if A is chosen the name for the array, then the elements of A are denoted by subscript notation ao, a, a2, a3.....an-l Element First Index (at 5 th index) G1 2 3 4\5 6 7 8 9g —Indexes 0 [Satish 1 | Jyothi 2 | Sandeep Length of Array 10. ————_» A linear array STUDENT consisting of the names of three students is pictured in below figure. Here STUDENT [1] denotes Jyothi, STUDENT [2] denotes Sandeep, and so on. Linear arrays are called one-dimensional arrays because each element in such an array is referenced by one subscript. A two-dimensional array is a collection of similar data elements where each element is referenced by two subscripts Y Linked Lists: will be introduced by means of an example. Another way of storing the date shown in the figure 1.x is to have a separate array for the sales people. Customer | Pointer Customer | Salesperson |; ret ae 1 [aaa [8 —~ | tones | 1 | Adams ste. [a oem | rw ls 4 eon ay 3 | Clark 1 ‘Smith 3 3 | Clark ones | ¢ 7 4 | Drow Ray 5 Evans ‘Smith . a 6 Farmor Jones « 1 7 | Getler Ray 7 2 | 8] Hi smin |e 3 2 | Intes Ray © | ntea 2 Y Stack: A stack, also called a fast-in first-out (LIFO) system, , such that each index has a value associated with it. It can be called as corresponding or a mapping. Example: <0, 25> list{0]-25 <1, 15> list ]=15, Int array [0] = 25, 88,42, 10,14, 19,27, 44,28, 31) <2, 20> list[2]-20 <3, 17> list[3]=17 <4,35> list[4]=35 Here, list is the name of array. By using, list [0] to list [4] the data items in list can be accessed. Array declaration: A one dimensional array in C is declared by adding brackets to the name of a variable. Before using the array in the program, it must be declared. By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithms (21CS32) 7 Syntax: data_type array_name[size]; Where, data_type represents the type of elements present in the array, array_name represents the name of the array, Size represents the number of elements that can be stored in the array. Example: int age[100]; float sal[15]; char grade[20]; > Here age is an integer type array, which can store 100 elements of integer type. > The array sal is floating type array of size 15, can hold float values Grade is a character type array which holds 20 characters. Initialize arrays at the time of declaration. Syntax: data_type array_name[size] = {value1, valued,......valueN}; Where, valuel, value2, valueN are the constant values known as initializers, which are assigned to the array elements one after another. > Example: int marks[5]={16,2, 0,23, 4}; The values of the array elements after this initialization are: marks[@]=16, marks[1]=2, marks[2]=@, marks[3]=23, marks[4]=4; (a) Basic Initialization (b) Initialization without Size int numbers (5] = (3,7,12/24,45); int mumbers{ } = (3,7,12,24,45); (0) Partial Initialization (4) Initialization to All Zeros Ant numbers (5) = (3/795 Ant lotsofwumbers (1000) = (9); Representation of One-Dimensional Array in Memory We have already discussed that whenever an array is declared in the program, contiguous memory to it elements are allocated. Initial address of the array ~ ie. address of the first element of the array is called base address of the array. Each element will occupy the memory space required to accommodate the values for its type, ie.; depending on elements datatype, 1, 4 or & bytes of memory is allocated for each element. Next successive memory address is allocated to the next element in the array. This process of allocating memory goes on till the number of elements in the array gets over. By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: ina:atssooms nanan Module 1: Introduction to Data Structures and Algorithms (21CS32) 8 The elements of a one-dimensional array are stored at consecutive locations in memory. Each of the locations is accessed with the help of array index identifier to retrieve the corresponding element, Consider the following integer array: Consider the following integer array: arr[5] = {2,6,7,3}3 Here, arr is a five-element integer array. Figure 2.12 shows the representation of array arr in memory: Array Index ——y arr (0) art] afr{2) arr{3)_arrf4) Identifiers [ete]7Ts fe] Memory Locations ——» 6000 6002 6004 6006 6008 6010 Array art{5] Figure: Array representation in memory ‘As shown in Fig. 2.12, each array element is stored at consecutive memory locations, i.e., 6000, 6002, 6004, and so on. The location of the first element, i.e., 6000 is also referred as the base address of the array. If we know the base address of an array, then we can find the location of its individual elements by using a simple formula, which is address of A[k] = B+W * k Here, A[k] is the array. B is the base address, i.e., the address of the first element. W is the word size or the size of an array element. k is the index identifier. For instance. the address of the third element of array arr stored at index location 2 and assumed the word size is 2 bytes would be Address of arr[2] = 6000 + 2* 2 6000 + 4 6004 Note: The word size of a data type is decided by the programming language being used and the hardware specifications, 1.3.2 Operations on Arrays Following are the basic operations supported by an array. © Traversal — processing each element in the list ‘©. Insertion ~ adding a new element at given index to the list. © Deletion — removing an element at given index from the list By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: ina:atssooms nanan Module 1: Introduction to Data Structures and Algorithns (21CS32) 9 © Search ~ finding the location of the element with a given value or the record with a given key © Sorting: arranging the elements in some type of order. © Merging: Combing two lists into a single list. ‘Traversing Linear Arrays: Let A be the array in the memory of the computer. If the operation required is to print the contents of each element of A (OR) Count the number of elements of A. Then this is accomplished by traversing A, i.e, by accessing and processing each element of A exactly once 7/ program to demonstrate the array creation and array traversal. #include #include # define SIZE 50 void main () { int arr[SIZE]; // array declaration int index, no_ele; — Sean to Execute printf("Enter the number of elements\n"); scanf("%d", &no_ele); printf("\nenter the elements\n"); // Reading array elements for(index=@; index=K Step 3. [move jth element downward] set LA[J+1]=LA(J]. Step 4. [Decrease the counter] set J=I-1 [end of step 2 loop] Step 5. [insert element] set LA[K]A=ITEM Step 6. [reset N] set N=N+1 Step 7. Exit 7/ program to demonstrate array insertion operations. #includecstdia.h> #include #define SIZE 50 void main () { int arr [SIZE]; // array declaration int i, no_ele, pos, new_ele; printf ("Enter the number of elenents \n"); scanf("%d", &no_ele); // read the elements for the array print# ("\n Enter the elements \n"); for (i=; icno_ele; i++) scanf ("%d", &arr[i]); //traversal of the array to print all elements printf ("\n The elements of the array are \n"); for (i=@;icno_ele; i++) printf ("%d\t", arr[i])s printf("\n Enter the position of the new element to be inserted \n"); scanf("%d", &pos); printf ("\n Enter the new element to be inserted\n"); scanf("%d", &new_ele); for(isno_ele-1;i>=pos-1;i--) // making the place to insertion arr[it1]=arr[il]; arr[pos-1]=new_ele; // storing the new element printf("\nthe resultant array is \n"); for (i-@; icno_ele+i;i++) print#("Zd\t",arr[i])5 F Output Enter the number of elements 5 Enter the elements a By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) i 22 33 44 55 The elements of the array are 11 22 33) 4455 Enter the position of the new element to be inserted 4 Enter the new element to be inserted 99 The resultant array is 1122, 3399 4a SS Deletion Operation Deletion refers to removing an existing element from the array and re-organizing all elements of an array, Algorithm DELETE(LA, N, K, ITEM) Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Below is the algorithm to delete an element available at the K* position of LA. Step 1. Set ITEM=LA[K] Step 2. repeat for J=K to N-1 Step 3. [move (j+1)* element upward] set LAL! Step 4. [end of step 2 loop] Step 5, [reset N] set N=N-I Step 6. Exit LA[J+ I]. 7/ program to demonstrate the array creation and deletion operations. #include #include #define SIZE 5@ SH void main() ‘ ay int arr[SIZE]; // array declaration & int i, no_ele, pos, new_ele; printf("Enter the number of elements \n"); scanf("%d", &no_ele); // read the elements for the array printf ("\n Enter the elements \n"); for (i=@; icno_ele; i++) scanf("%d", &arr[i]); //traveral of the array to print all elements printf ("\n The elements of the array are \n"); for(i=®; icno_ele;i++) printf("%d\t", arr[i]); printf("\n\n Enter the position of the deleting element \n"); scanf("%d", &pos); // find an appropriate position for deletion for (i=pos-1; icno_ele-1; i++) arr[i]=arr[i+l]; By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 12 printf("\n The resultant array is \n") 5 for(i=®; icno_ele-1; i++) printf ("Kd\t", arr[i]); i Output Enter the number of elements 5 Enter the elements a1 22 33 44 55 The elements of the array are 11220 «334455 Enter the position from which the element to be deleted 4 The resultant array is fre? 2 S Searching Searching is the process of finding some particular element in the list. If the element is present in the list, then the process is called successful and the process returns the location of that element, otherwise the search is called unsuccessful. There are two popular search methods that are widely used in order to search some item into the list. They are Linear Search and Binary Search, however choice of the algorithm depends upon the arrangement of the list. Linear Search Linear search is the simplest search algorithm and often called sequential search. In this type of searching, we simply traverse the list completely and match each element of the list with the item whose location is to be found. If the match found then location of the item is retuned otherwise the algorithm return NULL. Linear search is mostly used to search an unordered list in which the items are not sorted. The algorithm of linear search is given as follows, Algorithm LINEAR SEARCH (DATA, N, ITEM, LOC) Here DATA is a linear array with N elements and ITEM is a given element to be searched. In linear search, DATA array is traversed sequentially to locate ITEM. The given algorithm finds the location LOC of item in DATA or set LOC=0, if the search is unsuccessful Step I. Initialize set K=0 and LOC=0 Step 2. Repeat steps 3 & 4 while(LOC=0 and K<=N-1) Step 3. IF ITEM == DATA[K], then LOC=K Step 4. Set K=K+1 [Increment Counter] Step 5. [End of step 2 loop] By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 3 Step 6. [Successful?] If LOC=0, then write: ITEM is not in the array DATA else write: LOC+1 is the position of ITEM Step 7. Exit #include void main () { int a[10] = {10, 23, 40, 1, 2, @, 14, 13, 50, 9}; int item, i,flag; printf("\nEnter Item which is to be searched\n"); scanf("%d", Bitem): for (i = 0; ix 10; i++) { if(ai] == item) t flag = i+1; break; } else flag = } if(flag != @) printf("\nItem found at location %d\n", flag); else printf("\nItem not found\n"); } Output: Enter Item which is to be searched 20 Item not found Enter Item which is to be searched 23 Item found at location 2 Binary Search Binary Search is a search algorithm that is used to find the position of an element (target value) in a sorted array. The array should be sorted prior to applying a binary search. Binary search is. also known by these names, logarithmic search, binary chop, half interval search, Algorithm BINARY SEARCH (DATA, LB, UB, ITEM, LOC) Here DATA is a sorted array with lower bound LB and upper bound UB and ITEM is a given item of information. The variables BEG, END and MID denote respectively the beginning, end and middle locations of a segment of elements of data. This algorithm finds the location LOC of item in DATA or sets LOC=NULL. Step 1. [Initialize segment variables] By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) M4 Set BEG=LB, END=UB and MID=INT((BEG+END)/2); Step 2. repeat steps 3 and 4 while BEG<-END and DATA[MID]!=ITEM Step 3. if ITEM int BinarySearch(int array[], int start, int end, int ele) { while (start <= end) { int mid = start + (end - start)/2; if (array[mid] == ele) return mid; if (array[mid] < ele) start = mid + 15 else end = mid - 1; } return -1; } int main(void) { int array[] = {1, 4, 7, 9, 16, 56, 70}; int n= 7; int element; printf("Enter the Searching Elenent : scanf("%d", element) ; int found_index = BinarySearch(array, @, n-1, element); if(found_index == -1 ) printf("Element not found in the array "); else printf(“Element found at index : %d",found_index); return @; } Output: Enter the Searching Element: 56 Element found at index: 5 Enter the Searching Element: 23 Element not found in the array By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 15 Bubble sort Algorithm Bubble sort works on the repeatedly swapping of adjacent elements until they are not in the intended order. It is called bubble sort because the movement of array elements is just like the movement of air bubbles in the water. Bubbles in water rise up to the surface; similarly, the array elements in bubble sort move to the end in each iteration. Although i bubble sort is poor in the real world, It is not suitable for large data sets. The average and worst- s simple to use, it is primarily used as an educational tool because the performance of case complexity of Bubble sort is O(n’), where n is a number of items. Algorithm BUBBLE SORT(DATA, N) Here DATA is an array with N elements. THIS Algorithm sorts the elemts in DATA. Step I. repeat steps 2 and 3 for k=1 to N-1 Step 2. [Initalize the pass pointer PTR]. Set PTR=1 Step 3. Repeat while PTR<=N-K : [Executes pass] (a) if DATA[PTR]>DATA[PTR+1] then Interchange DATA[PTR] and DATA[PTR+1] [end of IF structure] (b) set PTR=PTR+1 [End of inner loop] [end of step! outer loop] Step 4. Exit f#include void print(int a[], int n) //function to print array elements { int i; for(i = 0; i < nj i++) printf("%d ",afi]); } void bubble(int a[], int n) // function to implement bubble sort { int i, j, temp; for(i = 0; i < nj itt) HH oy r ha for(j = il; j void main() - ‘ asm int i, j, A(3](3], 6(3](3]1, C(31[3]5 printf("Enter the elements of 3 x 3 matrix A: \n"); a for(i=0;i<3;i++) For(j=035<35 j++) { printf(“A[%d][%d] =", i, 9)5 scanf("%d", &A[i][j]); // reading the matrix elements + printf("Enter the elements of 3 x 3 matrix B: \n"); For(i=03i<3;i++) for(j=035<335++) t printf("B[%d][%d] =", i, 3)5 scanf("%d", &B[i][j]); // reading the matrix elements } for(i=0;i<3;i++) For(j=035<35 j++) CLi(j]= Ali](9] + BLAILG]s prantfC\nthe enlered matrices are: printf("\nMatrix A \n"); for (i=@; i<3; i++) { printf("\n"); for(j=055 } printf("\nMatrix B \n"); for (i=0; i<3; i++) { printf("\n")5 tor (J=033<35 j++) printf("%d ", BLA] [5])3 + printf("\nMatrix C - Addition result \n"); printf("%d ", A[i][5])5 By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 18 for (i=0; ic3; i++) { printf("\n"); For (5=035<33 j++) printf("%d -", CCiJl5])5 } + OUTPUT: Enter the elements of 3 x 3 matrix A: ale] 2] Ale] (2) ale] [2] Al2]{0] ALaI{a] Ala ][2] alta] AlzI{1] Al2](2] Enter the 8[0][0] = Bfe](1] = B[o}[2] = 8[1][0] B(2] [1] B(1][2] 8(2][0] B[2][2] 8(2][2] WNHEENWYUWEN® COVaNEUNE lements of 3 x 3 matrix B: The entered matrices are: latrix A NaRZ conn wawe HUNe nuee wwe Matrix C - Addition result 336 aaa 8 10 12 By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 19 Subtraction of Matrices Subtraction is the task of subtracting individual elements of two matrices, For instance, C program to perform matrix subtraction will be same as matrix addition (see Example 2.7). Wejustreed to replace the + sign with a — sign, C program to perform matrix subtraction, #include i” void main() Beil on a, j, A[3](3], B(3](3], C(3][3]5 printf("Enter the elements of 3 x 3 matrix A: \n"); i] for(i=054<35i11) C for(j=0;j<3;j++) { print#("A[%d][%d] = ", i, 5)5 scanf("%d", @A[i][j]); // reading the matrix elements + printf("Enter the elements of 3 x 3 matrix B: \n"); for(i=O;i<3;i++) For(j=035<35 j++) { printf("B[%d][%d] = D3 scanf("%d", &B[i][j]); // reading the matrix elements h For(1=031<3;1++) For(j=035<35 j++) CLi(j]= ALi](5] - BLAILI1s printf("\nThe entered matrices are: \n") ; printf ("\nMatrix A \n"); for (i=@; i<3; itt) { print#("\n"); For (5-05 5x35 5+) printf("%d ", ALA]CI])5 a printf("\n") For (j=035<35 printf("%d ", BLA] L5])3 + printf("\nMatrix C - Subtraction result \n"); for (i=0; i<3; i++) { printf("\n"); For (J=03 4<33 J++) printf("%d ", Cli][5])3 By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 20 Output: Enter the elements of 3 x 3 matrix A: Afe] [2] Afe] [2] A@][2] A[1][2] A(2][1] A[1][2] A[2][0] A[2][1] aA(2][2] Enter the elements of 3 x 3 matrix B: B[@][0] = 2 B(@](1] B[@][2] B[1][0] = B[1][1] B(1][2] [2] [0] B[2][4] B[2][2] = 2 The entered matrices are: Matrix A 123 456 789 Matrix B in a 22 NewS Matrix C - Subtraction result -110 345 5 Multiplication two of Matrices Matrix multiplication is not as simple as matrix addition or subtraction. It uses a certain formula to generate multiplication result, For instance. aieacenaaey If matrix A = a4 asa a? BD bi ba And, matrix B = ba us Ser alblta2b4+a3b7 —alb2tazbSta3b8—alb3+a2b6ra then, AX B= adbltaSb4taéb7? —adb2+asbS+acb@ ——adb3 260 Q%bltadb4+a9b7 —a/bZtabstavs —a7b3+a8b6+a3D9 By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 21 Program : C program to perform multiplication on two 3x3 matrices #include void main() ion by 1] { LA int i, j, A([3](3], B(3](3], C[3][3]; printf("Enter the elements of 3 x 3 matrix A: \n"); BH For(i=05i<3;i++) for(j=035<3;j++) { print#("A[%d] [%d] i, i)s scanf("%d", @A[i][j]); // reading the matrix elements } printf("Enter the elements of 3 x 3 matrix B: \n"); For(1=031¢3 514+) For(j=035<33j++) { <3; i++) For(j=035<3;j++) { CLaJ(j] = For(keO3k<35 k++) CLAIG]= CLi(5] + ALATEKI*BLKI[G]5 h printf("\nThe entered matrices are: \n") ; printf ("\nMatrix A \n"); for (i=0; i<3; i++) { printf("\n For (j=05 j<33 j++) printf("%d ", ALi][3])3 } printf(“\nmatrix 6 \n"); for (i=@; i<3; i++) t printf("\n For (j=055<33 j++) printf("%d ", Bli][5]); } printf("\nMatrix C - Multiplication Result \n"); for (i=0; ic3; i++) t printf("\n For (j=03 5<33 j++) printf("%d ", Clil[5]); } } By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 2 The entered matrices are: eas wow wa Nwe@ bes ‘The product of the two matrices A x B is shown below: 30 24 18 84 69 54 /.438 11490 Transposing a Matrix In simple words, transposing a matrix refers to the task of changing the rows into columns and columns into rows. For instance: al a2 a3 Tf matrix A = a4 aS aé a? Baad al a4 a? Then, transpose(A) = a2 a5 a a3 a6 ad Program 2.10: Write a C program to perform transpose of a 3x3 matrices #include #define ROW 3 #define COL 3 void readMatrix(int a[ROW][COL]); void TransMatrix(int a[ROW][COL])5 void main() { int x[ROW] [COL]; printf("\nenter the matrix contents (3x3) \n"); readMatrix(x); printf("\nTranspose Matrix is \n"); TransMatrix(x) 3 a void readMatrix(int a[ROW][COL]) { ant 2,42 for (i=0; i<3; i++) for (j-035<355+4) scanf("%d", &a[i}[i])s } By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 23 void TransMatrix(int a[ROW][COL]) { int i,33 For (i=03i<3; i++) { For(j=035<3; j++) printf ("xd ", alJJLi])3 printf("\n"); } . Output Enter the elements of 3 x 3 matrix A: Afe}[e] AL@][1] Ale] [2] A[1][0] A(1)}(1] A(1] [2] A[21[0] Al2][21] A(2][2] 1 Z 3 4 =5 6 7 8 9 The entered matrices aré 1.4 Pointers in C Programming A pointer is a variable that stores the address of another variable. Unlike other variables that hold values of a certain type, pointer holds the address of a variable, For example, an integer variable holds (or you can say stores) an integer value, however an integer pointer holds the address of a integer variable, A simple example to understand how to access the address of a variable without pointers In this program, we have a variable num of int type. The value of num is 10 and this value must be stored somewhere in the memory, right? A memory space is allocated for each variable that holds the value of that variable, this memory space has an address. For example, we live in a house and our house has an address, which helps other people to find our house. The same way the value of By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 24 the variable is stored in a memory address, which helps the C program to find that value when itis needed. num Variable name Ox7#ff5694dc58 « Address of num So let’s say the address assigned to variable num is @x7ff#5694dc58, which means whatever value we would be assigning to num should be stored at the location: @x7FF#5694d58. See the diagram below. #include int main() t int num = 10; printf("Value of variable num is: %d", num); /* To print the address of a variable we use %p * format specifier and ampersand (&) sign just * before the variable name like &num. */ printf("\n Address of variable num is: %p", &num); return 6; y Output: Value of variable num is: 10 Address of variable num is: ex7fff5694dc58 Dereferencing of Pointer Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is dereferenced, using the indirection operator *. Dereferencing is used to access or manipulate data contained in memory location pointed to hy a pointer *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers. A ple Example of Pointers in C This program shows how a pointer is declared and used. There are several other things that we can do with pointers, we have discussed them later in this guide. For now, we just need to know how to link a pointer to the address of a variable. Important point to note is: The data type of pointer and the variable must match, an int pointer can hold the address of int variable, similarly a pointer declared with float data type can hold the address of a float variable. In the example below, the pointer and the variable both are of int type. By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 25 #include int main() { /WNariable declaration int num = 10; //Pointer declaration int *p; //Assigning address of num to the pointer p p = # printf("Address of variable num is: %p", p); return Q; i Pointer and Arrays When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array. Base address which gives location of the first element is also allocated by the compiler. Suppose we declare an array arr, int arr[5]={ 1, 2, 3, 4, 5 }5 Assuming that the base address of arr is 1000 and each integer requires two byte, the five element will be stored as follows in figure. element FEO) area} Here variable arr will give the base address, which is a constant pointer pointing to the element, arr[0]. Therefore arr is containing the address of arr[0] ie 1000. We can declare a pointer of type int to point to the array arr. int *p; p= arr; or p = &arr[@]; //both the statements are equivalent. Now we can access every element of array arr using p++ to move from one element to another. NOTE: You can also decrement a pointer once incremented. p-- moves back by one location. As studied above, we can use a pointer to point to an Array, and then we can use that pointer to access the array. Let’s have an example, tinclude int main() { int i; int a[5] = {1, 2, 3, 4, 5} int *p = a; // same as int*p = &a[0] for (i=; i<5; i++) { printe("%d", *p)5 pits a return 0; By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithms (21CS32) 26 In the above program, the pointer *p will print all the values stored in the array one by one. We can also use the Base address (a in above case) to act as pointer and print all the values. 1.5 DYNAMIC MEMORY ALLOCATION The process of allocating memory at runtime is known as dynamic memory allocation. The process of allocating | "32 Vz48bte } Stack memory during the runtime is called as DMA (dynamic | yee memory } Heap memory allocation) and memory gets allotted in heap area of lobal variable program stack Library routines known as memory |” management functions are used for allocating and freeing gee etas storage memory during execution of a program. These functions are ae variable defined in std -h header file. ‘The following functions are used in dynamic memory allocation and are defined in 1, malloc() : allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated space Declaration: void *malloc(size_t size); // ptr—(datatpe*)malloc(sizeofdatatype)); int x5 x = (int*)malloc(5@ * sizeof(int));//memory allocated to variable x free(x); _//releases the memory allocated to variable x 2. ealloc(): allocates space for an array of elements, initialize them to zero and then returns a void pointer to the memory. Declaration: void *calloc(sice_t n,size_t size); /ptr=(datatype*)calloc(n,sizeof{datatype)); The first argument specifies the number of blocks and the second one specifies the size of each block. The memory allocated by calloc() is initialized to zero, int * x = (int*)calloc(5@, sizeof(int)); //memory allocated to variable x free(x); _//releases the memory allocated to variable x 1.5.1 Difference between malloc() and calloc() calloc() malloc() calloc() initializes the allocated memory with | malloc() initializes the allocated memory with Ovalue, garbage values, ‘Number of arguments is 2 ‘Number of argument is 1 yyntax [Syntax : (cast_type *)calloc(blocks, size); |(cast_type *)malloc(size); By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: ina:atssooms nanan Module 1: Introduction to Data Structures and Algorithns (21CS32) 27 3. realloc() changes memory size that is already allocated dynamically to a variable. Syntax: vaid* realloc(pointer, new-size) Example: int *x; x = (int*)malloc(5@ * sizeof(int)); x = (int*)realloc(x,100); //allocated a new memory to variable x 4. free(); This function is used to release the memory space allocated dynamically. The memory released by free() is made available to the heap again and can be used for some other purpose Declaration: void free(void *p)s //free(ptr)s Program implementation of Array Operations 7/Program to demonstrate Array operation using Pointer #include #include int n,*a; // ‘n’ - no. of elements & ‘+a’ - Pointer array void create(int n) { int i; a=(int*)malloc(n*sizeof(int)); // Dynamic memory allocation if(a==NULL) { printf("\n ** Array not created ** \n"); return; printf("\n Array created successfully \n"); printf("\n Enter array elements \n"); for (i=0;icn; i++) scant ("%d", 8aLi]); } . void display() Af { = int i; for (i=0;icn; i++) Bers printf("%d\t", ail); i } void insert(int ele, int pos) { int ness a-(int*)realloc(a,n*sizeof(int)); while(j>=pos) { a(j+1]=a[j]; By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 28 alpos]=ele; } void delarrEle(int pos) { int j,item; item=a[pos]; printf("\n The deleted ele is %d\n", item); for(j=pos3j@ && pos<=(n+1)) { printf("\n Enter the element : "); scanf("%d" ele); insert(ele, pos-1); t else printf("\n ** Invalid Position ** \n"); display(); break; case 4: printf("\nEnter the deleleting element position : By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 29 scanf("%d", &pos); if(pos>@ && pos<=n) delarrEle(pos-1) ; else printf("\n ** Invalid Position ** \n" display(); break; default: free(a); exit(@); } // end of switch } // end of while } // end of main() Output: 5 =MENU =~ 1.CREATE 2.DISPLAY 3. INSERT 4. DELETE 5.EXIT ENTER YOUR CHOICE a Enter the size of the array elements: 5 Enter the elements for the array: Tu aUNe =-MENU -- 1.CREATE 2.DISPLAY 3.INSCRT 4, DELETE 5.EXIT ENTER YOUR CHOICE: 2 The array elements are: 1 2 3 4 «5 -MENU - 1.CREATE 2.DISPLAY 3. INSERT 4,DELETE 5. EXIT ENTER YOUR CHOICE: 3 By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 30 Enter the position for the new element: 3 Enter the element to be inserted: 31 The array elements are: 1 2 3 31 4 = =-MENU -- 1.CREATE 2.DISPLAY 3. INSERT 4,DELETE 5. EXIT ENTER YOUR CHOICE: 4 Enter the position of the element to be deleted: 3 The deleted element is =31 The array elements are: 1 2 31 4 «5 --MENU -- 1.CREATE 2.DISPLAY 3. TNSERT 4, DELETE 5.EXIT ENTER YOUR CHOICE: 5 1.6 STRUCTURES Along with built-in data types like int, float, char, double C provides the programmer to defi his/her own data-type. These are known as user-defined data types. A programmer can derive a new data type based on existing data types. Stuctures, Unions and Enumerations are considered to be major user-defined data types. We know that an array is a collection of related elements of same data type. But, if the related elements belong to different data types, then it is not possible to form an array. Consider a situation of storing the information about students in a class, The information may include name of the student, age of the student and marks of the student. It can be easily observed that name is a character array (or string), age might be an integer and marks obtained may be a floating point number, Though name, age and marks are of same student, we can not combine them into an array. By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 31 To overcome this problem with arrays, C allows the programmer to combine elements of different data types into a single entity called as a structure. Structure is a collection of inter-related elements of Siete ag different data types, The syntax of structure is: i a4 t For example: Ctypoe var2) —Ljpmber variables struct student t 291,82, ~ 90 sae int age; Me a float marks; $s1, 825 Here, student is name of the structure oF structure tag. oge, marks are member variables of a structure. s1, s2 are variables of new data type struct student. 1.6.1 Declaration of Structure Variables Structure declaration is considered to as defining a new data type. So, to make use of it, the programmer has to declare a variable of this new data type. There are two ways of declaring a structure variable. The programmer can declare variables of structure at the time of structure declaration itself as shown in the above example. Otherwise, one can declare them separately. For example ~ struct student t int age; float marks; % struct student s1,s2; Here, struct student is name of new data type and hence using it, one can declare the variables s1 and s2 Note that declaration of structure is just a prototype and it will not occupy any space in the memory. When a variable of structure gets declared, memory will be allocated for those variables. The memory space required for one structure variable will be the sum of the memories required for all member variables. In the above example, each of the structure variables s1 and s2 takes 6 bytes of memory (2 bytes for age and 4 bytes for marks). The memory map can be given as. sl s2 age marks age marks 2 bytes 4 bytes 2 bytes 4 bytes Thus, s1 and s2 are considered to be separate variables. By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 32 Note: Afier declaring some of the structure variables along with the structure definition, it is possible to declare some more structure variables in a separate statement as shown below: struct student { int age; float marks; }s1, 525 struct student s3, s4; 1.6.2 Structure | alization Just like any variable or an array, a structure variable also can be initialized at the time of its declaration, Values for member variables are given in a comma-separated list as we do for arrays. Consider an example: struct student { int age; float marks; } sl = {21, 84.5}; struct student s2 = {20, 91.3}5 NOTE: 1. Providing lesser number of values during initialization will make the rest of the variables to hold the value zero, That is, struct test { int a,b,c; Ft = (12, 45}; Now, the values of a, b and ¢ will be 12, 45 and 0 respectively. 2. It is not possible to give initial value to a member variable within a structure definition. Because, structure definition is just a logical entity and member variables will not be having any physical location until the structure variables are declared. Thus, following attempt is erroneous. struct test { int a=10; //error float b= 12.5; //error 4 1.6.3 Accessing Member Variables Member variables of a structure can not be accessed just by referring to their names, The reasor obvious. Refer to the memory map given in section 1.6.1. It can be observed that memory location for the member variable age of s! is different from that of s2. Similarly for the member marks. By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 33 Hence, it can be understood that each of the member variable is associated with a structure variable. Or in other words, every structure variable has its own copy of member variables. Thus, for accessing any member variable, its associated structure variable also should be specified. This is done with the help of dot (,) operator. The syntax is: Structure_variable.member_variable Example for accessing member variable #include struct student { int age; float marks; ysl, s25 void main() { s1.age=21; s2.age=sl.age; printf(“Enter marks of students: "); scanf("Xf%F", &S1.marks, &S2.marks) ; printf("\nAgel= %d Age2=%d", s1.age, s2.age); printf("\nMarksi= %f Marks2=%f", sl.marks, s2.marks); if(s1.marks>s2.marks) printf("\n First Rank is Student1"); else iu printf("\n First Rank is Student2"); The output would be: Enter marks of students: 81.5 92.3 Age = 21 ‘Age2 = 21 Marks1 = 81.5 Marks2 = 92.3 First Rank is Student2 1.6.4 Structure Assignment In some situations, the programmer may need two structure variables to have same values for all the member variables. Then, instead of assigning each member separately, it is possible to assign whole structure variable to another structure variable of same type. For example struct student { int age; float marks; } sl, s2={21,92.3}5 Now, the statement By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 34 s1=s2; will assign values of all members of s2 to the corresponding members of sI 1.6.5 Arrays within Structure A member variable of a structure can be an array of any data type. Consider the following example Example for array as a member of structure #includecstdio.h> struct student t char name[2@]; //array as a member int age; float marks; }s1, s2={“Ramya”,22,92.3}5 void main() { s1.age=21; printf (“Enter name of student:”); scanf(“%s”, s1.name) ; printf(‘\nénter marks of student:”); scanf(“%f”, &s1.marks) ; printf(“\n Student Information: \n”); printf(“\n Name \t\t Age \t\t Marks \n”); printf(“%s \t %d \t %f \n”, sl.name, sl.age, s1.marks); printf(“%s \t %d \t %F \n”, s2.name, s2.age, s2.marks); a The output would be: Enter name of student: Rammu Enter marks of students: 81.5 Student Information: Name Age Marks Rammu a 81.5 Ramya 22 92.3 1.6.6 Arrays of Structures We know that array is a collection of elements of same data type and the structure is a collection of items of different data types. Some times, it may be necessary to have several structure variables For example, if the information (like name, age and marks) about 60 students studying in 6th Semester is required, creating 60 structure variables is absurd. Instead, one can create an array of structure variables, Memory allocation for array of structures will be in contiguous locations, This concept is illustrated in the following example: Example for array of structures #include struct student { By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 35 char name[20]; int age; float marks; }s[2]; //array of structures void main() { int i; for(i= it printf(“Enter name of student”); scanf(“%s”, s[i].name)5 printf(“\nEnter age of student”); scanf(“%d”, 8s [1] .age) ; printf(“\nénter marks of student”); scanf("%", &s[i].marks) 5; sic2sie+) print#(‘\n Student Information: \n”) printf (“\n Name \t Age \t Marks \n”); For(i=0;i<2;i++) print#(“\nts \t Xd \t %F, s[i].name, s{i].age, s[i].marks); } The output would be: Enter name of student: Suma Enter age of student: 21 Enter marks of student: 81.5 Enter name of student: Roopa Enter age of student: 22 Enter marks of student: 92.3 Student Information: Name Age Marks ‘Suma 21 81.5 Rooja 22 92.3 In the above example, memary allocation for the array s[2] might be as follows: s(0] sft] s[0].name | s[0].age | s[0]. marks s[i].name | s[t].age | s[i]. marks Note that array of structure variables can also be initialized just like a normal array. For example: struct student { int ages float marks; }s[3] = { {21, 81.5}, {22, 92.3}, {25, 88.4} }; Then, the individual elements will be assigned the values as s[0] .age=21 s[1]. s[2]. s[0] .marks=81.5 s[1].marks=92.3 By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 36 s[2].marks=88.4 Note also that, un-initialized members will take the value as zero. 1.6.7 Nested Structures A member variable of a structure may be a variable of type another structure. This is known as nesting of structures. For example struct address t int d_nos /{ 2 bytes char street[20]; /1 20 bytes char city[2@]: JJ 20 bytes hb Total 42 bytes struct employee { char name[20]; /1 2@ bytes int d_nos 7 2 bytes float sal; /1 4 bytes struct address add; /1 42 bytes emp; The total memory allocated for the variable emp would be 68 bytes. The memory map can be emp.name _emp.num _emp.sal_emp.add.d_no emp.add.street emp.add.city 20 bytes 2oytes ] dbytes | 2byes 2 bytes 20 bytes 1000 1020 1022 1026 1028 1048 Here, the structure address contains the members d_no, street and city. Then the structure employee contains the members name, d_no, sal and add. Here, add is a variable of structure address. To access the members of the inner structure one has to use the following type of statements: emp.add.d_no emp.add. street emp.add.city etc. 1.6.8 Passing Structure to Functions Just like a normal variable, it is possible to pass a structure variable as a function parameter either using call-by-value method or call-by-address method. Member variables as arguments: Individual members of a structure can be passed to function as arguments. In this situation, members of structure are treated like any normal variable. Consider an example Structure member as a function argument #include struct add { int a, b; By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithms (21832) 37 b int sum(int x, int y) { return (x+y); + void main() { struct add var ; int s 5 printf("Enter two numbers :" ); scanf(“%dkd”, &var.a, &var.b); s=sum(var.a, var.b); printf(“sum is: %d”,s)3 } The output would be Enter two numbers : 5 8 Sum is: 13 Whole structure variable as an argument: Instead of passing each member of a structure to a function, entire structure variable can be passed. For example: #include struct add { int a, bs bs int sum(struct add A) //parameter is a structure variable { return (A.x + A.y)3 + void main() { struct add var: int 35 print#(“Enter two numbers :" ); scanf(“%d%d”, &var.a, &var.b)} s=sum(var) 5 print#(“Sum is: %d”,s); pa The output would be — Enter two numbers : 5 8 Sum is: 13 1.6.9 Pointers and Structures We can create a pointer to store the address of a structure variable. To access the member variables ofa structure using a pointer, we need to use either an indirectional operator -> or the combination of * and dot(.). Let us consider an example By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 38 #include struct student char name[ 20]; int age; 3 void main() { struct student s: struct student *p; &s5 printf (“Student name =%s”, p ->name); printf(“\nStudent age =%d”, (*p).age); “Ramu”, 22}; + In the above example, note the usage (*p) age Here, the pointer p is dereferenced first, and then dot operator is used to get the member variable age. Instead of two operators * and dot, we can use single indirectional operator (arrow mark) to achieve dhe same, That is, we ean use p->age, p->name ete. We can even create a pointer to array of structures also. For example (with respect to structure declared in the above example): struct student s[10], *p; p = s3 // base address of the array s is assigned to p Then, for accessing array members, we can use: for(i=0; icn;it+) printf(“%s %d”, p[i]->name, p[i]-age); The sit ir approach can be used while passing structures to functions via call by address method. 1.6.10 Union Union can be defined as a user-defined data type which is a collection of different variables of different data types in the same memory location. The union can also be defined as many members, but only one member can contain a value at a particular point in time. Union is a user-defined data type, but unlike structures, they share the same memory location. To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows — union [union tag] { member definition; member definition; member definition; By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithms (21CS32) 9 } [one or more union variables]; Example: union Data { int i; float #; char str[20]; } data; The memory occupied by a union will be large enough to hold the largest member of the union For example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string, The following example displays the total memory size occupied by the above union — #includecstdio.h> s#include union Data { int i; float f; char str[20]; 3 int main() { union Data data; print#( "Memory size occupied by data : %d\n", sizeof(data)); return 0; + When the above code is compiled and executed, it produces the following result - Memory size occupied by data : 20 Accessing Union Members To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use the keyword union to define variables of union type. The following example shows how to use unions in a program ~ #include #include union Data { int i float f: char str[20]; b int main() By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: ina:atssooms nanan Module 1: Introduction to Data Structures and Algorithns (21CS32) 40 it union Data data; data 10; data.f = 220.5; strcpy( data.str, "C Programming"); printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f); printf( "“data.str : %s\n", data.str); return 0; t When the above code is compiled and executed, it produces the following result — data.i : 1917853763 data.f : 4122360580327794860452759994368. 000000 data.str : C Programming Here, we can see that the values of i and f members of union got corrupted because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well Now lets look into the same example once again where we will use one variable at a time which is the main purpose of having unions #include #include union Data { int i; float f; char str[20]; } int main( ) { union Data data; data.i = 10; printf( "data.i : %d\n", data.i); data.f = 220.5; printf( “data. : Xf\n", data.f); strepy( data.str, "C Programming"); printf( "data.str : %s\n", data.str); return 0; } When the above code is compiled and executed, it produces the following result data.i : 10 data.f : 220.500000 By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 41 |data.str : C Programming Here, all the members are getting printed very well because one member is being used at a time. Difference between Structure and union Structure Union. The keyword struct is used to define a structure The keyword union is used to define a union. When a variable is associated with a structure, the compiler allocates the memory for each member. The sizeof structure is greater than or equal to the sum of sizes of its members. The smaller members may end with unused slack bytes When a variable is associated with a union, the compiler allocates the memory by considering the size of the largest member. So, size of union is equal to the size of largest member. Altering the value of a member will not affect other members of the structure Altering the value of any of the member will alter other member values. The address of each member will be in ascending order This indicates that memory for each member will start at different offset values. The address is same for all the members of a union. his indicates that every member begins at offset zero. Individual members can be accessed at any time since separate memory is reserved for each member. Only one member can be accessed at a time since memory is shared by each member. 1.7 APPLICATIONS OF ARRAYS and Structures The two major applications of the arrays are polynomial and sparse matrix Polynomial representation Sparse matrix representations 1.7.1 POLYNOMIALS Polynomial is a sum of terms where each term has a form sxe, where x is the variable, a is the coefficient and e is the exponent. Examples: A(x) = 3x242x5 44 B(x) =x! +10x3 43x? +1 The largest exponent of a polynomial is called its degree. In the above example, degree of first polynomial is 20 and for the second polynomial itis 4. By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) a2 Note: Coefficients that are zero are not displayed, the term with exponent zero does not show the variable i.e. 4x2+5x+1 where 1 is a term having exponent zero so variable is not displayed. Operations on polynomials © Ad ion © Subtraction © Multiplication Now, let us consider a polynomial with only one variable and see “How to represent each term of the polynomial?” Each term consists of a co-efficient multiplied by a variable raised to a power. So, each term can be represented by a structure consisting of 2 fields namely: ¢ cf (representing coefficient) # px (power of x) The structure det ‘ion for a term of a polynomial can be written as shown below: typedef struct { int cf; // used to hold the co-efficient int px; // used to hold power of x } POLY; Now, consider the following declaration along with its memory representation: /* declaration */ /* memory representation */ POLY P P| of px Once the memory is allocated as shown above, the term 6x‘ can be stored using the variable p as shown below: $y We have represented only one term. Now the question is “How to represent a polynomial with more than one node?” This can be done us ng array of structures with the following declaration: typedef struct { int cf; // used to hold the co-efficient int px; // used to hold power of x } POLY; POLY p[1@]; Using the above declaration, we have an array of 10 terms where each term has four fields. Consider the following polynomial: 8x9 + 3x! + 6x2 43x +4 It can be stored as an array of 5 terms as shown below: By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 6 B+ 3+ 6H ZK FT 1 1 oo 9 a 3 ace ee cae Real Pio} pill pet PB} pis} By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 44 Program to add two polynomials #include typedef struct int cf; // used to hold the co-efficient int px; // used to hold power of x } POLY; POLY p[10]; void read_poly(POLY p[], int n) { int i, cf, px; for(i = 0; i < nj itt) qi printf("cf, px:")3 scanf("Xd %d", &cf, 8px); pli].cf = cf; pli].px = px; I + void print_poly(POLY p[], int n) { int i; for(i = @; i = @) /* px1 found in poly 2 */ { sum = cf1 + p2[pos].cf; /* Add the coefficients */ if (sum != @) p3[k].cf = sum; /*Insert sum into poly 3*/ p2[pos].cf = -999; /* Delete the term of poly2 */ + else p3[k].cf = cf1; /* Insert co-efficient of poly 1 */ p3[k1.px = px1; /* Insert power of x into poly 3 */ ket + k = copy_poly(p3, k, p2, n); /* Copy remaining terms of poly 2*/ return k; /* return total terms in poly 3 */ } int copy_poly ( POLY p3[], int k, POLY p2[], int n) { int 55 for(j = @; j < ns j++) { if(p2[j].cf l= -999) { p3[k].cf = p2tj].cfs p3[k] .px = p2[j].pxs k++5 } F return k; + void main() { POLY p1[20], p2[20], p3[40]; int m,n, k; printf("Enter total terms in Poly 1:"); scanf("%d", &m); read_poly(p1, m); printf("Enter total terms in Poly 2:"); scanf("%d", &n); read_poly(p2, n); printf("Poly 1: "); print_poly(p1, m); printf("Poly 2: "); print_poly(p2, n); printf("------- k = add_poly (p1, m, p2, n, p3 printf(“Poly 3: ")3 print_poly(p3, k); } By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 46 Input Enter total terms in Poly 1:4 [Pl 6x" + 7x + 8x + 8 m=4 terms cf, px:66 <——___——+ ef, px: 73, <——______ cf, px: 8 | . Thus, a sparse matrix can be created using the array of triples as shown below By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 48 #define MAX 25 /* Maximum number of terms */ typdef struct { int row; int col; int val; } TERM; /* 1 dimensional array representing array of triples */ TERM a[MAX_TERMS]; Example: How do you represent the following spare matrix using triples in a single dimensional array? col{0] col[ 1] col[2] col[3] yop ew oui] 0 mo ovpfo 0 08 ow} 0 8 row0 1808 The non-zero elements in the above matrix along with row and col position can be represented using a single dimensional array starting from a[1] as shown below: row col val a0] 5. 4 8 5 x4iissize and 8 non-zero values in given matrix afl] 0010 a2] 0 3 40 row 0 aB} 10 a4] 1.2.22 TOW! Note: Since row 2 in given matrix has all as} 3. 0-20 ( entries, they are not considered. Hence, af6] 3.3.50 ''> inthis representation row 2 is missing a7] 40 115 as} 4323 TOw4 1 get the transpose we exchange row, col indices along with va! as shown below’ Input sparse matrix ‘Transposed sparse matrix stored as triple stored as triples row col val row col val ao) 5 4 58 _ D0]. interchange size al] 0 0 0-10 bit] a2] 0 3 1 11 bf] row0 a3} 1 0 3.20. 3] a4] 1 2 4015. b[4] row as} 30 122 b[S]) row alo] 3 3 0 40 {6} a7] 4 1 3 50 [7] row3 als} 4 3 4.25. bis} Program to transpose sparse matrix By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: ina:atssooms nanan Module 1: Introduction to Data Structures and Algorithns (21CS32) 49 #include #define MAX 20 typedef struct { int row; int col; int value; } term; void printsparse(term b[]); void readsparse(term sp[]); void transpose(term b1[], term b2[]); int main() { term s1[MAX],trans[MAX]; int m,n; printf("Enter the size of matrix (rows.columns):" scanf("%d%d" , &m,&n) 5 81[0] .row=m; s1[0].col=n; readsparse(s1); printsparse(s1); transpose(si,trans) 5 printf("\nAfter Transpose:\n"); printsparse(trans) ; } void readsparse(term sp[]) { int i,t; printf("\nEnter no. of non-zero elements: scanf("%d" ,&t) 5 sp[®].value=t; for(i i printf("\nEnter the next triple(row, column, value): scanf("%d%d%d" , &sp[i] .row, &sp[i] .col, &sp[i].value) 5 } } void printsparse(term b[]) { int i,n; n=b[0].value; //no of 3-triples printf ("\nrow\t\tcolumn\t\tvalue\n") ; for (i=03i<=n; i++) printf ("%d\t\t&d\t\t%d\n", b[i] row, bli] .col, bi] .value) ; + void transpose(term bi[],term b2[]) { int i,j.ksn3 b2[@].row=b1[@].col; By: Dr. Rama Satish KV, RNSIT, Associate Professor, Bengaluru, For latest updates visit: inuatsasoa antici Module 1: Introduction to Data Structures and Algorithns (21CS32) 50 b2[@] .col=b1[0].row; b2[@].value=b1[@]. value; 1[0]. value; for (i=03i

You might also like