id
int64
0
25.6k
text
stringlengths
0
4.59k
24,300
data structures using middle of the array to do thiswe must first find the location from where the element has to be deleted and then move all the elements (having value greater than that of the elementone position towards left so that the space vacated by the deleted element can be occupied by rest of the elements example valuesdata[is an array that is declared as int data[ ]and contains the following data[{ }(aif data element with value has to be deletedfind its position (bdelete the data element and show the memory representation after the deletion solution (asince the elements of the array are stored in ascending orderwe will compare the value that has to be deleted with the value of every element in the array as soon as val data[ ]where is the index or subscript of the arraywe will get the position from which the element has to be deleted for exampleif we see this arrayhere val data[ which is not equal to we will continue to compare and finally get the value of pos ( datadata[ data[ data[ data[ data[ data[ data[ data[ algorithm to delete an element from the middle of an array step [initializationset pos step repeat steps and while < step set [ia[ step set [end of loopstep set step exit figure the algorithm delete will be declared as delete(anposthe arguments arealgorithm to delete an element from the middle of an array datadata[ data[ data[ data[ data[ datadata[ data[ data[ data[ data[ datadata[ data[ data[ data[ data[ datadata[ data[ data[ data[ data[ datadata[ data[ data[ data[ figure deleting elements from an array (aathe array from which the element has to be deleted (bnthe number of elements in the array (cposthe position from which the element has to be deleted figure shows the algorithm in which we first initialize with the position from which the element has to be deleted in step while loop is executed which will move all the elements having an index greater than pos one space towards left to occupy the space vacated by the deleted element when we say that we are deleting an elementactually we are overwriting the element with the value of its successive element in step we decrement the total number of elements in the array by nowlet us visualize this algorithm by taking an example given in fig calling delete (data will lead to the following processing in the array
24,301
programming example write program to delete number from given location in an array #include #include int main(int inposarr[ ]clrscr()printf("\ enter the number of elements in the array ")scanf("% "& )for( = ; < ; ++printf("\ arr[% " )scanf("% "&arr[ ])printf("\nenter the position from which the number has to be deleted ")scanf("% "&pos)for( =posi< - ; ++arr[iarr[ + ] --printf("\ the array after deletion is ")for( = ; < ; ++printf("\ arr[% % "iarr[ ])getch()return output enter the number of elements in the array arr[ arr[ arr[ arr[ arr[ enter the position from which the number has to be deleted the array after deletion is arr[ arr[ arr[ arr[ write program to delete number from an array that is already sorted in ascending order #include #include int main(int injnumarr[ ]clrscr()printf("\ enter the number of elements in the array ")scanf("% "& )for( = ; < ; ++printf("\ arr[% " )scanf("% "&arr[ ])printf("\ enter the number to be deleted ")scanf("% "&num)
24,302
data structures using for( = ; < ; ++if(arr[ =numfor( =ij< - ; ++arr[jarr[ + ] - printf("\ the array after deletion is ")for( = ; < ; ++printf("\ arr[% % "iarr[ ])getch()return output enter the number of elements in the array arr[ arr[ arr[ arr[ arr[ enter the number to be deleted the array after deletion is arr[ arr[ arr[ arr[ merging two arrays merging two arrays in third array means first copying the contents of the first array into the third array and then copying the contents of the second array into the third array hencethe merged array contains the contents of the first array followed by the contents of the second array if the arrays are unsortedthen merging the arrays is very simpleas one just needs to copy the contents of one array into another but merging is not trivial task when the two arrays are sorted and the merged array also needs to be sorted let us first discuss the merge operation on unsorted arrays this operation is shown in fig array array array figure merging of two unsorted arrays programming example write program to merge two unsorted arrays #include #include int main(
24,303
int arr [ ]arr [ ]arr [ ]int in mindex= clrscr()printf("\ enter the number of elements in array ")scanf("% "& )printf("\ \ enter the elements of the first array")for( = ; < ; ++printf("\ arr [% " )scanf("% "&arr [ ])printf("\ enter the number of elements in array ")scanf("% "& )printf("\ \ enter the elements of the second array")for( = ; < ; ++printf("\ arr [% " )scanf("% "&arr [ ]) + for( = ; < ; ++arr [indexarr [ ]index++for( = ; < ; ++arr [indexarr [ ]index++printf("\ \ the merged array is")for( = ; < ; ++printf("\ arr[% % "iarr [ ])getch()return output enter the number of elements in array enter the elements of the first array arr [ arr [ arr [ enter the number of elements in array enter the elements of the second array arr [ arr [ arr [ the merged array is arr[ arr[ arr[ arr[ arr[ arr[
24,304
data structures using if we have two sorted arrays and the resultant merged array also needs to be sorted onethen the task of merging the arrays becomes little difficult the task of merging can be explained using fig array array array figure merging of two sorted arrays figure shows how the merged array is formed using two sorted arrays herewe first compare the st element of array with the st element of array and then put the smaller element in the merged array since we put as the first element in the merged array we then compare the nd element of the second array with the st element of the first array since now is stored as the second element of the merged array nextthe nd element of the first array is compared with the nd element of the second array since we store as the third element of the merged array nowwe will compare the nd element of the first array with the rd element of the second array because we store as the th element of the merged array this procedure will be repeated until elements of both the arrays are placed in the right location in the merged array programming example write program to merge two sorted arrays #include #include int main(int arr [ ]arr [ ]arr [ ]int in mindex= int index_first index_second clrscr()printf("\ enter the number of elements in array ")scanf("% "& )printf("\ \ enter the elements of the first array")for( = ; < ; ++printf("\ arr [% " )scanf("% "&arr [ ])printf("\ enter the number of elements in array ")scanf("% "& )printf("\ \ enter the elements of the second array")for( = ; < ; ++printf("\ arr [% " )scanf("% "&arr [ ]) + while(index_first &index_second
24,305
if(arr [index_first]<arr [index_second]arr [indexarr [index_first]index_first++else arr [indexarr [index_second]index_second++index++/if elements of the first array are over and the second array has some elements if(index_first = while(index_second< arr [indexarr [index_second]index_second++index++/if elements of the second array are over and the first array has some elements else if(index_second = while(index_first< arr [indexarr [index_first]index_first++index++printf("\ \ the merged array is")for( = ; < ; ++printf("\ arr[% % "iarr [ ])getch()return output enter the number of elements in array enter the elements of the first array arr [ arr [ arr [ enter the number of elements in array enter the elements of the second array arr [ arr [ arr [ the merged array is arr[ arr[ arr[ arr[ arr[ arr[
24,306
data structures using passing arrays to functions like variables of other data typeswe can also pass an array to function in some situationsyou may want to pass individual elements of the arraywhile in other situationsyou may want to pass the entire array in this sectionwe will discuss both the cases look at fig which will help you understand the concept arrays for interfunction communication passing the entire array passing individual elements passing data values passing addresses figure one dimensional arrays for inter-function communication passing individual elements the individual elements of an array can be passed to function by passing either their data values or addresses passing data values individual elements can be passed in the same manner as we pass variables of any other data type the condition is just that the data type of the array element must match with the type of the function parameter look at fig (awhich shows the code to pass an individual array element by passing the data value calling function called function main(void func(int numprintf("% "num)int arr[ ={ }func(arr[ ])figure (apassing values of individual array elements to function in the above exampleonly one element of the array is passed to the called function this is done by using the index expression herearr[ evaluates to single integer value the called function hardly bothers whether normal integer variable is passed to it or an array value is passed passing addresses like ordinary variableswe can pass the address of an individual array element by preceding the indexed array element with the address operator thereforeto pass the address of the fourth element of the array to the called functionwe will write &arr[ howeverin the called functionthe value of the array element must be accessed using the indirection (*operator look at the code shown in fig (bwww allitebooks com
24,307
calling function called function main(void func(int *numprintf("% "*num)int arr[ ={ }func(&arr[ ]) figure (bpassing addresses of individual array elements to function passing the entire array we have discussed that in the array name refers to the first byte of the array in the memory the address of the remaining elements in the array can be calculated using the array name and the index value of the element thereforewhen we need to pass an entire array to functionwe can simply pass the name of the array figure illustrates the code which passes the entire array to the called function calling function called function main(void func(int arr[ ]int ifor( ; < ; ++printf("% "arr[ ])int arr[ ={ }func(arr)figure passing entire array to function function that accepts an array can declare the formal parameter in either of the two following ways func(int arr[])or func(int *arr)when we pass the name of an array to functionthe address of the zeroth element of the array is copied to the local pointer variable in the function when formal parameter is declared in function header as an arrayit is interpreted as pointer to variable and not as an array with this pointer variable you can access all the elements of the array by using the expressionarray_name index you can also pass the size of the array as another parameter to the function so for function that accepts an array as parameterthe declaration should be as follows func(int arr[]int )or func(int *arrint )it is not necessary to pass the whole array to function we can also pass part of the array known as sub-array pointer to sub-array is also an array pointer for exampleif we want to send the array starting from the third element then we can pass the address of the third element and the size of the sub-arrayi if there are elements in the arrayand we want to pass the array starting from the third elementthen only eight elements would be part of the sub-array so the function call can be written as func(&arr[ ] )note that in case we want the called function to make no changes to the arraythe array must be received as constant array by the called function this prevents any type of unintentional modifications of the array elements to declare an array as constant arraysimply add the keyword const before the data type of the array look at the following programs which illustrate the use of pointers to pass an array to function
24,308
data structures using programming examples write program to read an array of numbers and then find the smallest number #include #include void read_array(int arr[]int )int find_small(int arr[]int )int main(int num[ ]nsmallestclrscr()printf("\ enter the size of the array ")scanf("% "& )read_array(numn)smallest find_small(numn)printf("\ the smallest number in the array is % "smallest)getch()return void read_array(int arr[ ]int nint ifor( = ; < ; ++printf("\ arr[% " )scanf("% "&arr[ ])int find_small(int arr[ ]int nint small arr[ ]for( = ; < ; ++if(arr[ismallsmall arr[ ]return smalloutput enter the size of the array arr[ arr[ arr[ arr[ arr[ the smallest number in the array is write program to interchange the largest and the smallest number in an array #include #include void read_array(int my_array[]int)void display_array(int my_array[]int)void interchange(int arr[]int)int find_biggest_pos(int my_array[ ]int )int find_smallest_pos(int my_array[ ]int )int main(
24,309
int arr[ ]nclrscr()printf("\ enter the size of the array ")scanf("% "& )read_array(arrn)interchange(arrn)printf("\ the new array is")display_array(arr, )getch()return void read_array(int my_array[ ]int nint ifor( = ; < ; ++printf("\ arr[% " )scanf("% "&my_array[ ])void display_array(int my_array[ ]int nint ifor( = ; < ; ++printf("\ arr[% % "imy_array[ ])void interchange(int my_array[ ]int nint tempbig_possmall_posbig_pos find_biggest_pos(my_arrayn)small_pos find_smallest_pos(my_array, )temp my_array[big_pos]my_array[big_posmy_array[small_pos]my_array[small_postempint find_biggest_pos(int my_array[ ]int nint ilarge my_array[ ]pos= for( = ; < ; ++if (my_array[ilargelarge my_array[ ]pos=ireturn posint find_smallest_pos (int my_array[ ]int nint ismall my_array[ ]pos= for( = ; < ; ++if (my_array[ismallsmall my_array[ ]pos=
24,310
data structures using return posoutput enter the size of the array arr[ arr[ arr[ arr[ arr[ the new array is arr[ arr[ arr[ arr[ arr[ pointers and arrays arr[ arr[ arr[ arr[ arr[ figure memory representation of the concept of array is very much bound to the concept of pointer consider fig for exampleif we have an array declared asint arr[{ }arr[then in memory it would be stored as shown in fig array notation is form of pointer notation the name of the array is the starting address of the array in memory it is also known as the base address in other wordsbase address is the address of the first element in the array or the address of arr[ now let us use pointer variable as given in the statement below int *ptrptr &arr[ ]hereptr is made to point to the first element of the array execute the code given below and observe the output which will make the concept clear to you programming tip the name of an array is actually pointer that points to the first element of the array main(int arr[]={ , , , , }printf("\ address of array % % % "arr&arr[ ]&arr) arr[ arr[ arr[ arr[ arr[ ptr figure pointer pointing to the third element of the array programming tip an error is generated if an attempt is made to change the address of the array similarlywriting ptr &arr[ makes ptr to point to the third element of the array that has index figure shows ptr pointing to the third element of the array if pointer variable ptr holds the address of the first element in the arraythen the address of successive elements can be calculated by writing ptr+int *ptr &arr[ ]ptr++printf("\ the value of the second element of the array is % "*ptr)the printf(function will print the value because after being incremented ptr points to the next location one point to note here is that if is an integer variablethen ++adds to the value of but ptr
24,311
is pointer variableso when we write ptr+ithen adding gives pointer that points elements further along an array than the original pointer since ++ptr and ptr+are both equivalent to ptr+ incrementing pointer using the unary +operatorincrements the address it stores by the amount given by sizeof(typewhere type is the data type of the variable it points to ( for an integerfor exampleconsider fig arr[ arr[ arr[ arr[ arr[ ptr figure pointer (ptrpointing to the fourth element of the array programming tip when an array is passed to functionwe are actually passing pointer to the function thereforein the function declaration you must declare pointer to receive the array name ptr arrif ptr originally points to arr[ ]then ptr+will make it to point to the next elementi arr[ this is shown in fig had this been character arrayevery byte in the memory would have been used to store an individual character ptr+would then add only byte to the address of ptr when using pointersan expression like arr[iis equivalent to writing *(arr+imany beginners get confused by thinking of array name as pointer for examplewhile we can write /ptr &arr[ we cannot write arr ptrthis is because while ptr is variablearr is constant the location at which the first element of arr will be stored cannot be changed once arr[has been declared thereforean array name is often known to be constant pointer to summarizethe name of an array is equivalent to the address of its first elementas pointer is equivalent to the address of the element that it points to thereforearrays and pointers use the same concept note arr[ ] [arr]*(arr+ )*( +arrgives the same value look at the following code which modifies the contents of an array using pointer to an array int main(int arr[]={ , , , , }int *ptriptr=&arr[ ]*ptr - *(ptr+ *(ptr- printf("\ array is")for( = ; < ; ++printf(% "*(arr+ ))return output array is -
24,312
data structures using in we can add or subtract an integer from pointer to get new pointerpointing somewhere other than the original position also permits addition and subtraction of two pointer variables for examplelook at the code given below int main(int arr[]={ , , , , , , , , }int *ptr *ptr ptr arrptr arr+ printf("% "ptr -ptr )return output in the codeptr and ptr are pointers pointing to the elements of the same array we may subtract two pointers as long as they point to the same array herethe output is because there are two elements between ptr and ptr in the array arr both the pointers must point to the same array or one past the end of the arrayotherwise this behaviour cannot be defined moreoverc also allows pointer variables to be compared with each other obviouslyif two pointers are equalthen they point to the same location in the array howeverif one pointer is less than the otherit means that the pointer points to some element nearer to the beginning of the array like with other variablesrelational operators (>=etc can also be applied to pointer variables programming example write program to display an array of given numbers #include int main(int arr[]={ , , , , , , , , }int *ptr *ptr ptr arrptr &arr[ ]while(ptr <=ptr printf("% "*ptr )ptr ++return output arrays of pointers an array of pointers can be declared as int *ptr[ ]the above statement declares an array of pointers where each of the pointer points to an integer variable for examplelook at the code given below
24,313
int *ptr[ ]int ptr[ &pptr[ &qptr[ &rptr[ &sptr[ &tcan you tell what will be the output of the following statementprintf("\ % "*ptr[ ])the output will be because ptr[ stores the address of integer variable and *ptr[ will therefore print the value of that is now look at another code in which we store the address of three individual arrays in the array of pointersint main(int arr []={ , , , , }int arr []={ , , , , }int arr []={ , , , , }int *parr[ {arr arr arr }int ifor( ; < ; ++printf(>*parr[ ])return output surprised with this outputtry to understand the concept in the for loopparr[ stores the base address of arr (or&arr [ ]so writing *parr[ will print the value stored at &arr [ same is the case with *parr[ and *parr[ two-dimensional arrays till nowwe have only discussed one-dimensional arrays one-dimensional arrays are organized linearly in only one direction but at timeswe need to store data in the form of grids or tables herethe concept of single-dimension arrays is extended to incorporate two-dimensional data structures two-dimensional array is specified using two subscripts where the first subscript denotes the row and the second denotes the column the compiler treats two-dimensional array as an array of one-dimensional arrays figure shows two-dimensional array which can be viewed as an array of arrays declaring two-dimensional arrays any array must be declared before being used the declaration statement tells the compiler the name of the arraythe data type of each element in the arrayand the size of each dimension two-dimensional array is declared asfirst dimension data_type array_name[row_size][column_size]second dimension figure two-dimensional array thereforea two-dimensional yn array is an array that contains yn data elements and each element is accessed using two subscriptsi and jwhere < and < for exampleif we want to store the marks obtained by three students in five different subjectswe can declare twodimensional array asint marks[ ][ ]
24,314
data structures using in the above statementa two-dimensional array called marks has been declared that has ( rows and ( columns the first element of the array is denoted by marks[ ][ ]the second element as marks[ ][ ]and so on heremarks[ ][ stores the marks obtained by the first student in the first subjectmarks[ ][ stores the marks obtained by the second student in the first subject the pictorial form of two-dimensional array is shown in fig rows columns row row row col col col col col marks]marks][ marks][ marks][ marks][ marks[ ]marks[ ][ marks[ ][ marks[ ][ marks[ ][ marks[ ]marks[ ][ marks[ ][ marks[ ][ marks[ ][ figure two-dimensional array hencewe see that array is treated as collection of arrays each row of array corresponds to array consisting of elementswhere is the number of columns to understand thiswe can also see the representation of two-dimensional array as shown in fig marksmarksmarks[ marks[ marks[ marks[ marks[ marksmarks[ marks[ marks[ marks[ marks[ marksmarks[ marks[ marks[ marks[ figure representation of two-dimensional array marks[ ][ although we have shown rectangular picture of two-dimensional arrayin the memorythese elements actually will be stored sequentially there are two ways of storing two-dimensional array in the memory the first way is the row major order and the second is the column major order let us see how the elements of array are stored in row major order herethe elements of the first row are stored before the elements of the second and third rows that isthe elements of the array are stored row by row where elements of the first row will occupy the first locations this is illustrated in fig ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , figure elements of array in row major order howeverwhen we store the elements in column major orderthe elements of the first column are stored before the elements of the second and third column that isthe elements of the array are stored column by column where elements of the first column will occupy the first locations this is illustrated in fig ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , figure elements of array in column major order
24,315
in one-dimensional arrayswe have seen that the computer does not keep track of the address of every element in the array it stores only the address of the first element and calculates the address of other elements from the base address (address of the first elementsame is the case with two-dimensional array here alsothe computer stores the base addressand the address of the other elements is calculated using the following formula if the array elements are stored in column major orderaddress( [ ][ ]base_address { ( )and if the array elements are stored in row major orderaddress( [ ][ ]base_address { ( )where is the number of bytes required to store one elementn is the number of columnsm is the number of rowsand and are the subscripts of the array element example consider two-dimensional array marks which has its base address and the size of an element now compute the address of the elementmarks[ ] assuming that the elements are stored in row major order solution address( [ ][ ]base_address { ( ( )address(marks[ ][ ] { ( ( ) { ( ( initializing two-dimensional arrays like in the case of other variablesdeclaring two-dimensional array only reserves space for the array in the memory no values are stored in it two-dimensional array is initialized in the same way as one-dimensional array is initialized for exampleint marks[ ][ ]={ }note that the initialization of two-dimensional array is done row by row the above statement can also be written asint marks[ ][ ]={{ , , },{ }}the above two-dimensional array has two rows and three columns firstthe elements in the first row are initialized and then the elements of the second row are initialized thereforemarks[ ][ marks[ ][ marks[ ][ marks[ ][ marks[ ][ marks[ ][ in the above exampleeach row is defined as one-dimensional array of three elements that are enclosed in braces note that the commas are used to separate the elements in the row as well as to separate the elements of two rows in case of one-dimensional arrayswe have discussed that if the array is completely initializedwe may omit the size of the array the same concept can be applied to two-dimensional arrayexcept that only the size of the first dimension can be omitted thereforethe declaration statement given below is valid int marks[][ ]={{ , , },{ }}in order to initialize the entire two-dimensional array to zerossimply specify the first value as zero that isint marks[ ][ { }
24,316
data structures using the individual elements of two-dimensional array can be initialized using the assignment operator as shown here marks[ ][ or marks[ ][ marks[ ][ accessing the elements of two-dimensional arrays the elements of array are stored in contiguous memory locations in case of one-dimensional arrayswe used single for loop to vary the index in every passso that all the elements could be scanned since the two-dimensional array contains two subscriptswe will use two for loops to scan the elements the first for loop will scan each row in the array and the second for loop will scan individual columns for every row in the array look at the programs which use two for loops to access the elements of array programming examples write program to print the elements of array #include #include int main(int arr[ ][ { , }int ijfor( = ; < ; ++printf("\ ")for( = ; < ; ++printf("% \ "arr[ ][ ])return output write program to generate pascal' triangle #include #include int main(int arr[ ][ ]={ }int row= colijarr[ ][ arr[ ][ arr[ ][ while(row < arr[row][ for(col col <rowcol++arr[row][colarr[row- ][col- arr[row- ][col]row++for( = < ++printf("\ ")for( = <=ij++
24,317
getch()return printf("\ % "arr[ ][ ])output in small company there are five salesmen each salesman is supposed to sell three products write program using array to print (ithe total sales by each salesman and (iitotal sales of each item #include #include int main(int sales[ ][ ]ijtotal_sales= //input data printf("\ enter the data")printf("\ *****************")for( = < ++printf("\ enter the sales of items sold by salesman % " + )for( = < ++scanf("% "&sales[ ][ ])/print total sales by each salesman for( = < ++total_sales for( = < ++total_sales +sales[ ][ ]printf("\ total sales by salesman % % " + total_sales)/total sales of each item for( = < ++)/for each item total_sales= for( = < ++)/for each salesman total_sales +sales[ ][ ]printf("\ total sales of item % % " + total_sales)getch()return output enter the data ****************enter the sales of items sold by salesman enter the sales of items sold by salesman enter the sales of items sold by salesman enter the sales of items sold by salesman
24,318
data structures using enter the sales of items sold by salesman total sales by salesman total sales by salesman total sales by salesman total sales by salesman total sales by salesman total sales of item total sales of item total sales of item write program to read array marks which stores the marks of five students in three subjects write program to display the highest marks in each subject #include #include int main(int marks[ ][ ]ijmax_marksfor( = < ++printf("\ enter the marks obtained by student % ", + )for( = < ++printf("\ marks[% ][% "ij)scanf("% "&marks[ ][ ])for( = < ++max_marks - for( = < ++if(marks[ ][ ]>max_marksmax_marks marks[ ][ ]printf("\ the highest marks obtained in the subject % % " + max_marks)getch()return output enter the marks obtained by student marks[ ][ marks[ ][ marks[ ][ enter the marks obtained by student marks[ ][ marks[ ][ marks[ ][ enter the marks obtained by student marks[ ][ marks[ ][ marks[ ][ enter the marks obtained by student marks[ ][ marks[ ][ marks[ ][ enter the marks obtained by student
24,319
marks[ ][ marks[ ][ marks[ ][ the highest marks obtained in the subject the highest marks obtained in the subject the highest marks obtained in the subject operations on two-dimensional arrays two-dimensional arrays can be used to implement the mathematical concept of matrices in mathematicsa matrix is grid of numbersarranged in rows and columns thususing twodimensional arrayswe can perform the following operations on an mxn matrixtranspose transpose of an yn matrix is given as ym matrix bwhere bi, aj, sum two matrices that are compatible with each other can be added togetherstoring the result in the third matrix two matrices are said to be compatible when they have the same number of rows and columns the elements of two matrices can be added by writingci, ai, bi, difference two matrices that are compatible with each other can be subtractedstoring the result in the third matrix two matrices are said to be compatible when they have the same number of rows and columns the elements of two matrices can be subtracted by writingci, ai, bi, product two matrices can be multiplied with each other if the number of columns in the first matrix is equal to the number of rows in the second matrix thereforem yn matrix can be multiplied with yq matrix if = the dimension of the product matrix is yq the elements of two matrices can be multiplied by writingci, ai,kbk, for to programming examples write program to read and display matrix #include #include int main(int ijmat[ ][ ]clrscr()printf("\ enter the elements of the matrix ")for( = ; < ; ++for( = ; < ; ++scanf("% ",&mat[ ][ ])printf("\ the elements of the matrix are ")for( = ; < ; ++printf("\ ")for( = ; < ; ++
24,320
data structures using printf("\ % ",mat[ ][ ])return output enter the elements of the matrix the elements of the matrix are write program to transpose matrix #include #include int main(int ijmat[ ][ ]transposed_mat[ ][ ]clrscr()printf("\ enter the elements of the matrix ")for( = ; < ; ++for( = ; < ; ++scanf("% "&mat[ ][ ])printf("\ the elements of the matrix are ")for( = ; < ; ++printf("\ ")for( = ; < ; ++printf("\ % "mat[ ][ ])for( = ; < ; ++for( = ; < ; ++transposed_mat[ ][jmat[ ][ ]printf("\ the elements of the transposed matrix are ")for( = ; < ; ++printf("\ ")for( = ; < ; ++printf("\ % ",transposed_ mat[ ][ ])return output enter the elements of the matrix the elements of the matrix are the elements of the transposed matrix are
24,321
write program to input two yn matrices and then calculate the sum of their corresponding elements and store it in third yn matrix #include #include int main(int ijint rows cols rows cols rows_sumcols_sumint mat [ ][ ]mat [ ][ ]sum[ ][ ]clrscr()printf("\ enter the number of rows in the first matrix ")scanf("% ",&rows )printf("\ enter the number of columns in the first matrix ")scanf("% ",&cols )printf("\ enter the number of rows in the second matrix ")scanf("% ",&rows )printf("\ enter the number of columns in the second matrix ")scanf("% ",&cols )if(rows !rows |cols !cols printf("\ number of rows and columns of both matrices must be equal")getch()exit()rows_sum rows cols_sum cols printf("\ enter the elements of the first matrix ")for( = ; <rows ; ++for( = ; <cols ; ++scanf("% ",&mat [ ][ ])printf("\ enter the elements of the second matrix ")for( = ; <rows ; ++for( = ; <cols ; ++scanf("% ",&mat [ ][ ])for( = ; <rows_sum; ++for( = ; <cols_sum; ++sum[ ][jmat [ ][jmat [ ][ ]printf("\ the elements of the resultant matrix are ")for( = ; <rows_sum; ++printf("\ ")for( = ; <cols_sum; ++printf("\ % "sum[ ][ ])return
24,322
data structures using output enter the number of rows in the first matrix enter the number of columns in the first matrix enter the number of rows in the second matrix enter the number of columns in the second matrix enter the elements of the first matrix enter the elements of the second matrix the elements of the resultant matrix are write program to multiply two yn matrices #include #include int main(int ijkint rows cols rows cols res_rowsres_colsint mat [ ][ ]mat [ ][ ]res[ ][ ]clrscr()printf("\ enter the number of rows in the first matrix ")scanf("% ",&rows )printf("\ enter the number of columns in the first matrix ")scanf("% ",&cols )printf("\ enter the number of rows in the second matrix ")scanf("% ",&rows )printf("\ enter the number of columns in the second matrix ")scanf("% ",&cols )if(cols !rows printf("\ the number of columns in the first matrix must be equal to the number of rows in the second matrix")getch()exit()res_rows rows res_cols cols printf("\ enter the elements of the first matrix ")for( = ; <rows ; ++for( = ; <cols ; ++scanf("% ",&mat [ ][ ])printf("\ enter the elements of the second matrix ")for( = ; <rows ; ++for( = ; <cols ; ++scanf("% ",&mat [ ][ ])for( = ; <res_rows; ++for( = ; <res_cols; ++
24,323
res[ ][ ]= for( = <res_cols; ++res[ ][ +mat [ ][kmat [ ][ ]printf("\ the elements of the product matrix are ")for( = ; <res_rows; ++printf("\ ")for( = ; <res_cols; ++printf("\ % ",res[ ][ ])return output enter the number of rows in the first matrix enter the number of columns in the first matrix enter the number of rows in the second matrix enter the number of columns in the second matrix enter the elements of the first matrix enter the elements of the second matrix the elements of the product matrix are passing two-dimensional arrays to functions there are three ways of passing two-dimensional array to function firstwe can pass individual elements of the array this is exactly the same as passing an element of one-dimensional array secondwe can pass single row of the two-dimensional array this is equivalent to passing the entire one-dimensional array to function that has already been discussed in previous section thirdwe can pass the entire two-dimensional array to the function figure shows the three ways of using two-dimensional arrays for inter-functon communication array for interfunction communication passing individual elements passing row passing the entire arrary figure arrays for inter-function communication passing row row of two-dimensional array can be passed by indexing the array name with the row number look at fig which illustrates how single row of two-dimensional array can be passed to the called function
24,324
data structures using calling function called function main(void func(int arr[]int ifor( ; < ; ++printf("% "arr[ )int arr[ ][ ({ }{ })func(arr[ ])figure passing row of array to function passing the entire array to pass two-dimensional array to functionwe use the array name as the actual parameter (the way we did in case of arrayhoweverthe parameter in the called function must indicate that the array has two dimensions look at the following program which passes entire array to function programming example write program to fill square matrix with value zero on the diagonals on the upper right triangleand - on the lower left triangle #include #include void read_matrix(int mat[ ][ ]int)void display_matrix(int mat[ ][ ]int)int main(int rowint mat [ ][ ]clrscr()printf("\ enter the number of rows and columns of the matrix:")scanf("% "&row)read_matrix(mat row)display_matrix(mat row)getch()return void read_matrix(int mat[ ][ ]int rint ijfor( = <ri++for( = <rj++if( ==jmat[ ][ else if( >jmat[ ][ - else mat[ ][ void display_matrix(int mat[ ][ ]int rint ij
24,325
for( = <ri++printf("\ ")for( = <rj++printf("\ % "mat[ ][ ])output enter the number of rows and columns of the matrix - pointers and two-dimensional arrays consider two-dimensional array declared as int mat[ ][ ]to declare pointer to two-dimensional arrayyou may write int **ptr here int **ptr is an array of pointers (to one-dimensional arrays)while int mat[ ][ is array they are not the same type and are not interchangeable individual elements of the array mat can be accessed using eithermat[ ][jor *(*(mat ijor *(mat[ ]+ )to understand more fully the concept of pointerslet us replace *(multi rowwith so the expression *(*(mat ijbecomes *( colusing pointer arithmeticwe know that the address pointed to by ( value ofx col must be greater than the address col by an amount equal to sizeof(intsince mat is two-dimensional arraywe know that in the expression multi row as used abovemulti row must increase in value by an amount equal to that needed to point to the next rowwhich in this case would be an amount equal to cols sizeof(intthusin case of two-dimensional arrayin order to evaluate expression (for row major array)we must know total of values the address of the first element of the arraywhich is given by the name of the arrayi mat in our case the size of the type of the elements of the arrayi size of integers in our case the specific index value for the row the specific index value for the column note that int (*ptr)[ ]declares ptr to be pointer to an array of integers this is different from int *ptr[ ]which would make ptr the name of an array of pointers to type int you must be thinking how pointer arithmetic works if you have an array of pointers for exampleint arr[ int *ptr arr
24,326
data structures using in this casearr has type int *since all pointers have the same sizethe address of ptr can be calculated asaddr(ptr iaddr(ptr[sizeof(int *iaddr(ptr[ isince arr has type int **arr[ &arr[ ][ ]arr[ &arr[ ][ ]and in generalarr[ &arr[ ][ according to pointer arithmeticarr arr[ ]yet this skips an entire row of elementsi it skips complete bytes ( elements each of bytes sizethereforeif arr is address then arr is address to summarize&arr[ ][ ]arr[ ]arrand &arr[ point to the base address &arr[ ][ points to arr[ ][ arr[ points to arr[ ][ arr points to arr[ ][ &arr[ points to arr[ ][ to concludea two-dimensional array is not the same as an array of pointers to arrays actually two-dimensional array is declared asint (*ptr)[ here ptr is pointer to an array of elements the parentheses are not optional in the absence of these parenthesesptr becomes an array of pointersnot pointer to an array of ints look at the code given below which illustrates the use of pointer to two-dimensional array #include int main(int arr[ ][ ]={{ , }{ , }}int (*parr)[ ]parr arrfor( ++for( ; ++printf(% "(*(parr+ ))[ ])return output the golden rule to access an element of two-dimensional array can be given as arr[ ][ (*(arr+ ))[ *((*arr+ ))+ *(arr[ ]+jthereforearr[ ][ *(arr)[ *((*arr)+ *(arr[ ]+ arr[ ][ (*(arr+ ))[ *((*(arr+ ))+ *(arr[ ]+ if we declare an array of pointers usingif we declare pointer to an array usingdata_type *array_name[size]data_type (*array_name)[size]here size represents the number of rows and the space for columns that can be dynamically allocated here represents the number of columns and the space for rows that may be dynamically allocated (refer appendix to see how memory is dynamically allocated
24,327
programming example write program to read and display matrix #include #include void display(int (*)[ ])int main(int ijmat[ ][ ]clrscr()printf("\ enter the elements of the matrix")for( = ; < ; ++for( ++scanf("% "&mat[ ][ ])display(mat)return void display(int (*mat)[ ]int ijprintf("\ the elements of the matrix are")for( ++printf("\ ")for( = ; < ; ++printf("\ % ",*(*(mat )+ ))output enter the elements of the matrix the elements of the matrix are note double pointer cannot be used as array thereforeit is wrong to declare'int **matand then use 'matas array these are two very different data types used to access different locations in memory so running such code may abort the program with 'memory access violationerror array is not equivalent to double pointer 'pointer to pointer of tcannot serve as ' array of tthe array is equivalent to pointer to row of tand this is very different from pointer to pointer of when double pointer that points to the first element of an array is used with the subscript notation ptr[ ][ ]it is fully dereferenced two times and the resulting object will have an address equal to the value of the first element of the array multi-dimensional arrays multi-dimensional array in simple terms is an array of arrays as we have one index in onedimensional arraytwo indices in two-dimensional arrayin the same waywe have indices in an -dimensional array or multi-dimensional array converselyan -dimensional array is specified
24,328
data structures using using indices an -dimensional ym ym yymn array is collection of ym ym yymn elements in multi-dimensional arraya particular element is specified by using subscripts as [ ][ ][ [in]where < < < in <mn multi-dimensional array can contain as many indices as needed and as the requirement of memory increases with the number of indices used howeverin practicewe hardly use more than three indices in any program figure shows three-dimensional array the array has three pagesfour rowsand two columns second dimension (columnsfirst dimension (rowsq page page page third dimension figure three-dimensional array note multi-dimensional array is declared and initialized the same way we declare and initialize oneand two-dimensional arrays example consider three-dimensional array defined as int [ ][ ][ calculate the number of elements in the array alsoshow the memory representation of the array in the row major order and the column major order solution three-dimensional array consists of pages each pagein turncontains rows and columns ( , , ( , , ( , , ( , , ( , , ( , , ( , , ( , , ( , , ( , , ( , , ( , , (arow major order ( , , ( , , ( , , ( , , ( , , ( , , ( , , ( , , ( , , ( , , ( , , ( , , (bcolumn major order the three-dimensional array will contain elements
24,329
programming example write program to read and display array #include #include int main(int array[ ][ ][ ]ijkclrscr()printf("\ enter the elements of the matrix")for( = ; < ; ++for( = ; < ; ++for( = ; < ; ++scanf("% "&array[ ][ ][ ])printf("\ the matrix is ")for( = ; < ; ++printf("\ ")for( = ; < ; ++printf("\ ")for( = ; < ; ++printf("\ array[% ][% ][% % "ijkarray[ [ ][ ])getch()return output enter the elements of the matrix the matrix is arr[ ][ ][ arr[ ][ ][ arr[ ][ ][ arr[ ][ ][ arr[ ][ ][ arr[ ][ ][ arr[ ][ ][ arr[ ][ ][ pointers and three-dimensional arrays in this sectionwe will see how pointers can be used to access three-dimensional array we have seen that pointer to one-dimensional array can be declared asint arr[]={ , , , , }int *parrparr arrsimilarlypointer to two-dimensional array can be declared asint arr[ ][ ]={{ , },{ , }}int (*parr)[ ]parr arr
24,330
data structures using pointer to three-dimensional array can be declared asint arr[ ][ ][ ]={ , , , , , , , }int (*parr)[ ][ ]parr arrwe can access an element of three-dimensional array by writingarr[ ][ ][ *(*(*(arr+ )+ )+kprogramming example write program which illustrates the use of pointer to three-dimensional array #include #include int main(int , ,kint arr[ ][ ][ ]int (*parr)[ ][ ]arrclrscr()printf("\ enter the elements of array")for( ++for( ++for( ++scanf("% "&arr[ ][ ][ ])printf("\ the elements of the array are")for( ++for( ++for( ++printf("% "*(*(*(parr+ )+ )+ ))getch()return output enter the elements of array the elements of the array are note in the printf statementyou could also have used instead of *(*(*(parr+ )+ )+ ) sparse matrices sparse matrix is matrix that has large number of elements with zero value in order to efficiently utilize the memoryspecialized algorithms and data structures that take advantage of the sparse structure should be used if we apply the operations using standard matrix structures and algorithms to sparse matricesthen the execution will slow down and the matrix will consume large amount of memory sparse data can be easily compressedwhich in turn can significantly reduce memory usage
24,331
- - - figure - lower-triangular matrix there are two types of sparse matrices in the first type of sparse matrixall elements above the main diagonal have zero value this type of sparse matrix is also called (lowertriagonal matrix because if you see it pictoriallyall the elements with non-zero value appear below the diagonal in lower triangular matrixai, where an yn lower-triangular matrix has one non-zero element in the first rowtwo non-zero elements in the second row and likewise non-zero elements in the nth row look at fig which shows lower-triangular matrix to store lower-triangular matrix efficiently in the memorywe can use one-dimensional array which stores only non-zero elements the mapping between two-dimensional matrix and one-dimensional array can be done in any one of the following ways(arow-wise mapping--here the contents of array [will be { - - - figure upper-triangular (bcolumn-wise mapping--here the contents of array [will be matrix { - - - in an upper-triangular matrixai, where an yn upper-triangular matrix has non-zero elements in the first rown- non-zero elements in the second row and likewise one non-zero element in the nth row look at fig which shows an upper-triangular matrix there is another variant of sparse matrixin which elements with non-zero value can appear only on the diagonal or immediately above or below the diagonal this type of matrix is also called tri-diagonal matrix figure tri-diagonal hence in tridiagonal matrixai, where | in tridiagonal matrix matrixif elements are present on (athe main diagonalit contains non-zero elements for = in allthere will be elements (bbelow the main diagonalit contains non-zero elements for = + in allthere will be - elements (cabove the main diagonalit contains non-zero elements for = - in allthere will be - elements figure shows tri-diagonal matrix to store tri-diagonal matrix efficiently in the memorywe can use one-dimensional array that stores only non-zero elements the mapping between two-dimensional matrix and one-dimensional array can be done in any one of the following ways(arow-wise mapping--here the contents of array [will be { (bcolumn-wise mapping--here the contents of array [will be { (cdiagonal-wise mapping--here the contents of array [will be { applications of arrays arrays are frequently used in cas they have number of useful applications these applications are arrays are widely used to implement mathematical vectorsmatricesand other kinds of rectangular tables many databases include one-dimensional arrays whose elements are records arrays are also used to implement other data structures such as stringsstacksqueuesheapsand hash tables we will read about these data structures in the subsequent arrays can be used for sorting elements in ascending or descending order
24,332
data structures using points to remember an array is collection of elements of the same data type the elements of an array are stored in consecutive memory locations and are referenced by an index (also known as the subscriptthe index specifies an offset from the beginning of the array to the element being referenced declaring an array means specifying three parametersdata typenameand its size the length of an array is given by the number of elements stored in it there is no single function that can operate on all the elements of an array to access all the elementswe must use loop the name of an array is symbolic reference to the address of the first byte of the array thereforewhenever we use the array namewe are actually referring to the first byte of that array considers two-dimensional array as an array of one-dimensional arrays two-dimensional array is specified using two subscripts where the first subscript denotes the row and the second subscript denotes the column of the array using two-dimensional arrayswe can perform the different operations on matricestransposeadditionsubtractionmultiplication multi-dimensional array is an array of arrays like we have one index in one-dimensional arraytwo indices in two-dimensional arrayin the same way we have indices in an -dimensional or multidimensional array converselyan -dimensional array is specified using indices multi-dimensional arrays can be stored in either row major order or column major order sparse matrix is matrix that has large number of elements with zero value there are two types of sparse matrices in the first typeall the elements above the main diagonal have zero value this type of sparse matrix is called lower-triangular matrix in the second typeall the elements below the main diagonal have zero value this type of sparse matrix is called an uppertriangular matrix there is another variant of sparse matrixin which elements with non-zero value can appear only on the diagonal or immediately above or below the diagonal this type of sparse matrix is called tridiagonal matrix exercises review questions what are arrays and why are they needed how is an array represented in the memory how is two-dimensional array represented in the memory what is the use of multi-dimensional arrays explain sparse matrix how are pointers used to access two-dimensional arrays why does storing of sparse matrices need extra considerationhow are sparse matrices stored efficiently in the computer' memory for an array declared as int arr[ ]calculate the address of arr[ ]if base(arr and consider two-dimensional array marks[ ][ having its base address as and the number of bytes per element of the array is nowcompute the address of the elementmarks[ ][ ]assuming that the elements are stored in row major order how are arrays related to pointers briefly explain the concept of array of pointers how can one-dimensional arrays be used for interfunction communication consider two-dimensional array arr[ ][ which has base address and the number of bytes per element of the array nowcompute the address of the element arr[ ][ assuming that the elements are stored in column major order consider the array given belownameadam name[ charles name[ dicken name[ esha georgia name[ name[ hillary name[ mishael
24,333
(ahow many elements would be moved if the name andrew has to be added in it( (ii (iii (iv (bhow many elements would be moved if the name esha has to be deleted from it( (ii (iii (iv what happens when an array is initialized with (afewer initializers as compared to its size(bmore initializers as compared to its sizeprogramming exercises consider an array marks[ ][ which stores the marks obtained by students in subjects now write program to (afind the average marks obtained in each subject (bfind the average marks obtained by every student (cfind the number of students who have scored below in their average (ddisplay the scores obtained by every student write program that reads an array of integers display all the pairs of elements whose sum is write program to interchange the second element with the second last element write program that calculates the sum of squares of the elements write program to compute the sum and mean of the elements of two-dimensional array write program to read and display square (using functions write program that computes the sum of the elements that are stored on the main diagonal of matrix using pointers write program to add two matrix using pointers write program that computes the product of the elements that are stored on the diagonal above the main diagonal write program to count the total number of nonzero elements in two-dimensional array write program to input the elements of twodimensional array then from this arraymake two arrays--one that stores all odd elements of the two-dimensional array and the other that stores all even elements of the array write program to read two floating point number arrays merge the two arrays and display the resultant array in reverse order write program using pointers to interchange the second biggest and the second smallest number in the array write menu driven program to read and display yq yr matrix alsofind the sumtransposeand product of the two yq yr matrices write program that reads matrix and displays the sum of its diagonal elements write program that reads matrix and displays the sum of the elements above the main diagonal (hintcalculate the sum of elements aij where < write program that reads matrix and displays the sum of the elements below the main diagonal (hintcalculate the sum of elements aij where > write program that reads square matrix of size yn write function int isuppertriangular (int [][]int nthat returns if the matrix is upper triangular (hintarray is upper triangular if aij and > write program that reads square matrix of size yn write function int islowertriangular (int [][]int nthat returns if the matrix is lower triangular (hintarray is lower triangular if aij and < write program that reads square matrix of size yn write function int issymmetric (int [][]int nthat returns if the matrix is symmetric (hintarray is symmetric if aij aji for all values of and write program to calculate xa yb where and are matrices and and write program to illustrate the use of pointer that points to array write program to enter number and break it into number of digits write program to delete all the duplicate entries from an array of integers write program to read floating point array update the array to insert new number at the specified location
24,334
data structures using multiple-choice questions if an array is declared as arr[{ , , , , }then what is the value of sizeof(arr[ ])( ( ( ( if an array is declared as arr[{ , , , , }then what is the value of arr[ ]( ( ( ( if an array is declared as double arr[ ]how many bytes will be allocated to it( ( ( ( if an array is declared as int arr[ ]how many elements can it hold( ( ( ( if an array is declared as int arr[ ][ ]how many elements can it store( ( ( ( given an integer array arr[]the ith element can be accessed by writing ( *(arr+ ( *( arr(carr[ (dall of these true or false an array is used to refer multiple memory locations having the same name an array name can be used as pointer loop is used to access all the elements of an array an array stores all its data elements in nonconsecutive memory locations lower bound is the index of the last element in an array merged array contains contents of the first array followed by the contents of the second array it is possible to pass an entire array as function argument arr[iis equivalent to writing *(arr+ array name is equivalent to the address of its last element mat[ ][jis equivalent to *(*(mat ij an array contains elements of the same data type when an array is passed to functionc passes the value for each element two-dimensional array contains data of two different types the maximum number of dimensions that an array can have is by defaultthe first subscript of the array is zero fill in the blanks each array element is accessed using the elements of an array are stored in memory locations an -dimensional array contains subscripts name of the array acts as declaring an array means specifying the and is the address of the first element in the array length of an array is given by the number of multi-dimensional arrayin simple termsis an an expression that evaluates to an value may be used as an index arr[ initializes the element of the array with value
24,335
strings learning objective in the last we discussed array of integers taking step furtherin this we will discuss array of characters commonly known as strings we will see how strings are storeddeclaredinitializedand accessed we will learn about different operations that can be performed on strings as well as about array of strings introduction nowadayscomputers are widely used for word processing applications such as creatinginsertingupdatingand modifying textual data besides thiswe need to search for particular pattern within textdelete itor replace it with another pattern sothere is lot that we as users do to manipulate the textual data in ca string is null-terminated character array this means that after the last charactera null character ('\ 'is stored to signify the end of the character array for exampleif we write char str["hello"then we are declaring an array that has five charactersnamelyhelland apart from these charactersa null character ('\ 'is stored at the end of the string sothe internal representation of the string becomes hello'\ to store string of length we need locations ( extra for the null characterthe name of the character array (or the stringis pointer to the beginning of the string figure shows the difference between character storage and string storage if we had declared str as char str[ "hello"then the null character will not be appended automatically to the character array this is because str can hold only characters and the characters in hello have already filled the space allocated to it
24,336
char str["hello"char ch ' ' \ end of string beginning of string here is character not string the character requires only one memory location char str[" "char str["" \ \ here is string not character the string requires two memory locations one to store the character and another to store the null character empty string although permits empty stringit does not allow an empty character figure difference between character storage and string storage str str[ str[ str[ str[ str[ \ figure memory representation of character array programming tip when allocating memory space for stringreserve space to hold the null character also like we use subscripts (also known as indexto access the elements of an arraywe can also use subscripts to access the elements of string the subscript starts with zero ( all the characters of string are stored in successive memory locations figure shows how str[is stored in the memory thusin simple termsa string is sequence of characters in fig etc are the memory addresses of individual characters for simplicitythe figure shows that is stored at memory location but in realitythe ascii code of character is stored in the memory and not the character itself soat address will be stored as the ascii code for is the statement char str["hello"declares constant stringas we have assigned value to it while declaring the string howeverthe general form of declaring string is char str[size]when we declare the string like thiswe can store size- characters in the array because the last character would be the null character for examplechar mesg[ ]can store maximum of characters till nowwe have only seen one way of initializing strings the other way to initialize string is to initialize it as an array of characters for examplechar str[{' '' '' '' '' ''\ '}in this examplewe have explicitly added the null character also observe that we have not mentioned the size of the string herethe compiler will automatically calculate the size based on the number of characters soin this example six memory locations will be reserved to store the string variablestr we can also declare string with size much larger than the number of elements that are initialized for exampleconsider the statement below char str [ "hello"
24,337
in such casesthe compiler creates an array of size stores "helloin it and finally terminates the string with null character rest of the elements in the array are automatically initialized to null now consider the following statementschar str[ ]str "hello"the above initialization statement is illegal in and would generate compile-time error because of two reasons firstthe array is initialized with more elements than it can store secondinitialization cannot be separated from declaration reading strings if we declare string by writing char str[ ]then str can be read by the user in three ways using scanf function using gets(functionand using getchar(),getch()or getche(function repeatedly strings can be read using scanf(by writing scanf("% "str)although the syntax of using scanf(function is well known and easy to usethe main pitfall of using this function is that the function terminates as soon as it finds blank space for exampleif the user enters hello worldthen the str will contain only hello this is because the moment blank space is encounteredthe string is terminated by the scanf(function you may also specify field width to indicate the maximum number of characters that can be read remember that extra characters are left unconsumed in the input buffer unlike intfloatand char values% format does not require the programming tip ampersand before the variable str using operand with string the next method of reading string is by using the gets(function variable in the scanf statement the string can be read by writing generates an error gets(str)gets(is simple function that overcomes the drawbacks of the scanf(function the gets(function takes the starting address of the string which will hold the input the string inputted using gets(is automatically terminated with null character strings can also be read by calling the getchar(function repeatedly to read sequence of single characters (unless terminating character is enteredand simultaneously storing it in character array as shown below = ;(ch getchar;/get character while(ch !'*'str[ich;/store the read character in str ++ch getchar();/get another character str[ '\ ';/terminate str with null character note that in this methodyou have to deliberately append the string with null character the other two functions automatically do this
24,338
data structures using writing strings strings can be displayed on the screen using the following three ways using printf(function using puts(functionand using putchar(function repeatedly strings can be displayed using printf(by writing printf("% "str)we use the format specifier % to output string observe carefully that there is no '&character used with the string variable we may also use width and precision specifications along with % the width specifies the minimum output field width if the string is shortthe extra space is either left padded or right padded negative width left pads short string rather than the default right justification the precision specifies the maximum number of characters to be displayedafter which the string is truncated for exampleprintf ("% "str)the above statement would print only the first three characters in total field of five characters also these characters would be right justified in the allocated width to make the string left justifiedwe must use minus sign for exampleprintf ("%- "str)note when the field width is less than the length of the stringthe entire string will be printed if the number of characters to be printed is specified as zerothen nothing is printed on the screen the next method of writing string is by using puts(function string can be displayed by writing puts(str)puts(is simple function that overcomes the drawbacks of the printf(function strings can also be written by calling the putchar(function repeatedly to print sequence of single characters = while(str[ !'\ 'putchar(str[ ]);/print the character on the screen ++ operations on strings in this sectionwe will learn about different operations that can be performed on strings step [initializeset step repeat step while str[ !null step set [end of loopstep set length step end figure algorithm to calculate the length of string finding length of string the number of characters in string constitutes the length of the string for examplelength(" programming is fun"will return note that even blank spaces are counted as characters in the string figure shows an algorithm that calculates the length of string in this algorithmi is used as an index for traversing string str to traverse each and every character of strwe increment the value of
24,339
once we encounter the null characterthe control jumps out of the while loop and the length is initialized with the value of note the library function strlen( which is defined in string returns the length of string programming example write program to find the length of string #include #include int main(char str[ ] lengthclrscr()printf("\ enter the string ")gets(strwhile(str[ !'\ ' ++length iprintf("\ the length of the string is % "length)getch(return output enter the string hello the length of the string is step [initializeset istep repeat step while str[ !null step if str[ >'aand str[ <' set upperstr[istr[ - else set upperstr[istr[ [end of ifset [end of loopstep set upperstr[inull step exit figure algorithm to convert characters of string into upper case converting characters of string into upperlower case we have already discussed that in the memory ascii codes are stored instead of the real values the ascii code for - varies from to and the ascii code for - ranges from to soif we have to convert lower case character into uppercasewe just need to subtract from the ascii value of the character and if we have to convert an upper case character into lower casewe need to add to the ascii value of the character figure shows an algorithm that converts the lower case characters of string into upper case note the library functions toupper(and tolower(which are defined in ctype convert character into upper and lower caserespectively in the algorithmwe initialize to zero using as the index of strwe traverse each character of str from step to if the character is in lower casethen it is converted into upper case by subtracting from its ascii value but if the character is already in upper casethen it is copied into the upperstr string finallywhen all the characters have been traverseda null character is appended to upperstr (as done in step
24,340
data structures using programming example write program to convert the lower case characters of string into upper case #include #include int main(char str[ ]upper_str[ ]int = clrscr()printf("\ enter the string :")gets(str)while(str[ !'\ 'if(str[ ]>=' &str[ ]<=' 'upper_str[istr[ else upper_str[istr[ ] ++upper_str[ '\ 'printf("\ the string converted into upper case is ")puts(upper_str)return output enter the string hello the string converted into upper case is hello appending string to another string appending one string to another string involves copying the contents of the source string at the end of the destination string for exampleif and are two stringsthen appending to means we have to add the contents of to sos is the source string and is the destination string the appending operation would leave the source string unchanged and the destination string figure shows an algorithm that appends two strings note the library function strcat( which is defined in string concatenates string to step [initializeset iand jstep repeat step while dest_str[ !null step set [end of loopstep repeat steps to while source_str[ !null step dest_str[isource_str[jstep set step set [end of loopstep set dest_str[inull step exit figure algorithm to append string to another string in this algorithmwe first traverse through the destination string to reach its endthat isreach the position where null character is encountered the characters of the source string are then
24,341
copied into the destination string starting from that position finallya null character is added to terminate the destination string programming example write program to append string to another string #include #include int main(char dest_str[ ]source_str[ ]int = = clrscr()printf("\ enter the source string ")gets(source_str)printf("\ enter the destination string ")gets(dest_str)while(dest_str[ !'\ ' ++while(source_str[ !'\ 'dest_str[isource_str[ ] ++ ++dest_str[ '\ 'printf("\ after appendingthe destination string is ")puts(dest_str)getch()return output enter the source string how are youenter the destination string helloafter appendingthe destination string is hellohow are youcomparing two strings if and are two stringsthen comparing the two strings will give either of the following results(as and are equal (bs > when in dictionary orders will come after (cs < when in dictionary orders precedes to compare the two stringseach and every character is compared from both the strings if all the characters are the samethen the two strings are said to be equal figure shows an algorithm that compares two strings note the library function strcmp( which is defined in string compares string with in this algorithmwe first check whether the two strings are of the same length if notthen there is no point in moving aheadas it straight away means that the two strings are not the same howeverif the two strings are of the same lengththen we compare character by character to check if all the characters are same if yesthen the variable same is set to elseif same then we check which string precedes the other in the dictionary order and print the corresponding message
24,342
data structures using figure algorithm to compare two strings programming example write program to compare two strings #include #include #include int main(char str [ ]str [ ]int = len = len = same= clrscr()printf("\ enter the first string ")gets(str )printf("\ enter the second string ")gets(str )len strlen(str )len strlen(str )if(len =len while( <len if(str [ =str [ ] ++else breakif( ==len same= printf("\ the two strings are equal")
24,343
if(len !=len printf("\ the two strings are not equal")if(same = if(str [ ]>str [ ]printf("\ string is greater than string ")else if(str [ ]<str [ ]printf("\ string is greater than string ")getch()return output enter the first string hello enter the second string hello the two strings are equal reversing string if "hello"then reverse of "ollehto reverse stringwe just need to swap the first character with the lastsecond character with the second last characterand so on figure shows an algorithm that reverses string note the library function strrev( which is defined in string reverses all the characters in the string except the null character in step is initialized to zero and is initialized to the length of the string - in step while loop is executed until all the characters of the string are accessed in step we swap the step [initializeset ijlength(str)- step repeat steps and while step swap(str( )str( )step set [end of loopstep exit figure algorithm to reverse string ith character of str with its jth character as resultthe first character of str will be replaced with its last characterthe second character will be replaced with the second last character of strand so on in step the value of is incremented and is decremented to traverse str in the forward and backward directionsrespectively programming example write program to reverse given string #include #include #include int main(char str[ ]reverse_str[ ]tempint = = clrscr()printf("\ enter the string ")gets(str) strlen(str)- while( jtemp str[ ]
24,344
data structures using str[jstr[ ]str[itempi++ --printf("\ the reversed string is ")puts(str)getch()return output enter the stringhi there the reversed string isereht ih extracting substring from string to extract substring from given stringwe need the following three parameters the main string the position of the first character of the substring in the given stringand the maximum number of characters/length of the substring for exampleif we have string str["welcome to the world of programming"thenstep [initializeset =mjstep repeat steps to while str[ !null and nstep set substr[jstr[istep set step set step set [end of loopstep set substr[jnull step exit figure algorithm to extract substring from the middle of string substring(str world figure shows an algorithm that extracts substring from the middle of string in this algorithmwe initialize loop counter to mthat isthe position from which the characters have to be copied steps to are repeated until characters have been copied with every character copiedwe decrement the value of the characters of the string are copied into another string called the substr at the enda null character is appended to substr to terminate the string programming example write program to extract substring from the middle of given string #include #include int main(char str[ ]substr[ ]int = = nmclrscr()printf("\ enter the main string ")gets(str)printf("\ enter the position from which to start the substring")scanf("% "& )printf("\ enter the length of the substring")scanf("% "& ) =mwhile(str[ !'\ & >
24,345
substr[jstr[ ] ++ ++ --substr[ '\ 'printf("\ the substring is ")puts(substr)getch()return output enter the main string hi there enter the position from which to start the substring enter the length of the substring the substring is th step [initializeset ijand kstep repeat steps to while text[ !null step if pos repeat while str[ !null new_str[jstr[kset = + set + [end of inner loopelse new_str[jtext[iset + [end of ifstep set + [end of outer loopstep set new_str[jnull step exit figure algorithm to insert string in given text at the specified position inserting string in the main string the insertion operation inserts string in the main text at the th position the general syntax of this operation is insert(textpositionstringfor exampleinsert("xyzxyz" "aaa""xyzaaaxyzfigure shows an algorithm to insert string in given text at the specified position this algorithm first initializes the indices into the string to zero from steps to the contents of new_str are built if is exactly equal to the position at which the substring has to be insertedthen the inner loop copies the contents of the substring into new_str otherwisethe contents of the text are copied into it programming example write program to insert string in the main text #include #include int main(char text[ ]str[ ]ins_text[ ]int = = = ,posclrscr()printf("\ enter the main text ")gets(text)printf("\ enter the string to be inserted ")gets(str)printf("\ enter the position at which the string has to be inserted")scanf("% "&pos)while(text[ ]'\ '
24,346
data structures using if( ==poswhile(str[ !'\ 'ins_text[jstr[ ] ++ ++else ins_text[jtext[ ] ++ ++ins_text[ '\ 'printf("\ the new string is ")puts(ins_text)getch()return output enter the main text newsman enter the string to be inserted paper enter the position at which the string has to be inserted the new string isnewspaperman pattern matching this operation returns the position in the string where the string pattern first occurs for exampleindex("welcome to the world of programming""world" howeverif the pattern does not exist in the stringthe index function returns figure shows an algorithm to find the index of the first occurrence of string within given text step [initializeset iand max length(text)-length(str)+ step repeat steps to while max step repeat step for to length(strstep if str[ !text[ ]then goto step [end of inner loopstep set index goto step step set + [end of outer loopstep set index - step exit figure algorithm to find the index of the first occurrence of string within given text in this algorithmmax is initialized to length(textlength(str for exampleif text contains 'welcome to programmingand the string contains 'world'in the main textwe will look for at the most characters because after that there is no scope left for the string to be present in the text steps to are repeated until each and every character of the text has been checked for the occurrence of the string within it in the inner loop in step we check the characters of string
24,347
with the characters of text to find if the characters are same if it is not the casethen we move to step where is incremented if the string is foundthen the index is initialized with ielse it is set to - for exampleif text welcome to the world string come in the first pass of the inner loopwe will compare come with welc character by character as and do not matchthe control will move to step and then elco will be compared with come in the fourth passcome will be compared with come we will be using the programming code of pattern matching operation in the operations that follow deleting substring from the main string the deletion operation deletes substring from given text we can write it as delete(textpositionlengthfor exampledelete("abcdxxxabcd" "abcdabcdstep [initializeset iand jstep repeat steps to while text[ !null step if = repeat while nset + set [end of inner loop[end of ifstep set new_str[jtext[istep set step set [end of outer loopstep set new_str[jnull step exit figure algorithm to delete substring from text figure shows an algorithm to delete substring from given text in this algorithmwe first initialize the indices to zero steps to are repeated until all the characters of the text are scanned if is exactly equal to (the position from which deletion has to be done)then the index of the text is incremented and is decremented is the number of characters that have to be deleted starting from position howeverif is not equal to mthen the characters of the text are simply copied into the new_str programming example write program to delete substring from text #include #include int main(char text[ ]str[ ]new_text[ ]int = = found= kn= copy_loop= clrscr()printf("\ enter the main text ")gets(text)printf("\ enter the string to be deleted ")gets(str)while(text[ ]!='\ ' = found= =iwhile(text[ ]==str[ &str[ ]!='\ ' ++ ++
24,348
data structures using if(str[ ]=='\ 'copy_loop=knew_text[ntext[copy_loop] ++copy_loop++ ++new_str[ ]='\ 'printf("\ the new string is ")puts(new_str)getch()return output enter the main text hellohow are youenter the string to be deleted how are youthe new string is hello replacing pattern with another pattern in string the replacement operation is used to replace the pattern by another pattern this is done by writing replace(textpattern pattern for example("aaabbbccc""bbb"" "aaaxccc ("aaabbbccc"" ""yyy")aaabbbcc step [initializeset pos index(textp step set text delete(textposlength( )step insert(textposp step exit figure algorithm to replace pattern with another pattern in the text in the second examplethere is no change as does not appear in the text figure shows an algorithm to replace pattern with another pattern in the text the algorithm is very simplewhere we first find the position posat which the pattern occurs in the textthen delete the existing pattern from that position and insert new pattern there programming example write program to replace pattern with another pattern in the text #include #include main(char str[ ]pat[ ]new_str[ ]rep_pat[ ]int = = kn= copy_loop= rep_index= clrscr()printf("\ enter the string ")gets(str)printf("\ enter the pattern to be replaced")gets(pat)printf("\ enter the replacing pattern")gets(rep_pat)while(str[ ]!='\ ' = , =iwhile(str[ ]==pat[ &pat[ ]!='\ '
24,349
++ ++if(pat[ ]=='\ 'copy_loop=kwhile(rep_pat[rep_index!='\ 'new_str[nrep_pat[rep_index]rep_index++ ++new_str[nstr[copy_loop] ++copy_loop++ ++new_str[ ]='\ 'printf("\ the new string is ")puts(new_str)getch()return output enter the string how are youenter the pattern to be replaced are enter the replacing pattern are the new string is how are you arrays of strings till now we have seen that string is an array of characters for exampleif we say char name["mohan"then the name is string (character arraythat has five characters nowsuppose that there are students in class and we need string that stores the names of all the students how can this be doneherewe need string of strings or an array of strings such an array of strings would store individual strings an array of strings is declared as char names[ ][ ]herethe first index will specify how many strings are needed and the second index will specify the length of every individual string so herewe will allocate space for names where each name can be maximum characters long let us see the memory representation of an array of strings if we have an array declared as char name[ ][ {"ram""mohan""shyam""hari""gopal"}then in the memorythe array will be stored as shown in fig namename[ name[ name[ name[ ' ' ' ' 'figure memory representation of character array
24,350
data structures using step [initializeset istep repeat step while in step apply process to names[ [end of loopstep exit figure algorithm to process individual string from an array of strings by declaring the array nameswe allocate bytes but the actual memory occupied is bytes thuswe see that about half of the memory allocated is wasted figure shows an algorithm to process individual string from an array of strings in step we initialize the index variable to zero in step while loop is executed until all the strings in the array are accessed in step each individual string is processed programming examples write program to sort the names of students #include #include #include int main(char names[ ][ ]temp[ ]int injclrscr()printf("\ enter the number of students ")scanf("% "& )for( = ; < ; ++printf("\ enter the name of student % " + )gets(names[ ])for( = ; < ; ++for( = ; < - - ; ++if(strcmp(names[ ]names[ + ])> strcpy(tempnames[ ])strcpy(names[ ]names[ + ])strcpy(names[ + ]temp)printf("\ names of the students in alphabetical order are ")for( = ; < ; ++puts(names[ ])getch()return output enter the number of students enter the name of student goransh enter the name of student aditya enter the name of student sarthak names of the students in alphabetical order are aditya goransh sarthak write program to read multiple lines of text and then count the number of characterswordsand lines in the text #include
24,351
#include int main(char str[ ]int = word_count line_count = char_count clrscr()printf("\ enter '*to end")printf("\ **************")printf("\ enter the text ")scanf("% "&str[ ])while(str[ !'*' ++scanf("% "&str[ ])str[ '\ ' = while(str[ !'\ 'if(str[ ='\ | == line_count++if(str[ =&&str[ + !'word_count++char_count++ ++printf("\ the total count of words is % "word_count)printf("\ the total count of lines is % "line_count)printf("\ the total count of characters is % "char_count)return output enter '*to end *************enter the text hi therethe total count of words is the total count of lines is the total count of characters is write program to find whether string is palindrome or not #include #include int main(char str[ ]int jlength clrscr()printf("\ enter the string ")gets(str)while(str[ !'\ 'length+ + = length while( <length/
24,352
data structures using if(str[ =str[ ] ++ --else breakif( >=jprintf("\ palindrome")else printf("\ not palindrome")return output enter the stringmadam palindrome pointers and strings in cstrings are treated as arrays of characters that are terminated with binary zero character (written as '\ 'considerfor examplechar str[ ]str[ ' 'str[ ' 'str[ '!'str[ '\ ' provides two alternate ways of declaring and initializing string firstyou may write char str[ {' '' ''!''\ '}but this also takes more typing than is convenient soc permits char str[ "hi!"when the double quotes are useda null character ('\ 'is automatically appended to the end of the string when string is declared like thisthe compiler sets aside contiguous block of the memoryi bytes longto hold characters and initializes its first four characters as hi!\ nowconsider the following program that prints text #include int main(char str["hello"char *pstrpstr strprintf("\ the string is ")while(*pstr !'\ 'printf("% "*pstr)pstr++return output the string ishello
24,353
in this programwe declare character pointer *pstr to show the string on the screen we then point the pointer pstr to str thenwe print each character of the string using the while loop instead of using the while loopwe could straightaway use the function puts()as shown below puts(pstr)the function prototype for puts(is as followsint puts(const char * )here the const modifier is used to assure that the function dose not modify the contents pointed to by the source pointer the address of the string is passed to the function as an argument the parameter passed to puts(is pointer which is nothing but the address to which it points to or simply an address thuswriting puts(strmeans passing the address of str[ similarly when we write puts(pstr)we are passing the same addressbecause we have written pstr strconsider another program that reads string and then scans each character to count the number of upper and lower case characters entered #include int main(char str[ ]*pstrint upper lower printf("\ enter the string ")gets(str)pstr strwhile(*pstr !'\ 'if(*pstr >' &*pstr <' 'upper++else if(*pstr >' &*pstr <' 'lower++pstr++printf("\ total number of upper case characters % "upper)printf("\ total number of lower case characters % "lower)return output enter the string how are you total number of upper case characters total number of lower case characters programming examples write program to copy string into another string #include int main(char str[ ]copy_str[ ]char *pstr*pcopy_strpstr strpcopy_str copy_strprintf("\ enter the string ")gets(str)while(*pstr !'\ '
24,354
data structures using *pcopy_str *pstrpstr++pcopy_str++*pcopy_str '\ 'printf("\ the copied text is ")while(*pcopy_str !'\ 'printf("% "*pcopy_str)pcopy_str++return output enter the string programming the copied text is programming write program to concatenate two strings #include #include int main(char str [ ]str [ ]copy_str[ ]char *pstr *pstr *pcopy_strclrscr()pstr str pstr str pcopy_str copy_strprintf("\ enter the first string ")gets(str )printf("\ enter the second string ")gets(str )while(*pstr !'\ '*pcopy_str *pstr pcopy_str++pstr ++while(*pstr !'\ '*pcopy_str *pstr pcopy_str++pstr ++*pcopy_str '\ 'printf("\ the concatenated text is ")while(*pcopy_str !'\ 'printf("% "*pcopy_str)pcopy_str++return output enter the first string data structures using by enter the second string reema thareja the concatenated text is data structures using by reema thareja
24,355
points to remember string is null-terminated character array individual characters of strings can be accessed using subscript that starts from zero all the characters of string are stored in successive memory locations strings can be read by user using three waysusing scanf(functionusing gets(functionor using getchar(function repeatedly the scanf(function terminates as soon as it finds blank space the gets(function takes the starting address of the string which will hold the input the string inputted using gets(is automatically terminated with null character strings can also be read by calling getchar(repeatedly to read sequence of single characters strings can be displayed on the screen using three waysusing printf functionusing puts(functionor using putchar()function repeatedly standard library supports number of pre-defined functions for manipulating strings or changing the contents of strings many of these functions are defined in the header file string alternatively we can also develop functions which perform the same task as the pre-defined string handling functions the most basic function is the length function which returns the number of characters in string name of string acts as pointer to the string in the declaration char str[ "hello"str is pointer which holds the address of the first characteri 'han array of strings can be declared as char strings [ ][ ]where the first subscript denotes the number of strings and the second subscript denotes the length of every individual string exercises review questions what are stringsdiscuss some of the operations that can be performed on strings explain how strings are represented in the main memory how are strings read from the standard input deviceexplain the different functions used to perform the string input operation explain how strings can be displayed on the screen explain the syntax of printf(and scanf( list all the substrings that can be formed from the string 'abcd what do you understand by pattern matchinggive an algorithm for it write short note on array of strings explain with an example how an array of strings is stored in the main memory explain how pointers and strings are related to each other with the help of suitable program if the substring function is given as substring (stringpositionlength)then find ( if "welcome to world of programming if the index function is given as index(textpattern)then find index(tpwhere "welcome to world of programmingand "of differentiate between gets(and scanf( give the drawbacks of getchar(and scanf( which function can be used to overcome the shortcomings of getchar(and scanf() how can putchar(be used to print string differentiate between character and string differentiate between character array and string programming exercises write program in which string is passed as an argument to function write program in to concatenate first characters of string with another string write program in that compares first characters of one string with first characters of another string write program in that removes leading and trailing spaces from string write program in that replaces given character with another character in string
24,356
data structures using write program to count the number of digitsupper case characterslower case charactersand special characters in given string write program to count the total number of occurrences of given character in the string write program to accept text count and display the number of times the word 'theappears in the text write program to count the total number of occurrences of word in the text write program to find the last instance of occurrence of sub-string within string write program to input an array of strings thenreverse the string in the format shown below "happy birthday to youshould be displayed as "you to birthday happy write program to append given string in the following format "good morning morning good write program to input text of at least two paragraphs interchange the first and second paragraphs and then re-display the text on the screen write program to input text of at least two paragraphs construct an array par such that par[icontains the location of the ith paragraph in text write program to convert the given string "good morningto "good morning write program to concatenate two given strings "good morningand "worlddisplay the resultant string write program to check whether the two given strings "good morningand "good morningare same write program to convert the given string "hello worldto "dlrow olleh write program to extract the string "od mofrom the given string "good morning write program to insert "universityin the given string "oxford pressso that the string should read as "oxford university press write program to read textdelete all the semicolons it hasand finally replace all with ', write program to copy the last characters of character array in another character array alsoconvert the lower case letters into upper case letters while copying write program to rewrite the string "good morningto "good evening write program to read and display names of employees in department write program to read line until newline is entered write program to read short story rewrite the story by printing the line number before the starting of each line write program to enter text that contains multiple lines display the lines of text starting from the mth line write program to check whether pattern exists in text if it doesdelete the pattern and display it write program to insert new name in the string array stud[][]assuming that names are sorted alphabetically write program to delete name in the string array stud[][]assuming that names are sorted alphabetically multiple-choice questions insert("xxxyyyzzz" "ppp"(apppxxxyyyzzz (bxpppxxyyyzzz (cxxxyyyzzzppp delete("xxxyyyzzz" , (axxyz (bxxxyyzz (cxxxyzz if str["welcome to the world of programming"then substring(str (aworld (bprogramming (cwelcome (dnone of these strcat(is defined in which header file(bstdio (actype (cstring (dmath string can be read using which function( )(bscanf((agets((cgetchar((dall of these replace("xxxyyyzzz""xy""ab"(axxabyyzzz (bxabyyyzzz (cabxxxyyyzz the index of in oxford university press is( ( ( (
24,357
"hi" "hello" "byehow can we concatenate the three strings(astrcat( , , (bstrcat( (strcat( , ))(cstrcpy( strcat( , ) strlen("oxford university press"is ( ( ( ( which function adds string to the end of another string(astradd((bstrcat((cstrtok((dstrcpy(true or false string hello world can be read using scanf( string when read using scanf(needs an ampersand character the gets(function takes the starting address of string which will hold the input tolower(is defined in ctype header file if and are two stringsthen the concatenation operation produces string which contains the characters of followed by the characters of appending one string to another string involves copying the contents of the source string at the end of the destination string < when in dictionary orders precedes if "good morning"then substr_right ( morning replace ("aaabbbccc"" ""yyy")aaabbbcc initializing string as char str["hello"is incorrect as null character has not been explicitly added the scanf(function automatically appends null character at the end of the string read from the keyboard string variables can be present either on the left or on the right side of the assignment operator when string is initialized during its declarationthe string must be explicitly terminated with null character strcmp("and""ant")will return positive value assignment operator can be used to copy the contents of one string into another fill in the blanks strings are every string is terminated with if string is given as "ab cd"the length of this string is the subscript of string starts with characters of string are stored in memory locations char mesg[ ]can store maximum of characters function terminates as soon as it finds blank space the ascii code for - varies from toupper(is used to > means the function to reverse string is if "good morning"then substr_left ( index("welcome to the world of programming""world" returns the position in the string where the string pattern first occurs strcmp(str str returns if function computes the length of string besides printf()function can be used to print line of text on the screen
24,358
structures and unions learning objective today' modern applications need complex data structures to support them structure is collection of related data items of different data types it extends the concept of arrays by storing related information of heterogeneous data types together under single name it is useful for applications that need lot more features than those provided by the primitive data types union is also collection of variables of different data typesexcept that in case of unionsyou can only store information in one field at any one time in this we will learn how structures and unions are declareddefinedand accessed using the language introduction structure is in many ways similar to record it stores related information about an entity structure is basically user-defined data type that can store related information (even of different data typestogether the major difference between structure and an array is that an array can store only information of same data type structure is therefore collection of variables under single name the variables within structure are of different data types and each has name that is used to select it from the structure structure declaration structure is declared using the keyword struct followed by the structure name all the variables of the structure are declared within the structure structure type is generally declared by using the following syntaxstruct struct-name data_type var-name
24,359
programming tip do not forget to place semicolon after the declaration of structures and unions }data_type var-namefor exampleif we have to define structure for studentthen the related information for student probably would beroll_numbernamecourseand fees this structure can be declared asstruct student int r_nochar name[ ]char course[ ]float fees}now the structure has become user-defined data type each variable name declared within structure is called member of the structure the structure declarationhoweverdoes not allocate any memory or consume storage space it just gives template that conveys to the compiler how the structure would be laid out in the memory and also gives the details of member names like any other data typememory is allocated for the structure when we declare variable of the structure for examplewe can define variable of student by writingstruct student stud struct student stud r_no name course fees struct student stud r_no name course fees figure memory allocation for structure variable herestruct student is data type and stud is variable look at another way of declaring variables in the following syntaxthe variables are declared at the time of structure declaration struct student int r_nochar name[ ]char course[ ]float feesstud stud in this declaration we declare two variables stud and stud of the structure student so if you want to declare more than one variable of the structurethen separate the variables using comma when we declare variables of the structureseparate memory is allocated for each variable this is shown in fig note structure type and variable declaration of structure can be either local or global depending on their placement in the code last but not the leaststructure member names and names of the structure follow the same rules as laid down for the names of ordinary variables howevercare should be taken to ensure that the name of structure and the name of structure member should not be the same moreoverstructure name and its variable name should also be different typedef declarations the typedef (derived from type definitionkeyword enables the programmer to create new data type name by using an existing data type by using typedefno new data is createdrather an
24,360
data structures using alternate name is given to known data type the general syntax of using the typedef keyword is given asprogramming tip does not allow declaration of variables at the time of creating typedef definition so variables must be declared in an independent statement typedef existing_data_type new_data_typenote that typedef statement does not occupy any memoryit simply defines new type for exampleif we write typedef int integerthen integer is the new name of data type int to declare variables using the new data type nameprecede the variable name with the data type name (newthereforeto define an integer variablewe may now write integer num= when we precede struct name with the typedef keywordthen the struct becomes new type it is used to make the construct shorter with more meaningful names for types already defined by or for types that you have declared for exampleconsider the following declarationtypedef struct student int r_nochar name[ ]char course[ ]float fees}now that you have preceded the structure' name with the typedef keywordstudent becomes new data type thereforenow you can straightaway declare the variables of this new data type as you declare the variables of type intfloatchardoubleetc to declare variable of structure studentyou may write student stud note that we have not written struct student stud initialization of structures structure can be initialized in the same way as other data types are initialized initializing structure means assigning some constants to the members of the structure when the user does not explicitly initialize the structurethen automatically does it for int and float membersthe values are initialized to zeroand char and string members are initialized to '\ by default the initializers are enclosed in braces and are separated by commas howevercare must be taken to ensure that the initializers match their corresponding types in the structure definition the general syntax to initialize structure variable is as followsor struct struct_name data_type member_name data_type member_name data_type member_name }struct_var {constant constant constant }struct struct_name data_type member_name data_type member_name data_type member_name }
24,361
struct struct_name struct_var {constant constant constant }for examplewe can initialize student structure by writingprogramming tip struct student int r_nochar name[ ]char course[ ]float fees}stud { "rahul""bca" }it is an error to assign structure of one type to structure of another type orby writingstruct student stud { "rahul""bca" }figure illustrates how the values will be assigned to individual fields of the structure struct student stud "rahul""bca" struct student stud "rajiv"}} rahul bca rajiv \ r_no name course fees r_no name course fees figure assigning values to structure elements when all the members of structure are not initializedit is called partial initialization in case of partial initializationfirst few members of the structure are initialized and those that are uninitialized are assigned default values accessing the members of structure each member of structure can be used just like normal variablebut its name will be bit longer structure member variable is generally accessed using (dotoperator the syntax of accessing structure or member of structure can be given asstruct_var member_name the dot operator is used to select particular member of the structure for exampleto assign values to the individual data members of the structure variable studlwe may write stud r_no stud name "rahul"stud course "bca"stud fees to input values for data members of the structure variable stud we may write scanf("% "&stud r_no)scanf("% "stud name)similarlyto print the values of structure variable stud we may write printf("% "stud course)printf("% "stud fees)memory is allocated only when we declare the variables of the structure in other wordsthe memory is allocated only when we instantiate the structure in the absence of any variablestructure definition is just template that will be used to reserve memory when variable of type struct is declared once the variables of structure are definedwe can perform few operations on them for examplewe can use the assignment operator (=to assign the values of one variable to another
24,362
data structures using note statement of all the operators ->)and [have the highest priority this is evident from the following stud fees+will be interpreted as (stud fees)+copying and comparing structures we can assign structure to another structure of the same type for exampleif we have two structure variables stud and stud of type struct student given as struct student stud "rahul""bca" rahul struct student stud { "rahul""bca" }struct student stud }bca then to assign one structure variable to anotherwe will write stud stud this statement initializes the members of stud with the values of members of stud thereforenow the values struct student stud stud of stud and stud can be given as shown in fig does not permit comparison of one structure variable rahul bca with another howeverindividual members of one r_no name course fees structure can be compared with individual members of another structure when we compare one structure figure values of structure variables member with another structure' memberthe comparison programming tip will behave like any other ordinary variable comparison for exampleto compare the fees of two studentswe will write an error will be generated if you r_no name course try to compare two structure variables fees if(stud fees stud fees//to check if fees of stud is greater than stud programming examples write program using structures to read and display the information about student #include #include int main(struct student int roll_nochar name[ ]float feeschar dob[ ]}struct student stud clrscr()printf("\ enter the roll number ")scanf("% "&stud roll_no)printf("\ enter the name ")scanf("% "stud name)printf("\ enter the fees ")scanf("% "&stud fees)printf("\ enter the dob ")scanf("% "stud dob)printf("\ ********student' details *******")printf("\ roll no % "stud roll_no)printf("\ name % "stud name)printf("\ fees % "stud fees)
24,363
printf("\ dob % "stud dob)getch()return output enter the roll number enter the name rahul enter the fees enter the dob ********student' details ******roll no name rahul fees dob write program to readdisplayaddand subtract two complex numbers #include #include int main(typedef struct complex int realint imag}complexcomplex sum_csub_cint optionclrscr()do printf("\ *******main menu *********")printf("\ read the complex numbers")printf("\ display the complex numbers")printf("\ add the complex numbers")printf("\ subtract the complex numbers")printf("\ exit")printf("\ enter your option ")scanf("% "&option)switch(optioncase printf("\ enter the real and imaginary parts of the first complex number ")scanf("% % "& real& imag)printf("\ enter the real and imaginary parts of the second complex number ")scanf("% % "& real& imag)breakcase printf("\ the first complex number is % +%di" real, imag)printf("\ the second complex number is % +%di" real, imag)breakcase sum_c real real realsum_c imag imag imagprintf("\ the sum of two complex numbers is
24,364
data structures using % +%di",sum_c realsum_c imag)breakcase sub_c real real realsub_c imag imag imagprintf("\ the difference between two complex numbers is :% +%di"sub_c realsub_c imag)break}while(option ! )getch()return output *******main menu ********because of constraint of read the complex numbers spacewe will show the menu display the complex numbers only once in all the menudriven programs add the complex numbers subtract the complex numbers exit enter your option enter the real and imaginary parts of the first complex number enter the real and imaginary parts of the second complex number enter your option the first complex numbers is + the second complex numbers is + enter your option the sum of two complex numbers is + enter your option nested structures structure can be placed within another structurei structure may contain another structure as its member structure that contains another structure as its member is called nested structure let us now see how we declare nested structures although it is possible to declare nested structure with one declarationit is not recommended the easier and clearer way is to declare the structures separately and then group them in the higher level structure when you do thistake care to check that nesting must be done from inside out (from lowest level to the most inclusive level) declare the innermost structurethen the next level structureworking towards the outer (most inclusivestructure typedef struct char first_name[ ]char mid_name[ ]char last_name[ ]}nametypedef struct int ddint mmint yy}datetypedef struct int r_no
24,365
name namechar course[ ]date dobfloat feesstudentin this examplewe see that the structure student contains two other structuresname and date both these structures have their own fields the structure name has three fieldsfirst_namemid_nameand last_name the structure date also has three fieldsddmmand yywhich specify the daymonthand year of the date nowto assign values to the structure fieldswe will write student stud stud r_no stud name first_name "janak"stud name mid_name "raj"stud name last_name "thareja"stud course "bca"stud dob dd stud dob mm stud dob yy stud fees in case of nested structureswe use the dot operator in conjunction with the structure variables to access the members of the innermost as well as the outermost structures the use of nested structures is illustrated in the next program programming example write program to read and display the information of student using nested structure #include #include int main(struct dob int dayint monthint year}struct student int roll_nochar name[ ]float feesstruct dob date}struct student stud clrscr()printf("\ enter the roll number ")scanf("% "&stud roll_no)printf("\ enter the name ")scanf("% "stud name)printf("\ enter the fees ")scanf("% "&stud fees)printf("\ enter the dob ")scanf("% % % "&stud date day&stud date month&stud date year)
24,366
data structures using printf("\ ********student' details *******")printf("\ roll no % "stud roll_no)printf("\ name % "stud name)printf("\ fees % "stud fees)printf("\ dob % % % "stud date daystud date monthstud date year)getch()return output enter the roll number enter the name rahul enter the fees enter the dob ********student' details ******roll no name rahul fees dob arrays of structures in the above exampleswe have seen how to declare structure and assign values to its data members nowwe will discuss how an array of structures is declared for this purposelet us first analyse where we would need an array of structures in classwe do not have just one student but there may be at least students sothe same definition of the structure can be used for all the students this would be possible when we make an array of structures an array of structures is declared in the same way as we declare an array of built-in data type another example where an array of structures is desirable is in case of an organization an organization has number of employees sodefining separate structure for every employee is not viable solution sohere we can have common structure definition for all the employees this can again be done by declaring an array of structure employee the general syntax for declaring an array of structures can be given asstruct struct_name data_type member_name data_type member_name data_type member_name }struct struct_name struct_var[index]consider the given structure definition struct student int r_nochar name[ ]char course[ ]float fees} student array can be declared by writingstruct student stud[ ]nowto assign values to the ith student of the classwe will write stud[ir_no stud[iname "rashi"
24,367
stud[icourse "mca"stud[ifees in order to initialize the array of structure variables at the time of declarationwe can write as followsstruct student stud[ {{ "aman""bca" },{ "aryan""bca" }{ "john""bca" }}programming example write program to read and display the information of all the students in class then edit the details of the ith student and redisplay the entire information #include #include #include int main(struct student int roll_nochar name[ ]int feeschar dob[ ]}struct student stud[ ]int ninumnew_rolnoint new_feeschar new_dob[ ]new_name[ ]clrscr()printf("\ enter the number of students ")scanf("% "& )for( = ; < ; ++printf("\ enter the roll number ")scanf("% "&stud[iroll_no)printf("\ enter the name ")gets(stud[iname)printf("\ enter the fees ")scanf("% ",&stud[ifees)printf("\ enter the dob ")gets(stud[idob)for( = ; < ; ++printf("\ ********details of student % *******" + )printf("\ roll no % "stud[iroll_no)printf("\ name % "stud[iname)printf("\ fees % "stud[ifees)printf("\ dob % "stud[idob)printf("\ enter the student number whose record has to be edited ")scanf("% "&num)numnum- printf("\ enter the new roll number ")scanf("% "&new_rolno)printf("\ enter the new name ")gets(new_name)printf("\ enter the new fees ")
24,368
data structures using scanf("% "&new_fees)printf("\ enter the new dob ")gets(new_dob)stud[numroll_no new_rolnostrcpy(stud[numnamenew_name)stud[numfees new_feesstrcpy (stud[numdobnew_dob)for( = ; < ; ++printf("\ ********details of student % *******" + )printf("\ roll no % "stud[iroll_no)printf("\ name % "stud[iname)printf("\ fees % "stud[ifees)printf("\ dob % "stud[idob)getch()return output enter the number of students enter the roll number enter the name kirti enter the fees enter the dob enter the roll number enter the name kangana enter the fees enter the dob ********details of student ******roll no name kirti fees dob ********details of student ******roll no name kangana fees dob enter the student number whose record has to be edited enter the new roll number enter the new name kangana khullar enter the new fees enter the new dob ********details of student ******roll no name kirti fees dob ********details of student ******roll no name kangana khullar fees dob structures and functions for structures to be fully usefulwe must have mechanism to pass them to functions and return them function may access the members of structure in three ways as shown in fig
24,369
passing individual members passing structures to functions passing the entire structure passing the address of structure figure different ways of passing structures to functions passing individual members to pass any individual member of structure to functionwe must use the direct selection operator to refer to the individual members the called program does not know if variable is an ordinary variable or structured member look at the code given below which illustrates this concept #include typedef struct int xint }pointvoid display(intint)int main(point { }display( xp )return void display(int aint bprintf(the coordinates of the point are% % "ab)output the coordinates of the point are passing the entire structure just like any other variablewe can pass an entire structure as function argument when structure is passed as an argumentit is passed using the call by value methodi copy of each member of the structure is made the general syntax for passing structure to function and returning structure can be given asstruct struct_name func_name(struct struct_name struct_var)the above syntax can vary as per the requirement for examplein some situationswe may want function to receive structure but return void or the value of some other data type the code given below passes structure to function using the call by value method #include typedef struct int xint
24,370
data structures using }pointvoid display(point)int main(point { }display( )return void display(point pprintf("the coordinates of the point are% % " xp )programming example write program to readdisplayaddand subtract two distances distance must be defined using kms and meters #include #include typedef struct distance int kmsint meters}distancedistance add_distance (distancedistance)distance subtract_distance (distancedistance)distance int main(int optionclrscr()do printf("\ *******main menu *********")printf("\ read the distances ")printf("\ display the distances")printf("\ add the distances")printf("\ subtract the distances")printf("\ exit")printf("\ enter your option ")scanf("% "&option)switch(optioncase printf("\ enter the first distance in kms and meters")scanf("% % "& kms& meters)printf("\ enter the second distance in kms and meters")scanf("% % "& kms& meters)breakcase printf("\ the first distance is % kms % meters" kmsd meters)printf("\ the second distance is % kms % meters" kmsd meters)break
24,371
case add_distance( )printf("\ the sum of two distances is % kms % meters" kmsd meters)breakcase subtract_distance( )printf("\ the difference between two distances is % kms % meters" kmsd meters)break}while(option ! )getch()return distance add_distance(distance distance distance sumsum meters meters meterssum kms kms kmswhile (sum meters > sum meters sum meters sum kms + return sumdistance subtract_distance(distance distance distance subif( kms kmssub meters meters meterssub kms kms kmselse sub meters meters meterssub kms kms kmsif(sub meters sub kms sum kms sub meters sum meters return suboutput *******main menu ******** read the distances display the distances add the distances subtract the distances exit
24,372
data structures using enter your option enter the first distance in kms and meters enter the second distance in kms and meters enter your option the sum of two distances is kms meters enter your option let us summarize some points that must be considered while passing structure to the called function if the called function is returning copy of the entire structure then it must be declared as struct followed by the structure name the structure variable used as parameter in the function declaration must be the same as that of the actual argument in the called function (and that should be the name of the struct typewhen function returns structurethen in the calling function the returned structure must be assigned to structure variable of the same type passing structures through pointers passing large structures to functions using the call by value method is very inefficient thereforeit is preferred to pass structures through pointers it is possible to create pointer to almost any type in cincluding the user-defined types it is extremely common to create pointers to structures like in other casesa pointer to structure is never itself structurebut merely variable that holds the address of structure the syntax to declare pointer to structure can be given asorstruct struct_name data_type member_name data_type member_name data_type member_name }*ptrstruct struct_name *ptrfor our student structurewe can declare pointer variable by writing struct student *ptr_studstudthe next thing to do is to assign the address of stud to the pointer using the address operator (&)as we would do in case of any other pointer so to assign the addresswe will write ptr_stud &studto access the members of structurewe can write /get the structurethen select member *(*ptr_studroll_nosince parentheses have higher precedence than *writing this statement would work well but this statement is not easy to work withespecially for beginner soc introduces new operator to do the same task this operator is known as 'pointing-tooperator programming tip (->it can be used asthe selection operator -is single tokenso do not place any white space between them /the roll_no in the structure ptr_stud points to *ptr_stud -roll_no this statement is far easier than its alternative
24,373
programming examples write program to initialize the members of structure by using pointer to the structure #include #include struct student int r_nochar name[ ]char course[ ]int fees}int main(struct student stud *ptr_stud clrscr()ptr_stud &stud printf("\ enter the details of the student :")printf("\ enter the roll number =")scanf("% "&ptr_stud -r_no)printf("\ enter the name )gets(ptr_stud -name)printf("\ enter the course ")gets(ptr_stud -course)printf("\ enter the fees ")scanf("% "&ptr_stud -fees)printf("\ details of the student")printf("\ roll number % "ptr_stud -r_no)printf("\ name % "ptr_stud -name)printf("\ course % "ptr_stud -course)printf("\ fees % "ptr_stud -fees)return output enter the details of the studententer the roll number enter the name aditya enter the course mca enter the fees details of the student roll number name aditya course mca fees write programusing an array of pointers to structureto read and display the data of students #include #include #include struct student int r_nochar name[ ]char course[ ]int fees}struct student *ptr_stud[ ]int main(
24,374
data structures using int inprintf("\ enter the number of students ")scanf("% "& )for( = ; < ; ++ptr_stud[ (struct student *)malloc(sizeof(struct student))printf("\ enter the data for student % " + )printf("\ roll no ")scanf("% "&ptr_stud[ ]->r_no)printf("\ name")gets(ptr_stud[ ]->name)printf("\ course")gets(ptr_stud[ ]->course)printf("\ fees")scanf("% "&ptr_stud[ ]->fees)printf("\ details of students")for( = ; < ; ++printf("\ roll no % "ptr_stud[ ]->r_no)printf("\ name % "ptr_stud[ ]->name)printf("\ course % "ptr_stud[ ]->course)printf("\ fees % "ptr_stud[ ]->fees)return output enter the number of students enter the data for student roll no namerahul coursebca fees details of students roll no name rahul course bca fees write program that passes pointer to structure to function #include #include #include struct student int r_nochar name[ ]char course[ ]int fees}void display (struct student *)int main(struct student *ptrptr (struct student *)malloc(sizeof(struct student))printf("\ enter the data for the student ")printf("\ roll no ")scanf("% "&ptr->r_no)
24,375
printf("\ name")gets(ptr->name)printf("\ course")gets(ptr->course)printf("\ fees")scanf("% "&ptr->fees)display(ptr)getch()return void display(struct student *ptrprintf("\ details of student")printf("\ roll no % "ptr->r_no)printf("\ name % "ptr->name)printf("\ course % "ptr->course)printf("\ fees % "ptr->fees)output enter the data for the student roll no namerahul coursebca fees details of student roll no name rahul course bca fees self-referential structures self-referential structures are those structures that contain reference to the data of its same type that isa self-referential structurein addition to other datacontains pointer to data that is of the same type as that of the structure for exampleconsider the structure node given below struct node int valstruct node *next}herethe structure node will contain two types of dataan integer val and pointer next you must be wondering why we need such structure actuallyself-referential structure is the foundation of other data structures we will be using them throughout this book and their purpose will be clearer to you when we discuss linked liststreesand graphs unions similar to structuresa union is collection of variables of different data types the only difference between structure and union is that in case of unionsyou can only store information in one field at any one time to better understand unionthink of it as chunk of memory that is used to store variables of different types when new value is assigned to fieldthe existing data is replaced with the new data thusunions are used to save memory they are useful for applications that involve multiple memberswhere values need not be assigned to all the members at any one time
24,376
data structures using programming tip it is an error to use structureunion variable as member of its own struct type structure or union type unionrespectively declaring union the syntax for declaring union is the same as that of declaring structure the only difference is that instead of using the keyword structthe keyword union would be used the syntax for union declaration can be given as union union-name data_type var-namedata_type var-name}programming tip variable of structure or union can be declared at the time of structure/union definition by placing the variable name after the closing brace and before the semicolon again the typedef keyword can be used to simplify the declaration of union variables the most important thing to remember about union is that the size of union is the size of its largest field this is because sufficient number of bytes must be reserved to store the largest sized field accessing member of union member of union can be accessed using the same syntax as that of structure to access the fields of unionuse the dot operator ) the union variable name followed by the dot operator followed by the member name initializing unions the difference between structure and union is that in case of unionthe fields share the same memory spaceso new data replaces any existing data look at the following code and observe the difference between structure and union when their fields are to be initialized #include typedef struct point int xy}typedef union point int xint }int main(point { , }/point ={ , }illegal in case of unions point printf("\ the coordinates of are % and % " xp )printf("\ the coordinates of are % and % " xp )return output the coordinates of are and
24,377
the coordinates of are and in this codepoint is structure name and point is union name howeverboth the declarations are almost same (except the keywords--struct and unionin main()we can see the difference between structures and unions while initializing values the fields of union cannot be initialized all at once look at the output carefully for the structure variable the output is programming tip as expected but for the union variable the answer does not seem to be the size of union is equal to the correct to understand the concept of unionexecute the following code size of its largest member the code given below just re-arranges the printf statements you will be surprised to see the result #include typedef struct point int xy}typedef union point int xint }int main(point { , }point printf("\ the coordinates of are % and % " xp ) printf("\ the coordinate of is % " ) printf("\ the coordinate of is % " )return output the coordinates of are and the coordinate of is the coordinate of is here although the output is correctthe data is still overwritten in memory arrays of union variables like structures we can also have an array of union variables howeverbecause of the problem of new data overwriting existing data in the other fieldsthe program may not display the accurate results #include union point int xy}int main(int iunion point points[ ]points[ points[ points[ points[
24,378
data structures using points[ points[ for( = ; < ; ++printf("\ coordinates of point[%dare % and % "ipoints[ixpoints[iy)return output coordinates of point[ are and coordinates of point[ are and coordinates of point[ are and unions inside structures generallyunions can be very useful when declared inside structure consider an example in which you want field of structure to contain string or an integerdepending on what the user specifies the following code illustrates such scenario#include struct student union char name[ ]int roll_no}int marks}int main(struct student studchar choiceprintf("\ you can enter the name or roll number of the student")printf("\ do you want to enter the name( or )")gets(choice)if(choice==' |choice==' 'printf("\ enter the name")gets(stud name)else printf("\ enter the roll number")scanf("% "&stud roll_no)printf("\ enter the marks")scanf("% "&stud marks)if(choice==' |choice==' 'printf("\ name% "stud name)else printf("\ roll number% "stud roll_no)printf("\ marks% "stud marks)return now in this codewe have union embedded within structure we know the fields of union will share memoryso in the main program we ask the user which data he/she would like to store and depending on his/her choice the appropriate field is used
24,379
points to remember structure is user-defined data type that can store related information (even of different data typestogether structure is declared using the keyword structfollowed by the structure name the structure definition does not allocate any memory or consume storage space it just gives template that conveys to the compiler how the structure is laid out in the memory and gives details of the member names like any data typememory is allocated for the structure when we declare variable of the structure when struct name is preceded with the keyword typedefthen the struct becomes new type when the user does not explicitly initialize the structurethen automatically does it for int and float membersthe values are initialized to zero and char and string members are initialized to '\ by default structure member variable is generally accessed using (dotoperator structure can be placed within another structure that isa structure may contain another structure as its member such structure is called nested structure self-referential structures are those structures that contain reference to data of its same type that isa self-referential structurein addition to other datacontains pointer to data that is of the same type as that of the structure union is collection of variables of different data types in which memory is shared among these variables the size of union is equal to the size of its largest member the only difference between structure and union is that in case of unions information can only be stored in one member at time exercises review questions what is the advantage of using structures structure declaration reserves memory for the structure comment on this statement with valid justifications differentiate between structure and an array write short note on structures and inter-process communication explain the utility of the keyword typedef in structures explain with an example how structures are initialized is it possible to create an array of structuresexplain with the help of an example what do you understand by union differentiate between structure and union how is structure name different from structure variable explain how members of union are accessed write short note on nested structures in which applications unions can be usefulprogramming exercises declare structure that represents the following hierarchical information (astudent (broll number (cname (ifirst name (iimiddle name (iiilast name (dsex (edate of birth (iday (iimonth (iiiyear (fmarks (ienglish (iimathematics (iiicomputer science define structure to store the namean array marks[which stores the marks of three different subjectsand character grade write program to display the details of the student whose name is entered by the user use the structure definition of the first question to make an array of students
24,380
data structures using display the name of the students who have secured less than of the aggregate modify question to print each student' average marks and the class average (that includes average of all the student' marks make an array of students as illustrated in question and write program to display the details of the student with the given date of birth write program to find smallest of three numbers using structures write program to calculate the distance between the given points ( , and ( , write program to read and display the information about all the employees in department edit the details of the ith employee and redisplay the information write program to add and subtract height ' and ' write program to add and subtract hrs mins sec and hrs min sec write program using structure to check if the current year is leap year or not write program using pointer to structure to initialize the members of an employee structure use functions to print the employee' information write program to create structure with the information given below thenread and print the data employee[ (aemp_id (bname (ifirst name (iimiddle name (iiilast name (caddress (iarea (iicity (iiistate (dage (esalary (fdesignation define structure date containing three integers-daymonthand year write program using functions to read datato validate the date entered by the user and then print the date on the screen for exampleif you enter , , then that is an invalid date as is not leap year similarly , , is invalid as june does not have days using the structure definition of the above programwrite function to increment the date make sure that the incremented date is valid date modify the above program to add specific number of days to the given date write program to define structure vector then write functions to read dataprint dataadd two vectors and scale the members of vector by factor of write program to define structure for hotel that has members-nameaddressgradenumber of roomsand room charges write function to print the names of hotels in particular grade also write function to print names of hotels that have room charges less than the specified value write program to define union and structure both having exactly the same members using the sizeof operatorprint the size of structure variable as well as union variable and comment on the result declare structure time that has three fields--hrminsec create two variables start_time and end_time input their values from the user then while start_time does not reach the end_timedisplay good day on the screen declare structure fraction that has two fields-numerator and denominator create two variables and compare them using function return if the two fractions are equal- if the first fraction is less than the second and otherwise you may convert fraction into floating point number for your convenience declare structure point input the coordinates of point variable and determine the quadrant in which it lies the following table can be used to determine the quadrant quadrant positive positive negative positive negative negative positive negative write program to calculate the area of one of the geometric figures--circlerectangle or triangle write function to calculate the area
24,381
the function must receive one parameter which is structure that contains the type of figure and the size of the components needed to calculate the area must be part of union note that circle requires just one componentrectangle requires two components and triangle requires the size of three components to calculate the area multiple-choice questions data structure that can store related information together is called (aarray (bstring (cstructure (dall of these data structure that can store related information of different data types together is called (aarray (bstring (cstructure (dall of these memory for structure is allocated at the time of (astructure definition (bstructure variable declaration (cstructure declaration (dfunction declaration structure member variable is generally accessed using (aaddress operator (bdot operator (ccomma operator (dternary operator structure that can be placed within another structure is known as (aself-referential structure (bnested structure (cparallel structure (dpointer to structure union member variable is generally accessed using the (aaddress operator (bdot operator (ccomma operator (dternary operator typedef can be used with which of these data types(astruct (bunion (cenum (dall of these true or false structures contain related information of the same data type structure declaration reserves memory for the structure when the user does not explicitly initialize the structurethen automatically does it the dereference operator is used to select particular member of the structure nested structure contains another structure as its member struct type is primitive data type permits copying of one structure variable to another unions and structures are initialized in the same way structure cannot have union as its member permits nested unions field in structure can itself be structure no two members of union should have the same name union can have another union as its member new variables can be created using the typedef keyword fill in the blanks structure is data type is just template that will be used to reserve memory when variable of type struct is declared structure is declared using the keyword struct followed by when we precede struct name with then the struct becomes new type for int and float structure membersthe values are initialized to char and string structure members are initialized to by default structure member variable is generally accessed using structure placed within another structure is called structures contain reference to data of its same type memory is allocated for structure when is done is collection of data under one name in which memory is shared among the members the selection operator is used to permits sharing of memory among different types of data
24,382
linked lists learning objective linked list is collection of data elements called nodes in which the linear representation is given by links from one node to the next node in this we are going to discuss different types of linked lists and the operations that can be performed on these lists introduction we have studied that an array is linear collection of data elements in which the elements are stored in consecutive memory locations while declaring arrayswe have to specify the size of the arraywhich will restrict the number of elements that the array can store for exampleif we declare an array as int marks[ ]then the array can store maximum of data elements but not more than that but what if we are not sure of the number of elements in advancemoreoverto make efficient use of memorythe elements must be stored randomly at any location rather than in consecutive locations sothere must be data structure that removes the restrictions on the maximum number of elements and the storage condition to write efficient programs linked list is data structure that is free from the aforementioned restrictions linked list does not store its elements in consecutive memory locations and the user can add any number of elements to it howeverunlike an arraya linked list does not allow random access of data elements in linked list can be accessed only in sequential manner but like an arrayinsertions and deletions can be done at any point in the list in constant time basic terminologies linked listin simple termsis linear collection of data elements these data elements are called nodes linked list is data structure which in turn can be used to implement other data
24,383
structures thusit acts as building block to implement data structures such as stacksqueuesand their variations linked list can be perceived as train or sequence of nodes in which each node contains one or more data fields and pointer to the next node start figure simple linked list in fig we can see linked list in which every node contains two partsan integer and pointer to the next node the left part of the node which contains data may include simple data typean arrayor structure the right part of the node contains pointer to the next node (or address of the next node in sequencethe last node will have no next node connected to itso it will store special value called null in fig the null pointer is represented by while programmingwe usually define null as - hencea null pointer denotes the end of the list since in linked listevery node contains pointer to another node which is of the same typeit is also called self-referential data type linked lists contain pointer variable start that stores the address of the first node in the list we can traverse the entire list using start which contains the address of the first nodethe next part of the first node in turn stores the address of its succeeding node using this techniquethe individual nodes of the list will form chain of nodes if start nullthen the linked list is empty and contains no nodes in cwe can implement linked list using the following codestruct node int datastruct node *next}note linked lists provide an efficient way of storing related data and perform basic operations such as insertiondeletionand updation of information at the cost of extra space required for storing address of the next node start data next - figure start pointing to the first element of the linked list in the memory let us see how linked list is maintained in the memory in order to form linked listwe need structure called node which has two fieldsdata and next data will store the information part and next will store the address of the next node in sequence consider fig in the figurewe can see that the variable start is used to store the address of the first node herein this examplestart so the first data is stored at address which is the corresponding next stores the address of the next nodewhich is sowe will look at address to fetch the next data item the second data element obtained from address is againwe see the corresponding next to go to the next node from the entry in the nextwe get the next addressthat is and fetch as the data we repeat this procedure until we reach position where the next entry contains - or nullas this
24,384
data structures using would denote the end of the linked list when we traverse data and next in this mannerwe finally see that the linked list in the above example stores characters that when put together form the word hello note that fig shows chunk of memory locations which range from to the shaded portion contains data for other applications remember that the nodes of linked list need not be in consecutive memory locations in our examplethe nodes for the linked list are stored at addresses and let us take another example to see how two linked lists are maintained together in the computer' memory for examplethe students of class xi of science group are asked to choose between biology and computer science nowwe will maintain two linked listsone for each subject that isthe first linked list will contain the roll numbers of all the students who have opted for biology and the second list will contain the roll numbers of students who have chosen computer science nowlook at fig two different linked lists are simultaneously maintained in the memory there is no ambiguity in traversing through the list because each list maintains separate start pointerwhich gives the address of the first node of their respective linked lists the rest of the start next roll no nodes are reached by looking at the value stored (biologys in the next by looking at the figurewe can conclude that roll numbers of the students who have opted for start biology are and (computer science similarlyroll numbers of the students who chose computer science are and we have already said that the data part of node may contain just single data iteman arrayor structure let us take an example to see how structure is maintained in linked list that is stored - in the memory consider scenario in which the roll number nameaggregateand grade of students are stored - using linked lists nowwe will see how the next pointer is used to store the data alphabetically figure two linked lists which are simultaneously maintained in the memory this is shown in fig linked lists versus arrays both arrays and linked lists are linear collection of data elements but unlike an arraya linked list does not store its nodes in consecutive memory locations another point of difference between an array and linked list is that linked list does not allow random access of data nodes in linked list can be accessed only in sequential manner but like an arrayinsertions and deletions can be done at any point in the list in constant time another advantage of linked list over an array is that we can add any number of elements in the list this is not possible in case of an array for exampleif we declare an array as int marks[ ]then the array can store maximum of data elements only there is no such restriction in case of linked list
24,385
roll no name aggregate grade next ram distinction shyam first division mohit outstanding rohit varun distinction outstanding karan first division veena second division - meera first division krish kusum third division outstanding silky first division start monica distinction ashish first division gaurav first division figure studentslinked list thuslinked lists provide an efficient way of storing related data and performing basic operations such as insertiondeletionand updation of information at the cost of extra space required for storing the address of next nodes memory allocation and de-allocation for linked list we have seen how linked list is represented in the memory if we want to add node to an already existing linked list in the memorywe first find free space in the memory and then use it to store the information for exampleconsider the linked list shown in fig the linked list contains the roll number of studentsmarks obtained by them in biologyand finally next field which stores the address of the next node in sequence nowif new student joins the class and is asked to appear for the same test that the other students had takenthen the new student' marks should also be recorded in the linked list for this purposewe find free space and store the information there in fig the grey shaded portion shows free spaceand thus we have memory locations available we can use any one of them to store our data this is illustrated in figs (aand (bnowthe question is which part of the memory is available and which part is occupiedwhen we delete node from linked listthen who changes the status of the memory occupied by it from occupied to availablethe answer is the operating system discussing the mechanism of how the operating system does all this is out of the scope of this book soin simple languagewe can say that the computer does it on its own without any intervention from the user or the programmer as programmeryou just have to take care of the code to perform insertions and deletions in the list howeverlet us briefly discuss the basic concept behind it the computer maintains list of all free memory cells this list of available space is called the free pool
24,386
data structures using start (biologyroll no marks next start marks - (biology (afigure next roll no - ( (astudentslinked list and (blinked list after the insertion of new student' record we have seen that every linked list has pointer variable start which stores the address of the first node of the list likewisefor the free pool (which is linked list of all free memory cells)we have pointer variable avail which stores the address of the first free space let us revisit the memory representation of the linked list storing all the studentsmarks in biology nowwhen new student' record has to be addedthe memory address pointed by avail will be taken and used to store the desired information after the insertionthe next available free space' address will be stored in avail for examplein fig when the first free memory space is utilized for inserting the new nodeavail will be set to contain address this was all about inserting new node in start an already existing linked list nowwe will next marks roll no discuss deleting node or the entire linked (biologylist when we delete particular node from an existing linked list or delete the entire linked listthe space occupied by it must be given back to the free pool so that the memory can avail be reused by some other program that needs memory space the operating system does this task of adding the freed memory to the free pool the operating system will perform this operation whenever it finds the cpu idle or whenever the programs are falling short of memory space the operating system scans through all the - memory cells and marks those cells that are - being used by some program then it collects all the cells which are not being used and adds figure linked list with avail and start pointers
24,387
their address to the free poolso that these cells can be reused by other programs this process is called garbage collection there are different types of linked lists which we will discuss in the next section singly linked lists singly linked list is the simplest type of linked list in which every node contains some data and pointer to the next node of the same data type by saying that the node contains pointer to the next nodewe mean that the node stores the address of the next node in sequence singly linked list allows traversal of data only in one way figure shows singly linked list start figure singly linked list traversing linked list traversing linked list means accessing the nodes of the list in order to perform some processing on them remember linked list always contains pointer variable start which stores the address of the first node of the list end of the list is marked by storing null or - in the next field of the last node for traversing the linked listwe also make use of another pointer variable ptr which points to the node that is currently being accessed the algorithm to traverse linked list is shown in fig in this algorithmwe first initialize ptr with the address of start so nowptr points to the first node of the linked list then in step while loop is executed which is repeated till ptr processes the last nodethat is until it encounters null in step we apply the process ( printto the current nodethat isthe node pointed by ptr in step we move to the next node by making the ptr variable point to the node whose address is stored in the next field let us now write an algorithm to count the number of nodes in linked list to do thiswe step [initializeset ptr start will traverse each and every node of the list and step repeat steps and while ptr !null step apply process to ptr -data while traversing every individual nodewe will step set ptr ptr -next increment the counter by once we reach null[end of loopthat iswhen all the nodes of the linked list have step exit been traversedthe final value of the counter will be displayed figure shows the algorithm to figure algorithm for traversing linked list print the number of nodes in linked list step [initializeset count step [initializeset ptr start step repeat steps and while ptr !null step set count count step set ptr ptr -next [end of loopstep write count step exit figure algorithm to print the number of nodes in linked list searching for value in linked list searching linked list means to find particular element in the linked list as already discusseda linked list consists of nodes which are divided into two partsthe information part and the next part so searching means finding whether given value is present in the information part of the node or not if it is presentthe algorithm returns the address of the node that contains the value
24,388
data structures using figure shows the algorithm to search linked list in step we initialize the pointer variable ptr with start that contains the address of the first node in step while loop is executed which will compare every node' data with val for which the search is being made if the search is successfulthat isval has been foundthen the address of that node is stored in pos and the control jumps to the last statement of the algorithm howeverif the search is unsuccessfulpos is figure algorithm to search linked list set to null which indicates that val is not present in the linked list consider the linked list shown in fig if we have val then the flow of the algorithm can be explained as shown in the figure step [initializeset ptr start step repeat step while ptr !null step if val ptr -data set pos ptr go to step else set ptr ptr -next [end of if[end of loopstep set pos null step exit ptr here ptr -data since ptr -data ! we move to the next node ptr here ptr -data since ptr -data ! we move to the next node ptr here ptr -data since ptr -data ! we move to the next node ptr here ptr -data since ptr -data pos ptr pos now stores the address of the node that contains val figure searching linked list inserting new node in linked list in this sectionwe will see how new node is added into an already existing linked list we will take four cases and then see how insertion is done in each case case the new node is inserted at the beginning case the new node is inserted at the end case the new node is inserted after given node case the new node is inserted before given node before we describe the algorithms to perform insertions in all these four caseslet us first discuss an important term called overflow overflow is condition that occurs when avail null or no free memory cell is present in the system when this condition occursthe program must give an appropriate message inserting node at the beginning of linked list consider the linked list shown in fig suppose we want to add new node with data and add it as the first node of the list then the following changes will be done in the linked list
24,389
start allocate memory for the new node and initialize its data part to add the new node as the first node of the list by making the next part of the new node contain the address of start start now make start to point to the first node of the list start figure inserting an element at the beginning of linked list step if avail null write overflow go to step [end of ifstep set new_node avail step set avail avail -next step set new_node -data val step set new_node -next start step set start new_node step exit figure algorithm to insert new node at the beginning figure shows the algorithm to insert new node at the beginning of linked list in step we first check whether memory is available for the new node if the free memory has exhaustedthen an overflow message is printed otherwiseif free memory cell is availablethen we allocate space for the new node set its data part with the given val and the next part is initialized with the address of the first node of the listwhich is stored in start nowsince the new node is added as the first node of the listit will now be known as the start nodethat isthe start pointer variable will now hold the address of the new_node note the following two stepsstep set new_node avail step set avail avail -next these steps allocate memory for the new node in cthere are functions like malloc()allocand calloc(which automatically do the memory allocation on behalf of the user inserting node at the end of linked list consider the linked list shown in fig suppose we want to add new node with data as the last node of the list then the following changes will be done in the linked list figure shows the algorithm to insert new node at the end of linked list in step we take pointer variable ptr and initialize it with start that isptr now points to the first node of the linked list in the while loopwe traverse through the linked list to reach the last node once we reach the last nodein step we change the next pointer of the last node to store the address of the new node remember that the next field of the new node contains nullwhich signifies the end of the linked list inserting node after given node in linked list consider the linked list shown in fig suppose we want to add new node with value after the node containing data before discussing the changes that will be done in the linked listlet us first look at the algorithm shown in fig
24,390
data structures using start allocate memory for the new node and initialize its data part to and next part to null take pointer variable ptr which points to start startptr move ptr so that it points to the last node of the list start ptr add the new node after the node pointed by ptr this is done by storing the address of the new node in the next part of ptr start ptr figure inserting an element at the end of linked list step if avail null write overflow go to step [end of ifstep set new_node avail step set avail avail next step set new_node data val step set new_node next null step set ptr start step repeat step while ptr next !null step set ptr ptr next [end of loopstep set ptr next new_node step exit step if avail null write overflow go to step [end of ifstep set new_node avail step set avail avail next step set new_node data val step set ptr start step set preptr ptr step repeat steps and while preptr data !num step set preptr ptr step set ptr ptr next [end of loopstep preptr next new_node step set new_node next ptr step exit figure algorithm to insert new node at the end figure algorithm to insert new node after node that has value num in step we take pointer variable ptr and initialize it with start that isptr now points to the first node of the linked list then we take another pointer variable preptr which will be used to store the address of the node preceding ptr initiallypreptr is initialized to ptr so nowptrpreptrand start are all pointing to the first node of the linked list in the while loopwe traverse through the linked list to reach the node that has its value equal to num we need to reach this node because the new node will be inserted after this node once we reach this nodein steps and we change the next pointers in such way that new node is inserted after the desired node
24,391
start allocate memory for the new node and initialize its data part to take two pointer variables ptr and preptr and initialize them with start so that startptrand preptr point to the first node of the list start ptr preptr move ptr and preptr until the data part of preptr value of the node after which insertion has to be done preptr will always point to the node just before ptr start preptr ptr start preptr ptr add the new node in between the nodes pointed by preptr and ptr start preptr ptr new_node start figure inserting an element after given node in linked list inserting node before given node in linked list consider the linked list shown in fig suppose we want to add new node with value before the node containing before discussing step if avail null the changes that will be done in the linked write overflow listlet us first look at the algorithm shown go to step in fig [end of ifstep set new_node avail in step we take pointer variable step set avail avail next ptr and initialize it with start that isptr step set new_node data val now points to the first node of the linked step set ptr start list thenwe take another pointer variable step set preptr ptr step repeat steps and while ptr data !num preptr and initialize it with ptr so nowstep set preptr ptr ptrpreptrand start are all pointing to step set ptr ptr next the first node of the linked list [end of loopin the while loopwe traverse through step preptr next new_node step set new_node next ptr the linked list to reach the node that has step exit its value equal to num we need to reach this node because the new node will be figure algorithm to insert new node before node that has inserted before this node once we reach value num
24,392
data structures using this nodein steps and we change the next pointers in such way that the new node is inserted before the desired node start allocate memory for the new node and initialize its data part to initialize preptr and ptr to the start node start ptr preptr move ptr and preptr until the data part of ptr value of the node before which insertion has to be done preptr will always point to the node just before ptr start preptr ptr insert the new node in between the nodes pointed by preptr and ptr start preptr ptr new_node start figure inserting an element before given node in linked list deleting node from linked list in this sectionwe will discuss how node is deleted from an already existing linked list we will consider three cases and then see how deletion is done in each case case the first node is deleted case the last node is deleted case the node after given node is deleted before we describe the algorithms in all these three caseslet us first discuss an important term called underflow underflow is condition that occurs when we try to delete node from linked list that is empty this happens when start null or when there are no more nodes to delete note that when we delete node from linked listwe actually have to free the memory occupied by that node the memory is returned to the free pool so that it can be used to store other programs and data whatever be the case of deletionwe always change the avail pointer so that it points to the address that has been recently vacated deleting the first node from linked list consider the linked list in fig when we want to delete node from the beginning of the listthen the following changes will be done in the linked list
24,393
start make start to point to the next node in sequence start figure deleting the first node of linked list figure shows the algorithm to delete the first node from linked list in step we check if the linked list exists or not if start nullthen it signifies that there are no nodes in the list and the control is transferred step if start null write underflow to the last statement of the algorithm go to step howeverif there are nodes in the linked listthen we use [end of ifstep set ptr start pointer variable ptr that is set to point to the first node of the list step set start start -next for thiswe initialize ptr with start that stores the address of step free ptr the first node of the list in step start is made to point to the step exit next node in sequence and finally the memory occupied by the figure algorithm to delete the first node pointed by ptr (initially the first node of the listis freed node and returned to the free pool deleting the last node from linked list consider the linked list shown in fig suppose we want to delete the last node from the linked listthen the following changes will be done in the linked list start take pointer variables ptr and preptr which initially point to start start preptr ptr move ptr and preptr such that next part of ptr null preptr always points to the node just before the node pointed by ptr start set the next part of preptr node to null preptr ptr start figure deleting the last node of linked list figure shows the algorithm to delete the last node from linked list in step we take pointer variable ptr and initialize it with start that isptr now points to the first node of the linked list in the while loopwe take another pointer variable preptr such that it always points to one node before the ptr once we reach the last node and the second last nodewe set the next pointer of the second last node to nullso that it now becomes the (newlast node of the linked list the memory of the previous last node is freed and returned back to the free pool
24,394
data structures using step if start null write underflow go to step [end of ifstep set ptr start step repeat steps and while ptr -next !null step set preptr ptr step set ptr ptr -next [end of loopstep set preptr -next null step free ptr step exit figure algorithm to delete the last node deleting the node after given node in linked list consider the linked list shown in fig suppose we want to delete the node that succeeds the node which contains data value then the following changes will be done in the linked list start take pointer variables ptr and preptr which initially point to start start preptr ptr move preptr and ptr such that preptr points to the node containing val and ptr points to the succeeding node start preptr ptr preptr ptr start start preptr ptr set the next part of preptr to the next part of ptr start preptr ptr start figure deleting the node after given node in linked list figure shows the algorithm to delete the node after given node from linked list in step we take pointer variable ptr and initialize it with start that isptr now points to the first node of the linked list in the while loopwe take another pointer variable preptr such that it always points to one node before the ptr once we reach the node containing val and the node succeeding itwe set the next pointer of the node containing val to the address contained in next field of the node succeeding it the memory of the node succeeding the given node is freed and returned back to the free pool
24,395
step if start null write underflow go to step [end of ifstep set ptr start step set preptr ptr step repeat steps and while preptr -data !num step set preptr ptr step set ptr ptr -next [end of loopstep set temp ptr step set preptr -next ptr -next step free temp step exit figure algorithm to delete the node after given node programming example write program to create linked list and perform insertions and deletions of all cases write functions to sort and finally delete the entire list at once #include #include #include #include struct node int datastruct node *next}struct node *start nullstruct node *create_ll(struct node *)struct node *display(struct node *)struct node *insert_beg(struct node *)struct node *insert_end(struct node *)struct node *insert_before(struct node *)struct node *insert_after(struct node *)struct node *delete_beg(struct node *)struct node *delete_end(struct node *)struct node *delete_node(struct node *)struct node *delete_after(struct node *)struct node *delete_list(struct node *)struct node *sort_list(struct node *)int main(int argcchar *argv[]int optiondo printf("\ \ *****main menu *****")printf("\ create list")printf("\ display the list")printf("\ add node at the beginning")printf("\ add node at the end")printf("\ add node before given node")printf("\ add node after given node")printf("\ delete node from the beginning")
24,396
data structures using printf("\ delete node from the end")printf("\ delete given node")printf("\ delete node after given node")printf("\ delete the entire list")printf("\ sort the list")printf("\ exit")printf("\ \ enter your option ")scanf("% "&option)switch(optioncase start create_ll(start)printf("\ linked list created")breakcase start display(start)breakcase start insert_beg(start)breakcase start insert_end(start)breakcase start insert_before(start)breakcase start insert_after(start)breakcase start delete_beg(start)breakcase start delete_end(start)breakcase start delete_node(start)breakcase start delete_after(start)breakcase start delete_list(start)printf("\ linked list deleted")breakcase start sort_list(start)break}while(option != )getch()return struct node *create_ll(struct node *startstruct node *new_node*ptrint numprintf("\ enter - to end")printf("\ enter the data ")scanf("% "&num)while(num!=- new_node (struct node*)malloc(sizeof(struct node))new_node -data=numif(start==nullnew_node -next nullstart new_nodeelse ptr=start
24,397
while(ptr->next!=nullptr=ptr->nextptr->next new_nodenew_node->next=nullprintf("\ enter the data ")scanf("% "&num)return startstruct node *display(struct node *startstruct node *ptrptr startwhile(ptr !nullprintf("\ % "ptr -data)ptr ptr -nextreturn startstruct node *insert_beg(struct node *startstruct node *new_nodeint numprintf("\ enter the data ")scanf("% "&num)new_node (struct node *)malloc(sizeof(struct node))new_node -data numnew_node -next startstart new_nodereturn startstruct node *insert_end(struct node *startstruct node *ptr*new_nodeint numprintf("\ enter the data ")scanf("% "&num)new_node (struct node *)malloc(sizeof(struct node))new_node -data numnew_node -next nullptr startwhile(ptr -next !nullptr ptr -nextptr -next new_nodereturn startstruct node *insert_before(struct node *startstruct node *new_node*ptr*preptrint numvalprintf("\ enter the data ")scanf("% "&num)printf("\ enter the value before which the data has to be inserted ")scanf("% "&val)new_node (struct node *)malloc(sizeof(struct node))new_node -data numptr startwhile(ptr -data !val
24,398
data structures using preptr ptrptr ptr -nextpreptr -next new_nodenew_node -next ptrreturn startstruct node *insert_after(struct node *startstruct node *new_node*ptr*preptrint numvalprintf("\ enter the data ")scanf("% "&num)printf("\ enter the value after which the data has to be inserted ")scanf("% "&val)new_node (struct node *)malloc(sizeof(struct node))new_node -data numptr startpreptr ptrwhile(preptr -data !valpreptr ptrptr ptr -nextpreptr -next=new_nodenew_node -next ptrreturn startstruct node *delete_beg(struct node *startstruct node *ptrptr startstart start -nextfree(ptr)return startstruct node *delete_end(struct node *startstruct node *ptr*preptrptr startwhile(ptr -next !nullpreptr ptrptr ptr -nextpreptr -next nullfree(ptr)return startstruct node *delete_node(struct node *startstruct node *ptr*preptrint valprintf("\ enter the value of the node which has to be deleted ")scanf("% "&val)ptr startif(ptr -data =valstart delete_beg(start)return startelse
24,399
while(ptr -data !valpreptr ptrptr ptr -nextpreptr -next ptr -nextfree(ptr)return startstruct node *delete_after(struct node *startstruct node *ptr*preptrint valprintf("\ enter the value after which the node has to deleted ")scanf("% "&val)ptr startpreptr ptrwhile(preptr -data !valpreptr ptrptr ptr -nextpreptr -next=ptr -nextfree(ptr)return startstruct node *delete_list(struct node *startstruct node *ptr/lines - were modified from original code to fix unresposiveness in output window if(start!=null)ptr=startwhile(ptr !nullprintf("\ % is to be deleted next"ptr -data)start delete_beg(ptr)ptr startreturn startstruct node *sort_list(struct node *startstruct node *ptr *ptr int tempptr startwhile(ptr -next !nullptr ptr -nextwhile(ptr !nullif(ptr -data ptr -datatemp ptr -dataptr -data ptr -dataptr -data tempptr ptr -nextptr ptr -next