0% found this document useful (0 votes)
14 views8 pages

Unit I - Arrays at CSJMU - 6 Slides Handouts

Unit I Arrays @ CSJMU_6 Slides Handouts

Uploaded by

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

Unit I - Arrays at CSJMU - 6 Slides Handouts

Unit I Arrays @ CSJMU_6 Slides Handouts

Uploaded by

raghvendrac210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

1 2

Arrays 1 Introduction

Outline • Arrays
1 Introduction – Structures of related data items
2 Arrays
3 Declaring Arrays – Static entity – same size throughout program
4 Examples Using Arrays – Dynamic data structures
5 Passing Arrays to Functions
6 Sorting Arrays
7 Case Study: Computing Mean, Median and Mode Using Arrays
8 Searching Arrays
9 Multiple-Subscripted Arrays

Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

1 2

3 4
Name of array
2 Arrays (Note that all 2 Arrays
elements of this
• Array array have the • Array elements are like normal variables
same name, c)
– Group of consecutive memory locations c[ 0 ] = 3;
– Same name and type c[0] -45 printf( "%d", c[ 0 ] );
c[1] 6
– Perform operations in subscript. If x equals 3
• To refer to an element, specify c[2] 0
c[3] 72 c[ 5 - 2 ] == c[ 3 ] == c[ x ]
– Array name c[4] 1543
– Position number c[5] -89
c[6] 0
• Format: c[7] 62

arrayname[ position number ] c[8] -3


c[9] 1
– First element at position 0 c[10] 6453

– n element array named c: c[11] 78

• c[ 0 ], c[ 1 ]...c[ n – 1 ]
Position number
of the element
Arrays Unit I
within array c Porwal
Dr. Rabins Arrays Unit I Dr. Rabins Porwal

3 4

5 6

3 Declaring Arrays 4 Examples Using Arrays


• When declaring arrays, specify • Initializers
– Name int n[ 5 ] = { 1, 2, 3, 4, 5 };
– Type of array – If not enough initializers, rightmost elements become 0
– Number of elements int n[ 5 ] = { 0 }
arrayType arrayName[ numberOfElements ]; • All elements 0
– Examples: – If too many : a syntax error is produced (syntax error)
int c[ 10 ]; – C arrays have no bounds checking
float myArray[ 3284 ]; • If size omitted, initializers determine it
• Declaring multiple arrays of same type int n[ ] = { 1, 2, 3, 4, 5 };
– Format similar to regular variables – 5 initializers, therefore 5 element array
– Example:
int b[ 100 ], x[ 27 ];

Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

5 6

Compiled by: Dr. Rabins Porwal 1


1 /* fig06_08.c 7 8
2 Histogram printing program */ Outline Element Value Histogram
Outline
3 #include <stdio.h>
0 19 *******************
4 #define SIZE 10 1 3 ***
5
1. Initialize array 2 15 ***************
Program Output
6 int main() 3 7 *******
4 11 ***********
7 { 2. Loop 5 9 *********
8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 6 13 *************
9 int i, j; 7 5 *****
10 3. Print 8 17 *****************
9 1 *
11 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );
12
13 for ( i = 0; i <= SIZE - 1; i++ ) {
14 printf( "%7d%13d ", i, n[ i ]) ;
15
16 for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */
17 printf( "%c", '*' );
18
19 printf( "\n" );
20 }
21
22 return 0;
23 }

Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

7 8

9 1 /* fig06_10.c 10
2 Treating character arrays as strings */ Outline
4 Examples Using Arrays 3 #include <stdio.h>
4 1. Initialize strings
5 int main()
• Character arrays 6 {
2. Print strings
– String “first” is really a static array of characters 7 char string1[ 20 ], string2[] = "string literal";
8 int i;
– Character arrays can be initialized using string literals 9
2.1 Define loop
char string1[] = "first"; 10 printf(" Enter a string: ");
• Null character '\0' terminates strings 11 scanf( "%s", string1 ); 2.2 Print characters
12 printf( "string1 is: %s\nstring2: is %s\n" individually
• string1 actually has 6 elements
13 "string1 with spaces between characters is:\n",
– It is equivalent to 14 string1, string2 ); 2.3 Input string
char string1[] = { 'f', 'i', 'r', 's', 't', '\0' }; 15

– Can access individual characters 16 for ( i = 0; string1[ i ] != '\0'; i++ ) 3. Print string
17 printf( "%c ", string1[ i ] );
string1[ 3 ] is character ‘s’
18
– Array name is address of array, so & not needed for scanf 19 printf( "\n" );

scanf( "%s", string2 ); 20 return 0;


21 }
• Reads characters until whitespace encountered
Enter a string: Hello there
• Can write beyond end of array, be careful string1 is: Hello Program Output
string2 is: string literal
string1 with spaces between characters is:
H e l l o
Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

