0% found this document useful (0 votes)
11 views27 pages

Array

This document provides an overview of arrays in C programming, including definitions, declarations, and initializations of one-dimensional, two-dimensional, and multi-dimensional arrays. It explains how arrays can store multiple values of the same data type, facilitating efficient data manipulation and access. Additionally, it covers concepts such as dynamic arrays and the initialization of arrays at compile time and runtime.

Uploaded by

gstudy017
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)
11 views27 pages

Array

This document provides an overview of arrays in C programming, including definitions, declarations, and initializations of one-dimensional, two-dimensional, and multi-dimensional arrays. It explains how arrays can store multiple values of the same data type, facilitating efficient data manipulation and access. Additionally, it covers concepts such as dynamic arrays and the initialization of arrays at compile time and runtime.

Uploaded by

gstudy017
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
—— CHAPTER Array Ore Spt Upon completing this chapter, you will be able to: 108.1 Define the concept of arrays 10.8.2 Determine how one-dimensional array is declared and initialized 10.8.3 Know the concept of two-dimensional arrays 108.4 Discuss how two-dimensional array is declared and initialized 108.5 Describe multi-dimensional arrays 108.6 Explain dynamic arrays 8.1 | Introduction So far we have used only the fundamental data types, namely char, int, float, double and variations of int and double. Although these types are vary useful, they are constrained by the fact that a variable of these types can store only one value at any given time. Therefore, they can be used only to handle limited amounts of data. In many applications, however, we need to handle a large volume of data in terms of reading, processing and printing. To process such large amounts of data, we need a powerful data type that would facilitate efficient storing, accessing and manipulation of data items. C supports a derived data type known as array that can be used for such applications. ‘An array is a fixed-size sequenced collection of elements of the same data type. It is simply a grouping of like-type data. In its simplest form, an array can be used to represent a list of numbers, or 4 list of names, Some examples where the concept of an array can be used: List of temperatures recorded every hour in a day, or a month, or a year, List of employees in an organization. List of products and their cost sold by a store. Test scores of a class of students. List of customers and their telephone numbers. Table of daily rainfall data. i ‘and soon. | Since an array provides a convenient structure for representing data, it is classified as one of the date structures in C. Other data structures include structures, ists, queues and trees. A complete discussion of ell data structures is beyond the scope of this text, However, we shall consider structures in Chapter 10 and lists in Chapter 13. — ae Programming in ANSLC ‘As we mentioned earfier, an array is a sequenced collection of related data items that share @ common name. For instance, wa can use an array name salary to represent a set of salaries of a group of employees in an organization. We can refer to the individual salaries by writing a number called index or subscript in brackets after the array name. For example, salary [10] represents the salary of 10” employee. While the complete set of values is referred to as an array, individual values are called elements. The ability to tse a single name to represent a collection of items and to refer to an item by specifying the item number enables us to develop concise and efficient programs. For example, we can use a loop construct, discussed earlier, with the subscript as the control variable (0 read the entire array, perform calculations, and print out the results. We can use arrays to represent not only simple lists of values but also tables of data in two, three or more dimensions. in this chapter, we introduce the concept of an array and discuss how to use it to create and apply the following types of arrays. * One-dimensional arrays ‘© Two-dimensional arrays ‘* Multidimensional arrays 8.1.1 Data Structures C supports a rich set of derived and user-defined data types in addition to @ variety of fundamental types as shown below: Data Types eee =. a re 2 | Se | Derived Fundamental | | User-defined | | Types Types | | Types ~ Arays = Integral Types ~ Structures ~ Pointers ~ Float Types - Unions - Character Types = Enumerations amays and strictures are referred to as structured data types because they can be used to represent data values that have a structure of some sort. Structured data types provide an organizational scheme that shows the relationships among the individual elements and facilitate efficient data manipulations. In ming parlance, such data types are known as data structures. inaddition to arrays and structures, C supports creation and manipulation of the following data structures: «Linked Lists 2 Stacks © Queues » Trees 2 Graphs S Array ye ECC le tee) A ist of items may be given one variable name, and the individual elements may be accessed by the specification of their relative positions with respect | 40.8.1 to the start of the list. Such relative positions are referred to as the index or | Define the concept of ‘subscript of the element. Such a list in which the elements are accessible by | rays the variable name assigned to the list and its subscript is known as a one- dimensional array. For instance, we use the equation - x Rl to calculate the average of n values of x. The subscripted variable x, refers to the /” element of x. In C single subscripted variable x; can be expressed as x{i]. Notice that the subscript of the first element, that is, x{0] is 0. For example, if we want to represent a set of five numbers, say (35, 40, 20, 57, 19) by an array variable number, then we may declare number as follows: int number [5] and the computer reserves five storage locations as shown below: [———_ number [0] number [1] number [2] number [3] number (4] The values to the array elements can be assigned as follows: number [0] = 35; number [2] = 40; number [2] = 20; number [3] = 575 number [4] = 19; This would cause the array number to store the values as shown below: number [0] 35 number [1] 40 number [2] 20 number [3] 57 number [4] 1 A ‘These elements may be used in programs just like any other C variable, For example, the following are valid statements; a = number [0] + 10; number[4] = number[0] + number [2]; number [2] = x{5] + y[10]s value[6] = number[i] * 35 ‘The subscripts of an array can be integer constants, infsgor verses! like des . © performs no bounds checkir , there! ae ere bee sonar Dae anne the array indices are etbin the declared limits. _— a > Like any other variable, arrays must be declared before they are used sothat 14, the compiler can allocate space for ther in memory. The general form of array : declaration is Determine how one. dimensional array ic declared and initiating { type variable-namef size J; The type specifies the type of element that will be contained in the array, such as int, float, or char and the size indicates the maximum number of elements that can be store; in ime SILBYR LO © =St0PI0 float height [50] : declares the height to be an array containing 50 real elements. Any subscripts 0 to 49 are valid. Simiter, j int group[10] ; q declares the group as an array to contain a maximum of 10 integer constants. Remember: Any reference to the arrays outside the declared limits would not necessarily Cause an error. Rathe, , it might result in unpredictable program results = The size should be either a numeric constant or a symbolic constant. : The G language treats character strings simply as arrays of characters. The size in @ character st represents the maximum number of characters that the string can hold, For instance, "g char name[10]; declares the name as 2 character array (string) variable that can hold a maximum of 10 characters. Suppose ‘we read the following string constant into the string variable name. “WELL DONE” Each character of the string is treated as an element of the array name and Is stored in the memory as follows: on re * element space for the null terminator. ET 0" ‘When the compiler sees a character string, it terminates it with an additional null character. Thus, the element name[10] holds the null character '\0'. When declaring character arrays, we must allow one extté | WORKED-OUT PROBLEM 8.1 Write a program using a single-subscripted variable to evaluate the following expressions: 10 Total are read from the terminal. E for Easy, M for Medium and H for High float x{10], value, total ; «+ + «READING VALUES INTO ARRAY printf ("ENTER 10 REAL NUMBERS\n") 5 for(i =0; i <10; i+) scanf("sf", &value) 5 x(t] = value 5 } see + + COMPUTATION OF TOTAL total = 0.0; for(i =O: 1 < 103 1+) total = total + x[i] * x[i] + «+ PRINTING OF x[i] VALUES AND TOTAL . . . */ printf(*\n"); for( i= 0; i< 10; i+) printf("x[s2d] = %5.2f\n", i#1, xfi]) printf("\ntotal = %.2f\n", total) 5 ENTER 10 REAL NUMBERS 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.10 x 1] = 1.10 x{ 2] = 2.20 x[ 3] = 3.30 x[ 4] = 4.40 x[ 5] = 5.50 x[ 6] = 6.60 x[ 7] = 7.70 x{ 8] = 6.80 x[ 9] = 9.90 x[10} = 10.10 Total = 446.86 _ Programming it ANSLG Note C99 permits arrays whose size can be specified al run time. See Appendix "C99 Featuros” FMC ae Aftor an array is declared, its elements must be initialized. Otherwise, they will contain “garbage”. An array can be initialized at either of the following stages: + Atcompile time © Atrun time 8.4.1 Compile Time Initialization We can initialize the elements of arrays in the same way as the ordinary v The generat form of initialization of arrays is: type array-namo[sizo} = (list of values }; The values in the list are separated by commas. For exemple, the statement int number[3] = { 0,0,0 }: will declare the variable number as an array of size 3 and will assign zero to each element. If the number of values in the list is less than the number of elements, then only that many elements will be initialized. The remaining elements will be set to zero automatically. For instance, float total[5] = {0.0,15.75,-10}: will initialize the first three elements to 0.0, 15.75, and —10.0 and the remaining two elements to zero. The size may be omitted. In such cases, the compiler allocates enough space for al initialized elements. For example, the statement ariables when they are deciared_ int counter{ ] = {[Link]}: will deciare the counter array to contain four elements with initial values 1. This approach works fine as long as we initialize every element in the array. Character arrays may be initialized in a similar manner. Thus, the statement char name[ ] = {°J','0", ‘h’, ‘mn’, *\0"); declares the name to be an array of five characters, initialized with the string “John” ending with the null character. Altematively, we can assign the string literal directly as under: char name [ ] = "John® naracter arrays and strings are discussed in detail in Chapter 8.) ‘Compile time initialization may be partial. That is, the number of initializers may be less than the declared size. 11 such Gases, the ramaining elements are inlliaizad to zero, if the array type is numeric and NULL if the type Is char. For example, (cl int number [5] = {10, 20}; will initialize the first two elements to 10 and 20 respectively, and the remaining elements to 0. Similarly, the jaration. ees char city [5] = ('B'); will initialize the first element to “B' and the remaining four to NULL. It is a good idea, however, to declare the ‘size explicitly, as it allows the compiler to do some error checking. Remember, hawever, if we have more initializers than the declared size, the compiler will produce an error. fs, the statement pps int number [3] = (20, 20, 30, 40)5 wilt not work. It Is illegal in C. > Array 4.2 Run Time Initialization licitly initialized at run ti i it array can be explici z in time. This approach is usually applied for lizing large arrays. orexomple consider the following segment of a C eon, SE a for (i = 0; 1 < 100; 4 = 441) { if i<50 sum[i] = 0.0; /* assignment statement */ else sum[i] = 1.05 The first 50 elements of the array sum are initialized to zero while the remairing 50 elements are initialized to 1.0at nun time, We can also use a read function such as scanf to initialize an array. For example, the statements int x [3]5 scant ("xdedsd", &x{0], &E1], &xI2}); wil intialze array elements with the values entered through the keyboard, at runtime. WORKED-OUT PROBLEM 8.2 o Given below is the list of marks obtained by a class of 50 students in an annual examination. 43 65 51 27 79 11 5661 82 09 25 26 07 49 55 63 74 81 49 37 40 49 16 75 87 91 33 24 58 78 65 56 76 67 45 54 36 63 1221 73 49 51 19 39 49 68 93 85 59 Write @ program to count the number of students belonging to each of following groups of marks: 0-8, 40-19, 20-29.....,400. The program coded in Fig, 6.2 uses the array group containing 11 elements, one for each range of marks. Each element counts those values falling within the range of values it represents. For any value, we can determine the correct group element by dividing the value by 10. For example, Consider the value 59, The integer division of 59 by 10 yields 5. This is the element into which 59 is counted. Fdefine MAXVAL 50 fdefine COUNTER 11 rain() { float value[MAXVAL] 5 ‘int i, low, highs int graup[COUNTER] = {0,0,0,0,0,0,0,0,0,0,0}; Programming in ANSI C Output Pr + + + + sREADING AND COUNTING... . . .*/ for( 1 = 0 5 i < MAXVAL ; i++ ) { [hs os 0+ «+ READING OF VALUES 62.2. 1. / scanf("*f", &value[i]) 5 fi | /*. . . « .COUNTING FREQUENCY OF GROUPS... . . +/ + group[ (int) ( value[i]) / 10] ; } * /* . . . .PRINTING OF FREQUENCY TABLE... . .. . / printf("\n"); printf (" GROUP RANGE FREQUENCY\n\n") ; for( i= 0; i < COUNTER ; i++ ) { low = 4 * 10; if(i == 10) high = 100 ; else high = low + 9 ; printf(" %2d 53d to %3d %d\n", i+1, low, high, group[i] ) ; 43 65 51 27 79 11 56 61 82 09 25 36 07 49 55 63 74 81 49 37 40 49 16 75 87 91 33 24 58 78 65 56 76 67 (Input data) 45 54 36 63 12 21 73 49 5) 19 39 49 68 93 85 59 SROUP RANGE FREQUENCY 1 Beto 9 2 1 to 19 4 3) 20 to 29 4 4 30 to 39 5 5 40 to 49 3 6 50 to 59 8 q 60 to 69 7 8 7 to 79 5 9 80 to a9 c NY 9 to 99 > a 100 to 100 5 Fig. 8.2. Program for frequency counting two have used an Initialization statement ite tn int group [COUNTER] = {0,0,0,0,0,0,0,0,0,0,0}; by n be replaced ch 08 int group [COUNTER] = {0}; wa ntiatize all the elements 10 22r0, This ' ED-OUT PROBLEM 8.3 RK wo ram shown in Fig. 8.3 shows the algorithm, flowchart and the complete C program to find the *e compliment of a binary number. [L two problem Analysis Thez’s complement of a binary number is defined as the 1's complement of the number plus 1. Consider the folowing examples: Number 1’s Complement 2's Complement (11010101) (00101010) (00101011) (11111111) (00000000) (00000001) (10011000) (01100111) (01101000) (00000000) (11411111) (00000000) Algorithm Step 1 - Start Step 2 - Read a binary number string (a[]) Step 3 — Calculate the length of string str (len) Step 4- Initialize the looping counter k=0 Step 5 — Repeat Step 6 while a[k] f= ‘\0’ Step 6 = If a[k]!= 0 AND a[k]!= 1 Display error "Incorrect binary number format" and terminate the program else kekel End If End While Step 7 — Initialize the looping counter i = len- 1 Step 8 — Repeat Step 9 while aLi]!="'l' Step 9 — Rise tte End While Step 10 ~ Initialize the looping counter j = 4-1 ane 11 ~ Repeat Step 14-15 while J >= 0 oe AG. = If a[j}=1 a[i]='0" else ‘$0 far we have discussed the array variables There could be situations where a table of v ‘Consider the following data table, which shows L Programming in ANSI C ‘The table contains a total of 12 values, three in each fine. We can think of this table as. a matrix consisting ‘of four rows and three columns, Each row represents the values of sales by a particular salesgirl and each ‘column represents the values of sales of a particular item. In mathematics, we represent a particular value in a matrix by using two subscripts such as vy, Here y denotes the entire matrix and vy refers to the value in the (® row and j” column. For example, in the above table V2, refers to the value 325. C allows us to define such tables of items by using two-dimensional arrays. The table discussed above can be defined in C as vi4][3) ‘Two-dimensional arrays are declared as follows: type array_name [row_size}[column_size]; Note that unlike most other languages, which use one pair of parentheses with commas to separate array sizes, C places each size in its own set of brackets. ‘Two-dimensional arrays are stored in memory, as shown in Fig. 8.4. As with the single-dimensional arrays, ach dimension of the array is indexed from zero to its maximum size minus one; the first index selects the Tow and the second index selects the column within that row. Columnd: Column Column2 tls he fo}t2) Row Oo 310 Tos F 365 | (10) tt) (121 Row 1 10 190 325 | (2) {0} IN) tifa) Row 2-0 405 2s || so) Row 3-7 310 215 265 Fig. 8.4 Representation of a two-dimensional array in memory 'WORKED-OUT PROBLEM 8.4 ‘Write 8 program to compute and print a multiplication table for numbers 1 to 5 as shown below. Array | shown in Fig. 8.5 uses a two-dimensional array to store the table values. Each value is calculated Savon cra variables of the nested for loops as follows: 2 product[i] [J] = row * column where i denotes rows and j denotes columns of the product table. Since the indices | and j range from 0 to 4, ‘we have introduced the following transformation: row =i+1 ‘column = |+1 f#define ROWS #define COLUMNS main() { int row. column. product [ROWS] [COLUMNS] ; fot (31 5 printf(* MULTIPLICATION TABLE\n\n") 5 printt(* ") for( j - 15 j <= COLUMNS ; j++ ) printf("%4d" , 3) 5 printf(*\n") 5 print f(*$_—————_—___—\n") 5 for( 1 = 03 1 < ROWS 5 itt ) { rows i+); printf("%2d |", row) = for( j= 13 J <= COLUMNS ; j++) { column = 3 3 product[#] [j] - row * column 5 printf("44d", product{iJ[J] ) + } printf("\n*) 5 MULTIPLICATION TABLE 2 4 a Programming in ANSI C r WORKED-OUT PROBLEM 8.5 Write @ program using a two-dimensional array to compute and print the following information from the { table of data discussed above: (2) Total value of sales by each girl. (b) Total value of each item sold. (c) Grand total of sales of all items by all girls. The program and its output are shown in Fig. 8.6. The program uses the variable value in two-dimensions. with the index i representing girls and j representing items, The following equations are used in computing the results: 2 (@) Total sales by m"” girl = yy value (m){j] (gitl_total{m}) 0 (b) Total value of n® item = XY value [il{n] (item_total(n}) 3 2 (©) Grand total = > > vauetuur i=0 120 3 > air tory ° 2 > item_totalfi] i #define define main() { int value[MAXGIRLS] [MAXITEMS] ; int girl_total[MAXGIRLS] , item total [MAXITEMS]; int 1, J, grand_total; (/*-++++--READING OF VALUES AND COMPUTING girl total ...*/ printf(*Input data\n") ; printf("Enter values, one at a time, row-wise\n\n"); for( 1 = 0 ; 4

You might also like