0% found this document useful (0 votes)
20 views34 pages

Chapter 5 (PIC)

An array is a finite, ordered set of homogeneous elements that allows storage of multiple values under a single name, with elements accessed via indices. Arrays can be one-dimensional, two-dimensional, or multi-dimensional, and they are allocated memory contiguously. The document also discusses array declaration, memory allocation, and examples of one and two-dimensional arrays in programming.

Uploaded by

Shubham Sanger
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
20 views34 pages

Chapter 5 (PIC)

An array is a finite, ordered set of homogeneous elements that allows storage of multiple values under a single name, with elements accessed via indices. Arrays can be one-dimensional, two-dimensional, or multi-dimensional, and they are allocated memory contiguously. The document also discusses array declaration, memory allocation, and examples of one and two-dimensional arrays in programming.

Uploaded by

Shubham Sanger
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 34
ARRAY CHAPTER narray isa finite, ordered set of homogenous elements. Ane is defined as collection of related items. All the items are of similar data types. All items or elements are assigned a common name. Ordinary variables can hold only a single value at a time if one wants to store more than one values at a time having a single name, he has to use arrays. Array is also defined as collective name given to group of values. Arrays are allocated memory in contiguous manner. ‘The storing and retrieving of data in array is done in sequential manner. The elements can be of primitive type or may be string type or record type. The only difference is that the dimension of array may change depending on type of its elements, It is some times called as linear array. An array is a finite, ordered set of homogeneous elements i.e. the elements are of same type. Ordered means that first, second, third......... nth elements of an array can be identified. For this an integer data is used which is known as index. The elements of an array are stored in successive memory location. The first element of an array is assumed to have base address. Rest of them have consecutive address for consecutive elements. Thus the linear list remains ordered. Array elements are also known as subscripted variables because all of them have same name but different subscripts (Index number) for their identification. To understand an array let us move into real world problems. Let there are hundred students and you have to give them books. If all of them stand there in a huge group it will be difficult for 205 NORTH Progr: ee Array name Seutlent can Seudent 1 Anil Student 2 Gopal Seudent 3 Values of An array array elements [Varun ft— Student 100 Array elements FIG. 5.1 you to distribute the book and you will have no identification for them in the sense that who have got the book and who not. To solve this problem we arrange them ina row and then call them as student (1), student (2) ......... student (100). Now you can call them one by one as student (1), note this here name and give the book, call student (2), note name, give book and so on. Now this is exactly an array where there are 100 elements. Name of array is STUDENT and 1, 2, 3.. 100 are subscripts or index numbers. Now it is worth to say that as this array required only one subscript with each element for its identification so it is a one dimensional array. Name of the students will work as value stored in array elements. See fig. 5.1 sTuD Saud [ Stud | Sad [Sead | Stack an | a.2 Las) laa | as) Rows Sud Se a 3) ‘Columns FIG. 5.2 A two dimensior | ar:av An array may be one dimensional, two dimensional or multidimensional. It i® the problem, discussed above, we arrange them in ten rows and ten columus and ¢ them as student (1,1) for student of first row and first column, student (1.2) { student of first row and second column and so on finally student (10,10) for studet" of tenth row and tenth column then it is a two dimensional array. For accessing & 5 oe ner ae aT has two dimensions one for row and other for column. This is a two . See fig. 5.2. onsionall array Now if the same are arranged in five rooms each containing four rows and five ig students then we need three index numbers with each element. One than thre’ ample think of the case of 10 schools , each having five rooms and in each room students are standing in four rows and five columns resulting in an array of 1000 elements like stud (1,1,1,1), stud (1,1,1,2) stud (1,1,1,..... stud (10,5,4,5). This show: . nth term) stud (1LLjcee. 2 nth a four jimensional array. Similerly stud (n, tern) «. . nth term) shows representation of an n dimensional amay, It is really difficult to explain the multidimensional array system but if in above case you assume and proceed step by step like cities, sector, lanes, schools, floors, rooms, rows, columns ete you can easily understand the multidimensional array. 52 ONEAND TWO DIMENSIONAL ARRAY © allows declaration of n dimensional arrays but practically only one dimensional and two dimensional arays are used. For using an array in a program it should first be declared in declarative parts. The declaration is very much similer to that of declaration of simple variables However it needs size declaration also along with type and name declaration. For one dimensional array one subscript size is f two subscripts are required and so on. The needed, for two dimensional array size o} general format for declaring an array is #include #define max 100 main() { int i,n,atmax}; /* read the array »/ Printf(“\n enter number of Scanf("%d",6n); for(i=0; « elements in the array”); isn;i++) Print£(“\n Enter #4 th element” ritl); Scanf(“ta",garij); print£(“\n\n The array is as follows : \n"); for (i=0;i Columns rows ] Example: inta; [- a __ eubscripted variable, there can be one or two or three or more y is su the dimension of array. Array contain a number of Whereas arra’ : subscripts depending ¥P® memory locations: y a vy ay ate Ale 5.2.5 There can be following types of subscripts 1. Integer 2, Symbolic 3. Negative Subscript is also called as index of array. 5.2.6 Declaration of Array using integer subscript + int a [5]; Declaration of Array using symbolic subscript : int a [size]; Declaration of Array using negative subscript : int a [-5]; If is beneficial to use symbolic name as array index because whenever theres change in size of array we will change it at one place it will be change! automatically. ‘The index can be negative because there is no checks on bounds of array. Note : Size of array can’t be float or character value. Some examples on declaration of Single Dimensional array int a [5]; It is an integer array of five elements. float a [5] ; It is an array of five elements of float data type. double a [5]; It is an array of five elements of double data type. char a [5] ; It is an array of five elements of character data type. Examples on Declaration of Two Dimensional Array int a [5] [5] ; It is an integer array having five rows and columns. 213 yy Z Aoat a (9) [2] ; It is float array having three rows and two coh double a [3] [3] ; It is double array having three rows and three columns, lumns, 32.7 Allocation of Memory to Array The array is assigned memory durin; amount of memory assigned to array depe jedared to be integer then each block or nemory of 2 bytes. If array is of float data nemory of 4 bytes. If array is of character nemory of 1 byte. Following examples shows elements of various types of arrays. ig the compilation of the program. The nds on data typeof array. If an array is each element of array will be assigned element is assigned how memory is allocated to various 1 integer array int a [5] ; 2bytes bytes bytes bytes 2bytes | a0) all] a] als] ala] Total memory allocated to array =10 bytes. a will be = no. of elements x data typeie. 5x2 2. character array char a [5] ; Ibyte_Ibyte _Ibyte _Ibyte _Ihyte OT Total memory allocated to array a will be = number of element x data type ice. 5 1=5 bytes 8. float array float a [5] ; | Abytes _dbytes bytes dbytes abytes sel MaRS) ary pet RR ge Se 214 NORTH Progra, une Total memory allocated to array a will be = number of elements * data ty, : i 5X 4= 20 bytes ™ 4. double array Sbytes sbytes Sbytes Sbytes Sbytes a0] afl} a2] a3] a4] Total memory allocated to array a will be = number of elements x data type, 5 X 8 = 40 bytes Size of two dimensional array 1. integer array int a [2] [3]; afo}(0} | af0}{1] } al0}l2) afi}{0} | aft) | aft][2) Note : In above figure, each block is of two bytes. Here array has two rows and three columns so there will be 2 x 3 = 6 elements or memory locations. The array is of integer data type so total memory allocated to array will be = number of elements x data type i.e. 6 x 2 = 12 bytes. 2. float array float a [2] [3] ; a(0](0] } af0}[1] | afo}(2] a(1][0] } a(1](4) | a(t] Note : In above figure each block is of 4 bytes. Here array has two rows and three columns so there will be 2 x 3 = 6 elemem™® or memory locations. The array is of float data type so total memory allocated array will be = number of elements x data type = 6 X 4 = 24 bytes. she qhe 215 e pase Address Of One Dimensional Array 52 . i Base see i fet is address of first clement of array. It is assigned to ier. If we know the base address then esl f ae be done using formujes ‘ation of address of any other al d fourth will be 1002, tiated memory of two bytes, is TiYie8 Dhytes abyteo _Bbytes 2byten alo} 1000 1002, al2] 1004 [3] 1008 ala) 1008 The address of zeroth element i.e, a [ The address of first element ive. a {1] The address of second element i. a [ ‘The address of third element ie, a [ ‘The address of fourth element iea Note : We can’t assign or change th 0] will be 1000 will be 1002 2] will be 1004 3] will be 1006 [4] will be 1008, e base address of array. 5.29 Base Address of Two Dimensional Array In two dimensional array there are two an array, 1, Row-major order 2.Column major order, 1. Row-major order methods of storing data of elements of 'n row-major order elements of array are stored row-wise, First of all data will be fl led in first (zeroth) row and then data will be filled in second row and then in ‘hid row and 80 on. Example : v2 81 I= ¢t1, 2), (3, 4), (5, 6}; ‘alue assigned in row-major order a [0] [0] = 1 a [0] {lj=2 . ° all} [o}=3 ; 7 all} tjs4 ; a a [2] [o)=5 FS all tj=6 SaaS 216 ORTH 1) | Storing Values in Row-major ordor Values assigned in column-major order a (0) (0}=1 a[1} (o}=2 i [a a [2] [0)=3 2 [| o alo} [l}=4 a | a(t} (=5 | a[2])=6 Storing values in column-major order If base addr 1000 then next address will be 1002 which will be of a {1) y in case of column-major order and a [0] [1] in case of row-major order, 5.2.10 Initialization of Array igning values to the elements of array. Initialization can be on or during execution of program. If no value is assigned age value will be assigned to the elements of ng them in by and separating them array : It is defined as done during declar: during declaration then by default gark array. The values are initialized by wr using comma. Following example shows initializ: Lion of intey Bbyton Abytow 2 If array is only declared no value is assigned to it then by default garbage will be assigned. Example : int a [5]; iyton Ayton 2hytow —_hytox _abytay [sare arb | rerbag twins] etn ai) S088) arg If size of array is not specified and values are inigi : i ‘ automatically assigned as per number of values available ‘ved then values will ye: sa) (28.4515 apytes abytes 20YL0S 2bytes ahytas 2 3 4 5 ata] wo et) A) al8] nt of value of float array (5) ={0.5, 0, 0.9, 1.6, 2.0}; Abytes Abytes bytes _Abytes Abytes os | 0 | 09 | 16 | 20 ao att} a] as} all Assignment of values to character array For assigning values to character array, characters are separated by commas and also written in single quotes Example : char name [5] = £a’, ‘B,C, Dp, E}; byte _Tbyte_Ibyte_Tbyte_Tbyte A B|c D E Fane[o) nameli] namel2) name(s] name Initialization of Two Dimensional Array Like one dimensional array, two dimensional arrays can also be assigned values during its declaration. Following example shows declaration of 3 x 3 array and assigning of values to this array int a [3] [3] = or= (1, 2,3, 4, 5,6 78 5 1 2 | 3 4 6 | 6 7 | 8 | 9 ‘The a [0] {0} will be assigned value = 1 ‘The a {0} {1) will be assigned value = 2 ‘Phe a {0} 2) willbe assigned value = 3 ‘The a (1) {0} will be assigned value = 4 me a [1] [1] will be assigned value = 5 > | 18 Pho a [1] [2] will be aasianed value © 6 Tho a [2] [0] will be avvigned value #7 Pho a {2} {1} will be aatigned valuo = 8 ‘Tho a [2] [2] will be assigned value ® 9 One stop and two stop initialization of Array int a [5 int a[5] 7 a cop 2 dl} atl) = {27 a [2] (3) 7 ais} = (4) 3 a (4) {5} i * single step */ « gwo step initialization */ 5.3. ARRAY OPERATIONS Following are the operations that can be performed on single as well as two dimensional array : Ins tion : It is a process of adding new element to the array. Deletion : It is process of deleting single or more than one e array. rangement of elements in particular order. Order Sorting : It is process of can be T start to end exactly once. cending or descending. versal : It is visiting or accessing cach and every element of an array from Merging : It is process of combining two arrays into single one. Searching : It is process of finding particular element in array. Search is of two types : Linear and Binary. 5.3.1 Operations on Two Dimensional Array 1. Transpose of array w Printing of Diagonal elements of array 3, Rowwise sum of elements Columnwise sum of elements Display of data in row-major order Display of data in column-major order Printing of lower triangular matrix nee printiN6 Of Upper triang o, Finding Determinant of matrix yo, Finding Inverse of matrix 1, Addition, subtraction, multiplication of two matrices ete, gy Storage Class Specifier with Array o storage ch a ; If no storage clan is specified then it will be automatically assigned auto jorage C140 datatype Array Name | ai t -— Brackets . specification (optional) Static Storage Cla: static int a [5] ; Ifarray is declared as static then all elements will be assigned value nother value is assigned. Peer] 53.3 Accessing the Elements of Array zero, if Once array is declared its element an be assessed individually. The accessing is done with the help of index or subscript. The index specify position of an element inthe array, The elements of array start from zero. Accessing Single element of one Dimensional Array int a [5] = {1, 2,3, 4, 5}; For assessing the second element of array, we will give index as a [1] and value 2will be assessed. Accessing all elements of O' eee s low : For this, for loop is used as given ' - for (i = 0 a<5;it { ne Dimensional Array (rea\nt'r printf "This proues ab alld 2s This process is also called ag Yeading the elements from array or Semin og array, The following program shows entering of data into a: from the array : #include #include main ( ) { and printing of data int k, a [5) ; / * Entering data into array */ For (K= 0; K <5; K +4) { printf (’‘\n Enter number’’) ; scant (‘‘td'', ga (K]) ; } / * Printing data of array for (K= 0; K<5; K-44) { Printf (‘‘\n Element a (8d) is = ¢a’’, K, a [K) ); 2 Accessing single element of Two Dimensional Array Once two dimensional array is defined its single ele: writing array name followed by two subscripts. Example int a [3] [2] = (1, 2, 3, 4,5, 6); For accessing first row and first column, a [0] [0] = 1 For accessing first row and second column, a [0] [1] For accessing second row and first column, a [1] [0] = For accessing second row and second column, a [1] {= For accessing third row and first column, a [2] [0] = 5 For accessing third row and second column, a (2) Q)=6 Accessing all elements of Two Dimensional Array #include ‘ment can be accessed by 224 ww Trek pint main ( ) x oe int dy Je Mum [10] [10], Py a printf (‘‘Enter number of rows of array''); scanf (‘'8d'', & P); , printf (‘Enter number of columns of array’'); scanf (‘'#d'', &q) ; ' printf (‘‘\n Enter elements in array’') ; Yor (6807 i #include #define max 10 void main() { int i, 3m Mer ePF int a{max] {max} ,b{max} {max} ,c(max] [max]; rix / /* exp is order of matrix b «/ printf("\n Enter order of matrix A"); scanf("td #d”,&m,bn); i printf£("\n Enter order of matrix BY); scanf("*d *d”,&r, 4p); : if(m t= r || n t= p) { print£(“\n Order mismatch. Matrices cannot be added») return; /* read the matrix A */ for (i=0;i 10. Any particular element of array disturbing array, 11. Array can be initialized value during the declaration or run time, can be modified independently wit, t 5.5 DRAWBACKS OF ARRAY 1. There is no method to initialize only selected elements of array. 2. There is no method of initializing large number of elements of an array. 5.6 MULTIDIMENSIONAL ARRAY If an array has more than two dimensions or subscripts or indexes, we call it as multi dimensional array. In C, the limit of dimension of array is determined by compiler. Three dimensional array can be called as array of arrays. Suppose we have declared an array as ... [size n] General form of Multi Dimensional Array arrayname [sizel] [size2] datatype ‘ ‘ int a [5] [5] [5] int a [5] [5] [5]; ' In this first subscript indicate number of arrays. Second subscript indicat® indicate number of colums. So in above declaratio ubscript i s each having five rows and five columns. So in above number of rows. Third s will be five array: Hatt il] be five arrays each having twenty five elements. declaration there wi it as ree linn. So there be two 2D a panne T te Accessing elements jn mul mee (0] [1] [2] will access 5, the a [1) [2] [3] will access g, the « 2] [3] [3] will access g, tidimensional array int ab [5] [2] [3] ; int bb [3] [5] [2] ; float num [5] [4] [5] (2) . The array ab has 5 x 2 x 3 = 39 integer elements, ‘The array bb has 3 x 5 x. 2=30 integer elements, ‘The array num has 5 x 4x5xQ= 200 float elements, Initialization of Multi D: static int table [2] [3] (2) Inthis example, there w: imensional Array = 2, 4}, £7, 8}, (3, 4, {7, 8}, £3, 4}, 15, 3}; ill be two arrays. Each array will have three rows and "rays having three rows and two ¢ olumns, Entering thi Hinclude < Hnclude < Main ( { e data using loops Stdio.h> ‘Conio.h> intl, om, on ; int num (2) (2) ee tag ; for tm a (2) = { {1 4), (1, 6}, (2, 793; I< 2 1 fe) Oy w< 2 amt ¢) Benita n<2;n+*) for (n= 0 printf (‘‘\t td’’, @ (1) (m] ["]) getch ( ); , /* PROGRAM TO ACCEPT 5 ELEMENTS IN ARRAY AND PRINT 5 ELEMENTS */ #include #include main() { int i,num[10); elrser(); for(i=0;i<5;i++) Q printf(“\n enter values=>"); scanf(“%d”, &num[i]); D printf£(“\n elements of array are=>"); for(i=0;i<5;i++) printf£(“ %d”,num[i}); getch(); } OUTPUT g enter values=>3 enter values=>6 enter valu 7 enter values=>8 enter values=>9 ELEMENTS OF ARRRAY ARE=>3 67 § 9 ) Wine} ROGRAM TO F LARGEST ne ypcrudecstdio-N> ELEMENT AMONG 10 ELEMENTS"! ude oil) int i,num[10), Margestao, elrscr()i print£(“enter 10 elements» for(iz=07i<10;it+4) ee”) ic printf(“\n enter 4 elene scanf("%d", num ij); } largest=num[0]; for(i=0;i<10;i++) 4 if(largest" 44); OUTPUT enter 10 elements’ enter Oth elements enter 1 elements= enter 2 elements enter 3 elements =>3, enter 4 elements=>3 enter 5 elements=76 enter 6 element 8 enter 7 elements=>3 enter 8 elements=>9 enter 9 elements=>5 enter 10 elements=?7 largest element = 9 */ | 228 TO PR #include #include void main() { NORTH Prog am SUM OF EACH ROW,COULMN OF MATRIx#; ul he int a[3][3],i,j,row,col,rowtotal[3]; int coltotal[3],grandtotal=0; elrser(); printf(“\nEnter no. of rows & coulmns(max. limit is 3)", scanf(“%d %d”, &row, &COl) ; Ei printf(“\nEnter the elemets in matrix:\n”); for (i=0;i ‘inelude Main() { int i,num[10],sum=0; float average; clrser(); Printf(“enter 10 element for(i=0;i<10;i++) { "ili Printé(“\n enter $d element mu s=>")i 230 scanf(“%d”, num[i]); } sum=sumtnum[ i); } average=(float)sum/10; print£(“\n average=%f", average); getch(); } OUTPUT enter element=>5 enter element=>6 enter element=>7 enter element=>8 enter element=>9 enter element=>4 enter element=>2 enter element=>1 enter element=>3 enter element=>1 average=4,600000 af /* PROGRAM TO ACCEPT ELEMENTS OF 2 MATRICES FIRST MATEO HAVE 2 ROWS AND 2 COLUMNS SECOND MATRIX HAS 3 ROWS AN! COLUMNS */ #include #include main() int a(2][2],b[3] (3),4,5 clrser(); hays, for(i=0;4<2;i+4) for(J=075627 j44y ee Values-s,, seanf("84", Saf i}(5)), + } for(i=0;i<2;i++) { for (3=0;5<2; 54+) { printf(” 8d",ali}(5}); } print£("\n"); Mi for(i=0;i<3;i++) { for (j=0;j<3; j++) { print£(“enter values=>"); | scanf(“td",ab[iJ](j])i ti } } for(i=0;i<3;i++) { for (j=0;5<3;5++) ‘ Printe(” 9d”,b(i](J})7 } Print£(“\n"); } getch(); 232 OUTPUT enter valu 5 enter values=>6 enter value: enter values=>4 45 64 enter values=>3 enter values=>4 enter values=>3 enter values=>5 enter values=>7 enter values=>8 enter values=>9 enter values=>33 enter values=> 22 343 578 9 33 22 al /* PROGRAM TO FIND SUM OF TWO 2*2 MATRICES */ #include #include main() fi int a{2][2],b(2}[2],cf21[2],i,3; elrscr(); /* INPUT VALUES IN FIRST MATRIX */ printf(“\n enter values in first matrix\n"); py i<2iit+) v or! j<2i j++) (oe oii { wenter val tf ( Nes Of an, a mere” 20415}, Ns ; } ut VALUES IN gr, ja iNet OND wanery i: (*\nenter values of seq 0 jntt a 0;i<2;itt+) nd Matrix\any, gor (3707 poe 507325544) ( peinté(wenter values of bu>"), scant (“84", (4][5])¢ ) } /#PRINTING OF FIRST MATRIX +/ for (i=0;i<2;4i++) { + for (j=0;5<275++) { print£(“ ga”,afill5])i } print£(“\n"); } prx */ [PRINTING OF SECOND MM print£(“\n"); for(i=0;i<2;it+) if for(j=0;5<275+*) 234 peane ee’ ea”,b(i}[5]) } printé(“\n"); , /* ADDITION OF TWO MATRICES IN THIRD MATRIX AND Dispry RESULT*/ printf(“\nresult after addition of two Matrices”), print£(“\n"); for(i=0;i<2;i++) { for (j= { re efi}(j]=alil(j)]+blillil; 4<2;5++) printf(“ %d”,c[i}[j]); } printf£(“\n"); } getch(); /* OUTPUT enter values in first matrix enter values of a=>4 enter values of a=>5 enter values of a=>6, enter values of a=>g. enter values in enter values of g enter values of cond matrix 3 enter values of a=>7 enter values of a=>5 98 13 13 4 295 i ana TO ACCEPT ELEMENTS OF 3*3 MATRIX AND PRINT AL! fT ELEMENTS AS ZERO’S #/ ys BU giudecstdio-h> ee jude 8 pincl goin) {gmt al3](31e4,3; clrscr(); for (i=0;i<3;i++) { for (j=0; }<3; j++) printf (“enter elements=>") scanf("%d", &a[i}[5}); t } for (i=0;i<3;i++) { for (j=0;5<3; j++) { afil(j]=0; printf£(“\t $d4”,a(il(j]); } print£(“\n"); + getch(); } OUTPUT enter elements=>5 enter elements=>4 enter element: enter elements=: enter element: enter elements=>7 000 900 900 ¥ 236 /* PROGRAM TO FIND A PARTICULAR NUMBER FROM ARRAY, #include #include #include main() { int num,a[10],i, flag elrser(); printf(“enter number to be find=>”); scanf(“%d", num); for(i=0;i<10;i++) { printf(“\nenter %dth element in array=>",i); scanf("%d",&a[i]); _ | main( for(i=0;i<10;i++) a ‘ | if(ati | ; | flag=0; | break; | } + if(flag==0) printf(“\nnum is present”); else printf(“no is not present); getch(); } | 2 237 Array » OUTPUT enter number to be find=>7 enter Oth element in array=>5 enter 1th element in array=>7 enter 2th element in array=>8 enter 3th element in array=>9 enter 4th element in array=>10 enter 5th element in array=>4 enter 6th element in array=>5 enter 7th element in array=>11 enter 8th element in array=>12 enter 9th element in array=>131 4 /* PROGRAM OF BUBBLE SORT */ finclude #include #include main() { int n,i,j,num[5],temp; clrscr(); for(i=0;i<5;i++) { print£ (“enter values=>"); Scanf(“ %d”,&num[i]); Printf(“\ndisplay of elements before sorting\n”); for(i=0;i<5;i++) { Gg $d” ,num[i]); = = NORTH P; /* sorting of elements */ for (i=0;i<4;i++) { for (j=0;5<4;5++) if (num j]>num[ j+1]) { temp=num(j]; num[j]=num[ j+1]; num[ j+1]=temp; } + printf(“\ndisplay of elements after sorting\n”); for (i=0;i<5;i++) { printé(" %d”,num[i]); i} getch(); } /* output enter values=>6 enter values=>g enter values=>3 enter values=>4 enter values=>2 display of elements before sorting 68342 display of elements after sorting 23468 a fee ee

You might also like