9 10

11 12

5 Passing Arrays to Functions 5 Passing Arrays to Functions


• Passing arrays • Function prototype
– To pass an array argument to a function, specify the name of void modifyArray( int b[], int arraySize );
the array without any brackets – Parameter names optional in prototype
int myArray[ 24 ]; • int b[] could be written int []
myFunction( myArray, 24 ); • int arraySize could be simply int
• Array size usually passed to function
– Arrays passed call-by-reference
– Name of array is address of first element
– Function knows where the array is stored
• Modifies original memory locations
• Passing array elements
– Passed by call-by-value
– Pass subscripted name (i.e., myArray[ 3 ]) to function
Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

11 12

Compiled by: Dr. Rabins Porwal 2


1 /* fig06_13.c 13 33 14
2 Passing arrays and individual array elements to functions */ Outline 34 void modifyArray( int b[], int size ) Outline
3 #include <stdio.h>
4 #define SIZE 5 35 {
5 1. Function definitions 36 int j; 3.1 Function definitions
6 void modifyArray( int [], int ); /* appears strange */
37
7 void modifyElement( int );
8
2. Pass array to a function 38 for ( j = 0; j <= size - 1; j++ )
9 int main() 39 b[ j ] *= 2;
10 { 2.1 Pass array element to 40 }
11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i;
a function 41
12
13 printf( "Effects of passing entire array call " 42 void modifyElement( int e )
14 "by reference:\n\nThe values of the " 3. Print 43 {
15 "original array are:\n" );
16 44 printf( "Value in modifyElement is %d\n", e *= 2 );
17 for ( i = 0; i <= SIZE - 1; i++ )
Entire arrays passed call-by-
45 }
18 printf( "%3d", a[ i ] ); reference, and can be modified
19 Effects of passing entire array call by reference:
20 printf( "\n" ); Program Output
The values of the original array are:
21 modifyArray( a, SIZE ); /* passed call by reference */ 0 1 2 3 4
22 printf( "The values of the modified array are:\n" ); The values of the modified array are:
23 0 2 4 6 8
24 for ( i = 0; i <= SIZE - 1; i++ ) Array elements passed call-by-
25 printf( "%3d", a[ i ] ); Effects of passing array element call by value:
value, and cannot be modified
26
27 printf( "\n\n\nEffects of passing array element call " The value of a[3] is 6
28 "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] ); Value in modifyElement is 12
29 modifyElement( a[ 3 ] ); The value of a[3] is 6
30 printf( "The value of a[ 3 ] is %d\n", a[ 3 ] );
31 return 0;
Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal
32 }

13 14

15 16

Array Operations Algorithm for Array Traversal

• Traversal – the operation of visiting/ printing all Let arr be a linear array with lower bound LB
elements of an array and upper bound UB. The following algo
traverses arr applying an operation PROCESS
to each element of arr.
• Insertion & Deletion – the operation of adding and 1. Initialize counter
removing an element from an array Set counter = LB
2. Repeat steps 3 and 4 while counter <= UB
• Sorting – the operation of rearranging the 3. Visit element
elements of an array in some specified order Apply PROCESS to arr[counter]
4. Increase counter
• Searching – the operation of searching an element Set counter = counter + 1
in an array 5. Exit
Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

15 16

17 18

Insertion & Deletion Algorithm for Insertion


• Insertion – the operation of adding another INSERT(A, N, K, ITEM)
(where N is the number of items, K is the +ve integer s. t. K ≤ N. This
element to the array algorithm inserts an element ITEM into Kth position of linear array A.)
– At the end of the array, provided there is enough space to 1. Initialize counter
accommodate additional elements in the array Set J = N
– In the beginning or middle of the array 2. Repeat steps 3 and 4 while J >= K
3. Move Jth element downward
• All or half of the elements must be moved downwards to new
locations to accommodate the new element and retain the order Set A[J+1] = A[J]
of other element. 4. Decrease counter
Set J = J-1
• Deletion – the operation of removing an element End of step2 loop
from the array 5. Insert element
– Similarly, deleting the element from the end of an array is Set A[K] = ITEM
not a problem, but deleting from the middle requires 6. Reset N
movement of each element upwards in order to fill up the Set N = N+1
void in the array. 7. Exit
Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

