Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views41 pages

CHTP5e - 06-Arrays 1

Arrays 1 IN C PROGRAMME

Uploaded by

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

CHTP5e - 06-Arrays 1

Arrays 1 IN C PROGRAMME

Uploaded by

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

1

6
C Arrays
2

OBJECTIVES
In this chapter you will learn:
 To use the array data structure to represent lists
and tables of values.
 To define an array, initialize an array and refer
to individual elements of an array.
 To define symbolic constants.
 To pass arrays to functions.
 To use arrays to store, sort and search lists and
tables of values.
 To define and manipulate multiple-subscripted
arrays.
3

6.1 Introduction
6.2 Arrays
6.3 Defining Arrays
6.4 Array Examples
6.5 Passing Arrays to Functions
6.6 Sorting Arrays
6.7 Case Study: Computing Mean, Median and Mode
Using Arrays
6.8 Searching Arrays
6.9 Multiple-Subscripted Arrays
4

6.1 Introduction

 Arrays
– Structures of related data items
– Static entity – same size throughout program
– Dynamic data structures discussed in Chapter
12
5

6.2 Arrays
 Array
– Group of consecutive memory locations
– Same name and type
 To refer to an element, specify
– Array name
– Position number
 Format:
arrayname[ position number ]
– First element at position 0
– n element array named c:
- c[ 0 ], c[ 1 ]...c[ n – 1 ]
6

12-element array.
7

6.2 Arrays

 Array elements are like normal


variables
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );
– Perform operations in subscript. If x equals 3
c[ 5 - 2 ] == c[ 3 ] == c[ x ]
8

6.3 Defining Arrays


 When defining arrays, specify
– Name
– Type of array
– Number of elements
arrayType arrayName[ numberOfElements ];
– Examples:
int c[ 10 ];
float myArray[ 3284 ];
 Defining multiple arrays of same type
– Format similar to regular variables
– Example:
int b[ 100 ], x[ 27 ];
9

6.4 Array Examples


 Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
- All elements 0
– If too many initializers, a syntax error occurs
– C arrays have no bounds checking
 If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore 5 element array
1 /* Fig. 6.3: fig06_03.c 10
2 initializing an array */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int n[ 10 ]; /* n is an array of 10 integers */
9 int i; /* counter */
10
11 /* initialize elements of array n to 0 */ for loop initializes each array
12 for ( i = 0; i < 10; i++ ) { element separately
13 n[ i ] = 0; /* set element at location i to 0 */
14 } /* end for */
15
16 printf( "%s%13s\n", "Element", "Value" );
17
18 /* output contents of array n in tabular format */
19 for ( i = 0; i < 10; i++ ) { for loop outputs all array elements
20 printf( "%7d%13d\n", i, n[ i ] );
21 } /* end for */
22
23 return 0; /* indicates successful termination */
24
25 } /* end main */
11
Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
1 /* Fig. 6.4: fig06_04.c 12
2 Initializing an array with an initializer list */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 /* use initializer list to initialize array n */
9 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
10 int i; /* counter */
11
12 printf( "%s%13s\n", "Element", "Value" ); initializer list initializes all array
13 elements simultaneously
14 /* output contents of array in tabular format */
15 for ( i = 0; i < 10; i++ ) {
16 printf( "%7d%13d\n", i, n[ i ] );
17 } /* end for */
18
19 return 0; /* indicates successful termination */
20
21 } /* end main */
13

Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
1 /* Fig. 6.5: fig06_05.c 14
2 Initialize the elements of array s to the even integers from 2 to 20 */
3 #include <stdio.h>
4 #define SIZE 10 /* maximum size of array */
#define directive tells compiler to replace
5
all instances of the word SIZE with 10
6 /* function main begins program execution */
7 int main( void )
8 {
9 /* symbolic constant SIZE can be used to specify array size */
10 int s[ SIZE ]; /* array s has SIZE elements */ SIZE is replaced with 10 by the
11 int j; /* counter */ compiler, so array s has 10 elements
12
13 for ( j = 0; j < SIZE; j++ ) { /* set the values */
14 s[ j ] = 2 + 2 * j;
for loop initializes each array
15 } /* end for */
element separately
16
17 printf( "%s%13s\n", "Element", "Value" );
18
19 /* output contents of array s in tabular format */
20 for ( j = 0; j < SIZE; j++ ) {
21 printf( "%7d%13d\n", j, s[ j ] );
22 } /* end for */
23
24 return 0; /* indicates successful termination */
25
26 } /* end main */
15
Element Value
0 2
1 4
2 6
3 8
4 10
5 12
6 14
7 16
8 18
9 20
1 /* Fig. 6.6: fig06_06.c 16
2 Compute the sum of the elements of the array */
3 #include <stdio.h>
4 #define SIZE 12
5
6 /* function main begins program execution */
7 int main( void )
8 {
9 /* use initializer list to initialize array */
10 int a[ SIZE ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 };
11 int i; /* counter */
12 int total = 0; /* sum of array */ initializer list initializes all array
13 elements simultaneously
14 /* sum contents of array a */
15 for ( i = 0; i < SIZE; i++ ) {
for loop adds each element of the
16 total += a[ i ];
array to variable total
17 } /* end for */
18
19 printf( "Total of array element values is %d\n", total );
20
21 return 0; /* indicates successful termination */
22
23 } /* end main */