17 18

Compiled by: Dr. Rabins Porwal 3


19 20

Algorithm for Deletion 6 Sorting Arrays


DELETE(A, N, K, ITEM) • Sorting data
(where N is the number of items, K is the +ve integer s. t. – Important computing application
K ≤ N. This algorithm deletes Kth element from linear – Virtually every organization must sort some data
array A.) • Bubble sort (sinking sort)
1. Set ITEM = A[K] – Several passes through the array
2. Repeat for J = K to N-1 – Successive pairs of elements are compared
(Move J+1 element upward) • If increasing order (or identical ), no change
• If decreasing order, elements exchanged
Set A[J] = A[J+1] – Repeat
End of loop • Example:
3. Reset the number N of elements in A – original: 3 4 2 6 7
Set N = N-1 – pass 1: 3 2 4 6 7
4. Exit – pass 2: 2 3 4 6 7
– Small elements "bubble" to the top
Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

19 20

21 22

Algorithm for Bubble Sort 7


Case Study: Computing Mean, Median and
Mode Using Arrays
BUBBLE (A, N) • Mean – average
(This algorithm sorts the elements of an array A) • Median – number in middle of sorted list
1. Repeat steps 2 and 3 for K=1 to N-1 – 1, 2, 3, 4, 5
2. Set PTR = 1 (Initialize pass pointer PTR) – 3 is the median
3. Repeat while PTR <= N-K (Execute pass) • Mode – number that occurs most often
a. If A[PTR] > A[PTR+1], then – 1, 1, 1, 2, 3, 3, 4, 5
Interchange A[PTR] and A[PTR+1] – 1 is the mode
(End of if structure)
b. Set PTR = PTR+1
(End of Step3 inner loop)
(End of Stpe1 outer loop)
4. Exit
Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

21 22

1 /* fig06_16.c 23 33 24
2 This program introduces the topic of survey data analysis. Outline 34 void mean( const int answer[] ) Outline
3 It computes the mean, median, and mode of the data */ 35 {
4 #include <stdio.h> 36 int j, total = 0;
5 #define SIZE 99 1. Function prototypes 37 3. Define function mean
6 38 printf( "%s\n%s\n%s\n", "********", " Mean", "********" );
7 void mean( const int [] ); 39
8 void median( int [] );
1.1 Initialize array 40 for ( j = 0; j <= SIZE - 1; j++ )
3.1 Define function
9 void mode( int [], const int [] ) ; 41 total += answer[ j ];
median
10 void bubbleSort( int [] ); 2. Call functions mean, 42
11 void printArray( const int [] ); 43 printf( "The mean is the average value of the data\n"
median, and mode 3.1.1 Sort Array
12 44 "items. The mean is equal to the total of\n"
13 int main() 45 "all the data items divided by the number\n"
14 { 46 "of data items ( %d ). The mean value for\n" 3.1.2 Print middle element
15 int frequency[ 10 ] = { 0 }; 47 "this run is: %d / %d = %.4f\n\n",
16 int response[ SIZE ] = 48 SIZE, total, SIZE, ( double ) total / SIZE );
17 { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9, 49 }
18 7, 8, 9, 5, 9, 8, 7, 8, 7, 8, 50
19 6, 7, 8, 9, 3, 9, 8, 7, 8, 7, 51 void median( int answer[] )
20 7, 8, 9, 8, 9, 8, 9, 7, 8, 9, 52 {
21 6, 7, 8, 7, 8, 7, 9, 8, 9, 2, 53 printf( "\n%s\n%s\n%s\n%s",
22 7, 8, 9, 8, 9, 8, 9, 7, 5, 3, 54 "********", " Median", "********",
23 5, 6, 7, 2, 5, 3, 9, 4, 6, 4, 55 "The unsorted array of responses is" );
24 7, 8, 9, 6, 8, 7, 8, 9, 7, 8, 56
25 7, 4, 4, 2, 5, 3, 8, 7, 5, 6, 57 printArray( answer );
26 4, 5, 6, 1, 6, 5, 7, 8, 7 }; 58 bubbleSort( answer );
27 59 printf( "\n\nThe sorted array is" );
28 mean( response ); 60 printArray( answer );
29 median( response ); 61 printf( "\n\nThe median is element %d of\n"
30 mode( frequency, response ); 62 "the sorted %d element array.\n"
31 return 0; 63 "For this run the median is %d\n\n",
Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal
32 } 64 SIZE / 2, SIZE, answer[ SIZE / 2 ] );

23 24

Compiled by: Dr. Rabins Porwal 4


65 } 25 95 printf( "\n" ); 26
66 Outline 96 } Outline
67 void mode( int freq[], const int answer[] ) 97
68 { 98 printf( "The mode is the most frequent value.\n"
3.2 Define function 99 "For this run the mode is %d which occurred"
3.3 Define bubbleSort
69 int rating, j, h, largest = 0, modeValue = 0;
70
mode 100 " %d times.\n", modeValue, largest );
71 printf( "\n%s\n%s\n%s\n", 101 } 3.3 Define printArray
3.2.1 Increase
72 "********", " Mode", "********" ); 102
frequency[] 103 void bubbleSort( int a[] )
73
depending on 104 {
74 for ( rating = 1; rating <= 9; rating++ )
response[] 105 int pass, j, hold;
75 freq[ rating ] = 0;
Notice how the subscript in 106
76
frequency[] is the value of an 107 for ( pass = 1; pass <= SIZE - 1; pass++ )
77 for ( j = 0; j <= SIZE - 1; j++ )
108
78 ++freq[ answer[ j ] ]; element in response[]
109 for ( j = 0; j <= SIZE - 2; j++ )
79 (answer[])
110
80 printf( "%s%11s%19s\n\n%54s\n%54s\n\n",
111 if ( a[ j ] > a[ j + 1 ] ) {
81 "Response", "Frequency", "Histogram",
112 hold = a[ j ];
82 "1 1 2 2", "5 0 5 0 5" ); Bubble sort: if elements out of order,
113 a[ j ] = a[ j + 1 ];
83 swap them.
114 a[ j + 1 ] = hold;
84 for ( rating = 1; rating <= 9; rating++ ) {
115 }
85 printf( "%8d%11d ", rating, freq[ rating ] );
116 }
86 117
87 if ( freq[ rating ] > largest ) { 118 void printArray( const int a[] )
88 largest = freq[ rating ]; 119 {
89 modeValue = rating; 120 int j;
90 } 121
91 Print stars depending on value of 122 for ( j = 0; j <= SIZE - 1; j++ ) {
92 for ( h = 1; h <= freq[ rating ]; h++ ) frequency[] 123
93 printf( "*" ); 124 if ( j % 20 == 0 )
Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal
94 125 printf( "\n" );

25 26

126 27 28
********
127 printf( "%2d", a[ j ] ); Outline Mode
Outline
128 } ********
129 } Response Frequency Histogram
Program Output Program Output
********
Mean 1 1 2 2
******** 5 0 5 0 5
The mean is the average value of the data
items. The mean is equal to the total of 1 1 *
all the data items divided by the number 2 3 ***
of data items (99). The mean value for 3 4 ****
this run is: 681 / 99 = 6.8788 4 5 *****
5 8 ********
******** 6 9 *********
Median 7 23 ***********************
******** 8 27 ***************************
The unsorted array of responses is 9 19 *******************
7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8 The mode is the most frequent value.
6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9 For this run the mode is 8 which occurred 27 times.
6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3
5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8
7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7

The sorted array is


1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5
5 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9

The median is element 49 of


the sorted 99 element array.
For this run the median is 7

Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

27 28

29 30
8 Searching Arrays: Linear Search and Binary Algorithm for Linear Search
Search
• Search an array for a key value LINEAR (A, N, ITEM, LOC)
(The algorithm finds the location LOC of ITEM in the array A,
• Linear search or sets LOC=0 if the search is unsuccessful)
– Simple 1. [Insert ITEM at the end of A]
– Compare each element of array with key value Set A[N+1] = ITEM
– Useful for small and unsorted arrays 2. [Initialize counter]
Set LOC = 1
3. [Search for ITEM]
Repeat while A[LOC] ≠ ITEM
Set LOC = LOC+1
[End of loop]
4. [Successful ?]
If LOC = N+1, then Set LOC = 0
5. Exit
Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

29 30

Compiled by: Dr. Rabins Porwal 5


31 Dr. Rabins Porwal
8 Searching Arrays: Linear Search and Binary Binary Search Algorithm
Search
BINARY (DATA, LB, UB, ITEM, LOC)
• Binary search (The algorithm finds the location LOC of ITEM in the array DATA, or sets
LOC=NULL if the search is unsuccessful)
– For sorted arrays 1. [Initialize segment variables]
– Compares middle element with key Set BEG = LB, END = UB and MID = INT ((BEG+END)/2)
2. Repeat steps 3 and 4 while BEG ≤ END and DATA[MID] ≠ ITEM
• If equal, match found
3. If ITEM < DATA[MID] then
• If key < middle, looks in first half of array set END = MID – 1
• If key > middle, looks in last half else
• Repeat set BEG = MID + 1
[End of If structure]
– Very fast; at most n steps, where 2n > number of elements 4. Set MID = INT ((BEG+END)/2)
• 30 elements array takes at most 5 steps [End of step 2 loop]
5. If DATA[MID] = ITEM, then
– 25 > 30 so at most 5 steps
set LOC = MID
else
LOC = NULL
[End of If structure]
5. Exit

Arrays Unit I Dr. Rabins Porwal Arrays Unit I Unit III. 32

31 32

Dr. Rabins Porwal Dr. Rabins Porwal

Complexity of Binary Search Example on Complexity of Binary Search Algorithm

The complexity is measured by the number f(n) of


comparisons to locate ITEM in DATA where DATA Suppose DATA contains 1000000 elements. It can be
contains n elements. It can be observed that each observed that 210 = 1024 > 1000 and hence 220 >
comparison reduces the sample size in half. Hence if f(n) 10002 = 1000000.
comparisons are required to locate ITEM, then
Hence, using the binary search algorithm, only about
2f(n) > n or equivalently f(n) = log2n + 1 20 comparisons will be required to find the location
That is, the running time for the worst case is of an item in a DATA array with 1000000 elements.
approximately equal to O (log2n). It can also be shown
that the running time for the average case is
approximately equal to the running time for the worst
case.

Arrays Unit I Unit III. 33 Arrays Unit I Unit III. 34

33 34

Dr. Rabins Porwal 36

Limitations of Binary Search Algorithm 9 Multiple-Subscripted Arrays


• Multiple subscripted arrays
• Though this type of search algorithm is very efficient,
– Tables with rows and columns (m by n array)
but it has some limitations on arrays: – Like matrices: specify row, then column
– The list must be sorted.
– One must have direct access to the middle element in any sublist Column 0 Column 1 Column 2 Column 3
– Keeping data in a sorted array is very expensive when there are Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
many insertions and deletions. Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
• Alternative data structures:
– Usage of linked list or Binary Search tree to store the data. Column subscript
Array name
Row subscript

Arrays Unit I Unit III. 35 Arrays Unit I Dr. Rabins Porwal

35 36

Compiled by: Dr. Rabins Porwal 6


37 38

9 Multiple-Subscripted Arrays Row Major and Column Major Order


• Initialization • All elements of a matrix get stored in the memory
1 2
– Initializers grouped by row in braces
3 4
in a linear fashion.
– int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; • Two ways to represent elements in computer’s
– If not enough, unspecified elements set to zero
memory
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 1 0
– Row major representation
3 4
• Referencing elements – Column major representation
– Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );

Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