Total of array element values is 383


• Using arrays to summarize survey results
• Student poll program
1 /* Fig. 6.7: fig06_07.c 18
2 Student poll program */
3 #include <stdio.h>
4 #define RESPONSE_SIZE 40 /* define array sizes */ #define directives create
5 #define FREQUENCY_SIZE 11 symbolic constants
6
7 /* function main begins program execution */
8 int main( void )
9 {
10 int answer; /* counter to loop through 40 responses */
11 int rating; /* counter to loop through frequencies 1-10 */
12
13 /* initialize frequency counters to 0 */
frequency array is defined
14 int frequency[ FREQUENCY_SIZE ] = { 0 };
15
with 11 elements
16 /* place the survey responses in the responses array */
17 int responses[ RESPONSE_SIZE ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10,
responses array is defined
18 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6,
19 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 };
with 40 elements and its
20 elements are initialized
21 /* for each answer, select value of an element of array responses
22 and use that value as subscript in array frequency to
23 determine element to increment */
24 for ( answer = 0; answer < RESPONSE_SIZE; answer++ ) {
25 ++frequency[ responses [ answer ] ];
subscript of frequency array is given
26 } /* end for */
27
by value in responses array
28 /* display results */ 19
29 printf( "%s%17s\n", "Rating", "Frequency" );
30
31 /* output the frequencies in a tabular format */
32 for ( rating = 1; rating < FREQUENCY_SIZE; rating++ ) {
33 printf( "%6d%17d\n", rating, frequency[ rating ] );
34 } /* end for */
35
36 return 0; /* indicates successful termination */
37
38 } /* end main */

Rating Frequency
1 2
2 2
3 2
4 2
5 5
6 11
7 5
8 7
9 1
10 3
• Histogram printing program
1 /* Fig. 6.8: fig06_08.c 21
2 Histogram printing program */
3 #include <stdio.h>
4 #define SIZE 10
5
6 /* function main begins program execution */
7 int main( void )
8 {
9 /* use initializer list to initialize array n */
10 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
11 int i; /* outer for counter for array elements */
12 int j; /* inner for counter counts *s in each histogram bar */
13
14 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );
15
16 /* for each element of array n, output a bar of the histogram */
17 for ( i = 0; i < SIZE; i++ ) {
18 printf( "%7d%13d ", i, n[ i ]) ;
19
20 for ( j = 1; j <= n[ i ]; j++ ) { /* print one bar */
21 printf( "%c", '*' ); nested for loop prints n[ i ]
22 } /* end inner for */ asterisks on the ith line
23
24 printf( "\n" ); /* end a histogram bar */
25 } /* end outer for */
26
27 return 0; /* indicates successful termination */
28
29 } /* end main */
22
Element Value Histogram
0 19 *******************
1 3 ***
2 15 ***************
3 7 *******
4 11 ***********
5 9 *********
6 13 *************
7 5 *****
8 17 *****************
9 1 *
• Roll a six-sided die 6000 times
1 /* Fig. 6.9: fig06_09.c 24
2 Roll a six-sided die 6000 times */
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <time.h>
6 #define SIZE 7
7
8 /* function main begins program execution */
9 int main( void )
10 {
11 int face; /* random die value 1 - 6 */
12 int roll; /* roll counter 1-6000 */
13 int frequency[ SIZE ] = { 0 }; /* clear counts */
14
15 srand( time( NULL ) ); /* seed random-number generator */
16
17 /* roll die 6000 times */
18 for ( roll = 1; roll <= 6000; roll++ ) {
19 face = 1 + rand() % 6;
20 ++frequency[ face ]; /* replaces 26-line switch of Fig. 5.8 */
21 } /* end for */
for loop uses one array to track
number of times each number is
rolled instead of using 6 variables
and a switch statement
22 25
23 printf( "%s%17s\n", "Face", "Frequency" );
24
25 /* output frequency elements 1-6 in tabular format */
26 for ( face = 1; face < SIZE; face++ ) {
27 printf( "%4d%17d\n", face, frequency[ face ] );
28 } /* end for */
29
30 return 0; /* indicates successful termination */
31
32 } /* end main */

Face Frequency
1 1029
2 951
3 987
4 1033
5 1010
6 990
26

6.4 Array Examples


 Character arrays
– String “first” is really a static array of characters
– Character arrays can be initialized using string literals
char string1[] = "first";
- Null character '\0' terminates strings
- string1 actually has 6 elements
It is equivalent to
char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };
– Can access individual characters
string1[ 3 ] is character ‘s’
– Array name is address of array, so & not needed for
scanf
scanf( "%s", string2 );
- Reads characters until whitespace encountered
1 /* Fig. 6.10: fig06_10.c 27
2 Treating character arrays as strings */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 char string1[ 20 ]; /* reserves 20 characters */
9 char string2[] = "string literal"; /* reserves 15 characters */
10 int i; /* counter */
string2 array is defined with one
11
element for each character, so 15
12 /* read string from user into array string1 */
13 printf("Enter a string: ");
elements including null character /0
14 scanf( "%s", string1 ); /* input ended by whitespace character */
15
16 /* output strings */
17 printf( "string1 is: %s\nstring2 is: %s\n"
18 "string1 with spaces between characters is:\n",
19 string1, string2 );
20
21 /* output characters until null character is reached */
22 for ( i = 0; string1[ i ] != '\0'; i++ ) {
for loop prints characters of string1
23 printf( "%c ", string1[ i ] );
array with spaces in between
24 } /* end for */
25
26 printf( "\n" );
27
28 return 0; /* indicates successful termination */
29
30 } /* end main */
28
Enter a string: Hello there
string1 is: Hello
string2 is: string literal
string1 with spaces between characters is:
H e l l o
1 /* Fig. 6.11: fig06_11.c 29
2 Static arrays are initialized to zero */
3 #include <stdio.h>
4
5 void staticArrayInit( void ); /* function prototype */
6 void automaticArrayInit( void ); /* function prototype */
7
8 /* function main begins program execution */
9 int main( void )
10 {
11 printf( "First call to each function:\n" );
12 staticArrayInit();
13 automaticArrayInit();
14
15 printf( "\n\nSecond call to each function:\n" );
16 staticArrayInit();
17 automaticArrayInit();
18
19 return 0; /* indicates successful termination */
20
21 } /* end main */
22
23 /* function to demonstrate a static local array */ 30
24 void staticArrayInit( void )
25 {
26 /* initializes elements to 0 first time function is called */
27 static int array1[ 3 ];
28 int i; /* counter */
static array is created only once, when
staticArrayInit is first called
29
30 printf( "\nValues on entering staticArrayInit:\n" );
31
32 /* output contents of array1 */
33 for ( i = 0; i <= 2; i++ ) {
34 printf( "array1[ %d ] = %d ", i, array1[ i ] );
35 } /* end for */
36
37 printf( "\nValues on exiting staticArrayInit:\n" );
38
39 /* modify and output contents of array1 */
40 for ( i = 0; i <= 2; i++ ) {
41 printf( "array1[ %d ] = %d ", i, array1[ i ] += 5 );
42 } /* end for */
43
44 } /* end function staticArrayInit */
45 31
46 /* function to demonstrate an automatic local array */
47 void automaticArrayInit( void )
48 {
49 /* initializes elements each time function is called */
50 int array2[ 3 ] = { 1, 2, 3 };
automatic array is recreated every time
51 int i; /* counter */
automaticArrayInit is called
52
53 printf( "\n\nValues on entering automaticArrayInit:\n" );
54
55 /* output contents of array2 */
56 for ( i = 0; i <= 2; i++ ) {
57 printf("array2[ %d ] = %d ", i, array2[ i ] );
58 } /* end for */
59
60 printf( "\nValues on exiting automaticArrayInit:\n" );
61
62 /* modify and output contents of array2 */
63 for ( i = 0; i <= 2; i++ ) {
64 printf( "array2[ %d ] = %d ", i, array2[ i ] += 5 );
65 } /* end for */
66
67 } /* end function automaticArrayInit */
32
First call to each function:

Values on entering staticArrayInit:


array1[ 0 ] = 0 array1[ 1 ] = 0 array1[ 2 ] = 0
Values on exiting staticArrayInit:
array1[ 0 ] = 5 array1[ 1 ] = 5 array1[ 2 ] = 5

Values on entering automaticArrayInit:


array2[ 0 ] = 1 array2[ 1 ] = 2 array2[ 2 ] = 3
Values on exiting automaticArrayInit:
array2[ 0 ] = 6 array2[ 1 ] = 7 array2[ 2 ] = 8

Second call to each function:

Values on entering staticArrayInit:


array1[ 0 ] = 5 array1[ 1 ] = 5 array1[ 2 ] = 5
Values on exiting staticArrayInit:
array1[ 0 ] = 10 array1[ 1 ] = 10 array1[ 2 ] = 10

Values on entering automaticArrayInit:


array2[ 0 ] = 1 array2[ 1 ] = 2 array2[ 2 ] = 3
Values on exiting automaticArrayInit:
array2[ 0 ] = 6 array2[ 1 ] = 7 array2[ 2 ] = 8
33

6.5 Passing Arrays to Functions


 Passing arrays
– To pass an array argument to a function, specify the
name of the array without any brackets
int myArray[ 24 ];
myFunction( myArray, 24 );
- 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
34

6.5 Passing Arrays to Functions

 Function prototype
void modifyArray( int b[], int
arraySize );
– Parameter names optional in prototype
- int b[] could be written int []
- int arraySize could be simply int
1 /* Fig. 6.12: fig06_12.c 35
2 The name of an array is the same as &array[ 0 ] */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 char array[ 5 ]; /* define an array of size 5 */
9
10 printf( " array = %p\n&array[0] = %p\n &array = %p\n",
11 array, &array[ 0 ], &array );
12
13 return 0; /* indicates successful termination */
14
15 } /* end main */

array = 0012FF78
&array[0] = 0012FF78
&array = 0012FF78
1 /* Fig. 6.13: fig06_13.c 36
2 Passing arrays and individual array elements to functions */
3 #include <stdio.h>
4 #define SIZE 5
5
6 /* function prototypes */
Function prototype indicates
7 void modifyArray( int b[], int size );
8 void modifyElement( int e );
function will take an array
9
10 /* function main begins program execution */
11 int main( void )
12 {
13 int a[ SIZE ] = { 0, 1, 2, 3, 4 }; /* initialize a */
14 int i; /* counter */
15
16 printf( "Effects of passing entire array by reference:\n\nThe "
17 "values of the original array are:\n" );
18
19 /* output original array */
20 for ( i = 0; i < SIZE; i++ ) {
21 printf( "%3d", a[ i ] );
22 } /* end for */
23
24 printf( "\n" );
25
26 /* pass array a to modifyArray by reference */ Array a is passed to modifyArray
27 modifyArray( a, SIZE ); by passing only its name
28
29 printf( "The values of the modified array are:\n" );
30
31 /* output modified array */ 37
32 for ( i = 0; i < SIZE; i++ ) {
33 printf( "%3d", a[ i ] );
34 } /* end for */
35
36 /* output value of a[ 3 ] */
37 printf( "\n\n\nEffects of passing array element "
38 "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] );
39
40 modifyElement( a[ 3 ] ); /* pass array element a[ 3 ] by value */
41 Array element is passed to modifyElement
42 /* output value of a[ 3 ] */
by passing a[ 3 ]
43 printf( "The value of a[ 3 ] is %d\n", a[ 3 ] );
44
45 return 0; /* indicates successful termination */
46
47 } /* end main */
48
49 /* in function modifyArray, "b" points to the original array "a"
50 in memory */
51 void modifyArray( int b[], int size )
52 {
53 int j; /* counter */
54
55 /* multiply each array element by 2 */
56 for ( j = 0; j < size; j++ ) {
57 b[ j ] *= 2;
58 } /* end for */
59
60 } /* end function modifyArray */
61 38
62 /* in function modifyElement, "e" is a local copy of array element
63 a[ 3 ] passed from main */
64 void modifyElement( int e )
65 {
66 /* multiply parameter by 2 */
67 printf( "Value in modifyElement is %d\n", e *= 2 );
68 } /* end function modifyElement */

Effects of passing entire array by reference:

The values of the original array are:


0 1 2 3 4
The values of the modified array are:
0 2 4 6 8

Effects of passing array element by value:

The value of a[3] is 6


Value in modifyElement is 12
The value of a[ 3 ] is 6
1 /* Fig. 6.14: fig06_14.c 39
2 Demonstrating the const type qualifier with arrays */
3 #include <stdio.h>
4
5 void tryToModifyArray( const int b[] ); /* function prototype */
6
7 /* function main begins program execution */ const qualifier tells compiler that
8 int main( void ) array cannot be changed
9 {
10 int a[] = { 10, 20, 30 }; /* initialize a */
11
12 tryToModifyArray( a );
13
14 printf("%d %d %d\n", a[ 0 ], a[ 1 ], a[ 2 ] );
15
16 return 0; /* indicates successful termination */
17
18 } /* end main */
19
20 /* in function tryToModifyArray, array b is const, so it cannot be
21 used to modify the original array a in main. */
22 void tryToModifyArray( const int b[] )
23 {
24 b[ 0 ] /= 2; /* error */
Any attempts to modify the array will
25 b[ 1 ] /= 2; /* error */
result in errors
26 b[ 2 ] /= 2; /* error */
27 } /* end function tryToModifyArray */
40
Compiling...
FIG06_14.C
fig06_14.c(24) : error C2166: l-value specifies const object
fig06_14.c(25) : error C2166: l-value specifies const object
fig06_14.c(26) : error C2166: l-value specifies const object
41

Operators Associativity Type

[] () left to right highest

++ -- ! (type) right to left unary

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

&& left to right logical AND

|| left to right logical OR

?: right to left conditional

= += -= *= /= %= right to left assignment

, left to right comma

Operator precedence.

You might also like