37 38

39 40

Address Calculation in single D array Address Calculation in 2-D array


• As the elements of the array A are stored in • Using row major order, the formula to calculate address of
(j, k)th element in a 2-D array A of size m×n is
consecutive memory cells, the computer does not
addr (j, k) = base(A) + w × [n(j – 1) + (k – 1)]
need to keep track of the address of every element
where
of the array. It only needs to keep track the base(A) = the address of first element of the array, i.e., A[0][0]
address of the first element of the array which is w = word size
denoted by base(A). n = number of columns
• Using column major order, the formula to calculate address
• Using this base address base(A), the computer of (j, k)th element in a 2-D array A of size m×n is
calculates the address of any element of the array addr (j, k) = base(A) + w × [(j – 1) + m(k – 1)]
by using the following formula: where
addr (kth element) = base(A) + w × (k-1) base(A) = the address of first element of the array, i.e., A[0][0]
w = word size
where w is the size of the data type of the array A. m = number of rows

Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

39 40

41 1 /* fig06_22.c 42
2 Double-subscripted array example */ Outline
Example 3
4
#include <stdio.h>
#define STUDENTS 3
5 #define EXAMS 4 1. Initialize variables
6
Let 7 int minimum( const int [][ EXAMS ], int, int );
1.1 Define functions to
8 int maximum( const int [][ EXAMS ], int, int );
int A[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; 9 double average( const int [], int ); take double scripted
10 void printArray( const int [][ EXAMS ], int, int ); arrays
Each row is a particular student,
Assume base address of the array is 100. 11
12 int main() each column is the grades on the
exam. 1.2 Initialize
Since elements are integer type, w = 2 13
14
{
int student; studentgrades[][]
Address of (2, 3)th element in the array A is 15
16
const int studentGrades[ STUDENTS ][ EXAMS ] =
{ { 77, 68, 86, 73 },
2. Call functions
17 { 96, 87, 89, 78 },
1. Using row major order 18 { 70, 90, 86, 81 } };
minimum, maximum, and
19 average
addr (2, 3) = 100 + 2[4(2-1) + (3-1)] 20 printf( "The array is:\n" );
21 printArray( studentGrades, STUDENTS, EXAMS );
112 22
23
printf( "\n\nLowest grade: %d\nHighest grade: %d\n",
minimum( studentGrades, STUDENTS, EXAMS ),
2. Using column major order 24
25
maximum( studentGrades, STUDENTS, EXAMS ) );

addr (2, 3) = 100 + 2[(2-1) + 3(3-1)] 26


27
for ( student = 0; student <= STUDENTS - 1; student++ )
printf( "The average grade for student %d is %.2f\n",
28 student,
114 29 average( studentGrades[ student ], EXAMS ) );
30
Dr. Rabins Porwal 31 return 0;
Arrays Unit I Arrays Unit I Dr. Rabins Porwal
32 }

41 42

Compiled by: Dr. Rabins Porwal 7


33 43 65 int i, total = 0; 44
34 /* Find the minimum grade */ Outline 66 Outline
35 int minimum( const int grades[][ EXAMS ], 67 for ( i = 0; i <= tests - 1; i++ )
36 int pupils, int tests ) 68 total += setOfGrades[ i ];
37 { 3. Define functions 69 3. Define functions
38 int i, j, lowGrade = 100; 70 return ( double ) total / tests;
39 71 }
40 for ( i = 0; i <= pupils - 1; i++ ) 72
41 for ( j = 0; j <= tests - 1; j++ ) 73 /* Print the array */
42 if ( grades[ i ][ j ] < lowGrade ) 74 void printArray( const int grades[][ EXAMS ],
43 lowGrade = grades[ i ][ j ]; 75 int pupils, int tests )
44 76 {
45 return lowGrade; 77 int i, j;
46 } 78
47 79 printf( " [0] [1] [2] [3]" );
48 /* Find the maximum grade */ 80
49 int maximum( const int grades[][ EXAMS ], 81 for ( i = 0; i <= pupils - 1; i++ ) {
50 int pupils, int tests ) 82 printf( "\nstudentGrades[%d] ", i );
51 { 83
52 int i, j, highGrade = 0; 84 for ( j = 0; j <= tests - 1; j++ )
53 85 printf( "%-5d", grades[ i ][ j ] );
54 for ( i = 0; i <= pupils - 1; i++ ) 86 }
55 for ( j = 0; j <= tests - 1; j++ ) 87 }
56 if ( grades[ i ][ j ] > highGrade )
57 highGrade = grades[ i ][ j ];
58
59 return highGrade;
60 }
61
62 /* Determine the average grade for a particular exam */
63 double average( const int setOfGrades[], int tests )
Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal
64 {

43 44

45 46
The array is:
Outline
[0]
studentGrades[0] 77
[1]
68
[2]
86
[3]
73
Program Output
Applications & Limitations of Linear Arrays
studentGrades[1] 96 87 89 78
studentGrades[2] 70 90 86 81

Lowest grade: 68 • Linear arrays are used to represent all sorts of


Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
lists. They are used to implement other data
The average grade for student 2 is 81.75 structures such as stacks, queues, heaps etc.
• Limitations of Linear Arrays
1. The prior knowledge of number of elements in
the linear array is necessary.
2. These are static structures, i.e., the memory used
by them cannot be reduced or extended.
3. Since the elements are stored in consecutive
locations, the insertions and deletions in these
arrays are time consuming.

Arrays Unit I Dr. Rabins Porwal Arrays Unit I Dr. Rabins Porwal

45 46

Compiled by: Dr. Rabins Porwal 8

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy