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

Arrays: Outline Arrays Declaring Arrays Examples Using Arrays

The document discusses arrays, including declaring arrays, initializing arrays, and using arrays in examples. It defines arrays as structures that store related data items of the same type. Arrays have a fixed size set at declaration. Elements in an array are accessed using an index number. Examples shown how to initialize arrays to specific values or all the same value, and how to use a constant to define the array size.

Uploaded by

Rayan Khaled
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)
47 views34 pages

Arrays: Outline Arrays Declaring Arrays Examples Using Arrays

The document discusses arrays, including declaring arrays, initializing arrays, and using arrays in examples. It defines arrays as structures that store related data items of the same type. Arrays have a fixed size set at declaration. Elements in an array are accessed using an index number. Examples shown how to initialize arrays to specific values or all the same value, and how to use a constant to define the array size.

Uploaded by

Rayan Khaled
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/ 34

1

Arrays
Outline
Introduction
Arrays
Declaring Arrays
Examples Using Arrays

 2003 Prentice Hall, Inc. All rights reserved.


Array
• The Array is the most commonly used Data
Storage Structure.

• It’s built into most Programming languages.

 2003 Prentice Hall, Inc. All rights reserved.


3

Introduction

• Arrays
– Structures of related data items
– Static entity (same size throughout program)
• A few types
– Pointer-based arrays (C-like)
– Arrays as objects (C++)

 2003 Prentice Hall, Inc. All rights reserved.


4

Arrays

• Array
– Consecutive group of memory locations
– Same name and type (int, char, etc.)
• To refer to an element
– Specify array name and position number (index)
– Format: arrayname[ position number ]
– First element at position 0
• N-element array c
c[ 0 ], c[ 1 ] … c[ n - 1 ]
– Nth element as position N-1

 2003 Prentice Hall, Inc. All rights reserved.


5

Arrays

• Array elements like other variables


– Assignment, printing for an integer array c
c[ 0 ] = 3;
cout << c[ 0 ];
• Can perform operations inside subscript
c[ 5 – 2 ] same as c[3]

 2003 Prentice Hall, Inc. All rights reserved.


  6

Arrays
Name of array (Note
that all elements of
this array have the
same name, c)

c[0] -45
c[1] 6
c[2] 0
c[3] 72
c[4] 1543
c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78

Position number of the


element within array c

 2003 Prentice Hall, Inc. All rights reserved.


7

Declaring Arrays

• When declaring arrays, specify


– Name
– Type of array
• Any data type
– Number of elements
– type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats

• Declaring multiple arrays of same type


– Use comma separated list, like regular variables
int b[ 100 ], x[ 27 ];

 2003 Prentice Hall, Inc. All rights reserved.


8

Examples Using Arrays

• Initializing arrays
– Initializer list
• Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers, rightmost elements 0
• If too many syntax error
– To set every element to same value
int n[ 5 ] = { 0 };
– If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array

 2003 Prentice Hall, Inc. All rights reserved.


9
2 // Initializing an array.
3 #include <iostream>
Outline
4 7
8 #include <iomanip>
9
10 using std::setw;
11
12 int main()
13 {
14 int n[ 10 ]; // n is an array of 10 integers
15
Declare a 10-element array of
16 // initialize elements of integers.
array n to 0
17 for ( int i = 0; i < 10; i++ )
18 n[ i ] = 0; // set element atInitialize
location array
i toto 00 using a
19 for loop. Note that the array
20 // output contents of array n in has elements
tabular n[0] to n[9].
format
23 for ( int j = 0; j < 10; j++ )
24 cout << j << n[ j ] << endl;
25 return 0; // indicates successful termination
27
28 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
10
Outline

Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0

 2003 Prentice Hall, Inc.


All rights reserved.
11
2 // Initializing an array with a declaration.
3 #include <iostream>
Outline
4
5
11
12 int main()
13 {
14 // use initializer list to initialize array n
15 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
16
17 cout << "Element" << setw( 13 ) << "Value" << endl;
18
19 // output contents of array n in tabular format
20 for ( int i = 0; i < 10; i++ )
21 cout << i << n[ i ] << endl;
22
23 return 0; // indicates successful termination
24
25 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
12
Element Value
0 32
Outline
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37

 2003 Prentice Hall, Inc.


All rights reserved.
13

Examples Using Arrays

• Array size
– Can be specified with constant variable (const)
• const int size = 20;
– Constants cannot be changed
– Constants must be initialized when declared
– Also called named constants or read-only variables

 2003 Prentice Hall, Inc. All rights reserved.


14
2 // Initialize array s to the even integers from 2 to 20.
3 #include <iostream>
Outline
4
11
12 int main()
13 {
14 // constant variable can be used to specify array size
15 const int arraySize = 10;
16
17 int s[ arraySize ]; // array s has 10 elements
18
19 for ( int i = 0; i < arraySize; i++ ) // set the values
20 s[ i ] = 2 * i;
21
22 cout << "Element“ << "Value" << endl;
23
24 // output contents of array s in tabular format
25 for ( int j = 0; j < arraySize; j++ )
26 cout << j << s[ j ] << endl;
27
28 return 0; // indicates successful termination
29
30 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
15
Outline

Element Value
0 0
1 2
2 4
3 6
4 8
5 10
6 12
7 14
8 16
9 18

 2003 Prentice Hall, Inc.


All rights reserved.
16
2 // Compute the sum of the elements of the array.
Outline
3 #include <iostream>
4
5 int main()
9 {
10 const int arraySize = 10;
11
12 int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
13
14 int total = 0;
15
16 // sum contents of array a
17 for ( int i = 0; i < arraySize; i++ )
18 total += a[ i ]; // total = total+ a[i]
19
20 cout << "Total of array element values is " << total << endl;
21
22 return 0; // indicates successful termination
23
24 } // end main

Total of array element values is 55

 2003 Prentice Hall, Inc.


All rights reserved.
17

Array of characters or string

• Strings
– Arrays of characters
– All strings end with null ('\0')
– Examples
• char string1[] = "hello";
– Null character implicitly added
– string1 has 6 elements
• char string1[] = { 'h', 'e', 'l', 'l',
'o', '\0’ };
– Subscripting is the same
String1[ 0 ] is 'h'
string1[ 2 ] is 'l'

 2003 Prentice Hall, Inc. All rights reserved.


18

Examples Using Arrays

• Input from keyboard


char string2[ 10 ];
cin >> string2;
– Puts user input in string
• Stops at first whitespace character
• Adds null character
– If too much text entered, data written beyond array
• We want to avoid this (section 5.12 explains how)
• Printing strings
– cout << string2 << endl;
• Does not work for other array types
– Characters printed until null found

 2003 Prentice Hall, Inc. All rights reserved.


19
2 // Treating character arrays as strings.
Outline
3 #include <iostream>
4
8
9 int main()
10 {
11 char string1[ 20 ], // reserves 20 characters
12 char string2[] = "string literal"; // reserves 15 characters
13
14 // read string from user into array string2
15 cout << "Enter the string \"hello there\": ";
16 cin >> string1; // reads "hello" [space terminates input]
17
18 // output strings
19 cout << "string1 is: " << string1
20 << "\nstring2 is: " << string2;
21
22 cout << "\nstring1 with spaces between characters is:\n";
23

 2003 Prentice Hall, Inc.


All rights reserved.
20
24 // output characters until null character is reached
25 for ( int i = 0; string1[ i ] != '\0'; i++ )
Outline
26 cout << string1[ i ] << ' ';
27
28 cin >> string1; // reads "there"
29 cout << "\nstring1 is: " << string1 << endl;
30
31 return 0; // indicates successful termination
32
33 } // end main

Enter the string "hello there": hello there


string1 is: hello
string2 is: string literal
string1 with spaces between characters is:
h e l l o
string1 is: there

 2003 Prentice Hall, Inc.


All rights reserved.
21

Memory Representation of 1D Array

• If the array is float arr [ 5 ];


memory representation would be as follows:

5000 5004 5008 5012 5016

Arr [ 0 ] Arr [ 1 ] Arr [ 2 ] Arr [ 3 ] Arr [ 4 ]

Total Memory requirement is : size of ( type ) * size of array

 2003 Prentice Hall, Inc. All rights reserved. 4 * 5 = 20 bytes


22

Multiple-Subscripted Arrays

• Multiple subscripts
– a[ i ][ j ]
– Tables with rows and columns
– Specify row, then column
– “Array of arrays”
• a[0] is an array of 4 elements
• a[0][0] is the first element of that array
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]

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 ]

Column subscript

Array name
Row subscript

 2003 Prentice Hall, Inc. All rights reserved.


23

Multiple-Subscripted Arrays

• To initialize
– Default of 0
– Initializers grouped by row in braces
1 2
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 3 4
Row 0 Row 1

1 0

int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 3 4

 2003 Prentice Hall, Inc. All rights reserved.


24

Multiple-Subscripted Arrays

• Referenced like normal


cout << b[ 0 ][ 1 ]; 1 0

– Outputs 0 3 4

– Cannot reference using commas


cout << b[ 0, 1 ];
• Syntax error

 2003 Prentice Hall, Inc. All rights reserved.


25

Multiple-Subscripted Arrays

• Next: program showing initialization


– After, program to keep track of students grades
– Multiple-subscripted array (table)
– Rows are students
– Columns are grades Quiz1 Quiz2

Student0 95 85
Student1 89 80

 2003 Prentice Hall, Inc. All rights reserved.


26

Exercise 1:
(a) Write the command to create a two dimensional array
that stores integer numbers. The name of the array is
grade. The array stores grades of 5 courses of 10
students. (hint: rows represent students, columns
represent grades of courses).
 
Write the command to create an array that can store 5 )b(
integer numbers and initialize the array values with the
.numbers 10, 20, 30, 40, 50. The name of the array is value

 2003 Prentice Hall, Inc. All rights reserved.


27

Exercise 2:
Write the command to create an array that can store 5 )b(
integer numbers and initialize the array values with the
.numbers 10, 20, 30, 40, 50. The name of the array is value
Define an array a of type int with size 5 and fill this )c( 
.array with values 1, 4, 7, 10, 13

(d) Write a C++ program which counts number of times a value


occur in an array of 10 integers. The program reads first the 10
integers from keyboard; then it stores in the array. At the end,
the program should ask a number to search and display the
number of occurrence.
 

 2003 Prentice Hall, Inc. All rights reserved.


28
2 // Double-subscripted array example.
Outline
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7 using std::fixed;
8 using std::left;
9
10 #include <iomanip>
11
12 using std::setw;
13 using std::setprecision;
14
15 const int students = 3; // number of students
16 const int exams = 4; // number of exams
17
18 // function prototypes
19 int minimum( int [][ exams ], int, int );
20 int maximum( int [][ exams ], int, int );
21 double average( int [], int );
22 void printArray( int [][ exams ], int, int );
23

 2003 Prentice Hall, Inc.


All rights reserved.
29
24 int main()
25 {
Outline
26 // initialize student grades for three students (rows)
27 int studentGrades[ students ][ exams ] =
28 { { 77, 68, 86, 73 },
29 { 96, 87, 89, 78 },
30 { 70, 90, 86, 81 } };
31
32 // output array studentGrades
33 cout << "The array is:\n";
34 printArray( studentGrades, students, exams );
35
36 // determine smallest and largest grade values
37 cout << "\n\nLowest grade: "
38 << minimum( studentGrades, students, exams )
39 << "\nHighest grade: "
40 << maximum( studentGrades, students, exams ) << '\n';
41
42 cout << fixed << setprecision( 2 );
43

 2003 Prentice Hall, Inc.


All rights reserved.
30
44 // calculate average grade for each student
45 for ( int person = 0; person < students; person++ )
Outline
46 cout << "The average grade for student " << person
47 << " is "
48 << average( studentGrades[ person ], exams )
49 << endl;
50 Determines the average for
51 return 0; // indicates successful termination
one student. We pass the
52
array/row containing the
53 } // end main
student’s grades. Note that
54
55 // find minimum grade
studentGrades[0] is
56 int minimum( int grades[][ exams ], int itself
pupils, intantests
array. )
57 {
58 int lowGrade = 100; // initialize to highest possible grade
59
60 for ( int i = 0; i < pupils; i++ )
61
62 for ( int j = 0; j < tests; j++ )
63
64 if ( grades[ i ][ j ] < lowGrade )
65 lowGrade = grades[ i ][ j ];
66
67 return lowGrade;
68
69 } // end function minimum

 2003 Prentice Hall, Inc.


All rights reserved.
31
70
71 // find maximum grade
Outline
72 int maximum( int grades[][ exams ], int pupils, int tests )
73 {
74 int highGrade = 0; // initialize to lowest possible grade
75
76 for ( int i = 0; i < pupils; i++ )
77
78 for ( int j = 0; j < tests; j++ )
79
80 if ( grades[ i ][ j ] > highGrade )
81 highGrade = grades[ i ][ j ];
82
83 return highGrade;
84
85 } // end function maximum
86

 2003 Prentice Hall, Inc.


All rights reserved.
32
87 // determine average grade for particular student
88 double average( int setOfGrades[], int tests )
Outline
89 {
90 int total = 0;
91
92 // total all grades for one student
93 for ( int i = 0; i < tests; i++ )
94 total += setOfGrades[ i ];
95
96 return static_cast< double >( total ) / tests; // average
97
98 } // end function maximum

 2003 Prentice Hall, Inc.


All rights reserved.
33
99
100 // Print the array
Outline
101 void printArray( int grades[][ exams ], int pupils, int tests )
102 {
103 // set left justification and output column heads
104 cout << left << " [0] [1] [2] [3]";
105
106 // output grades in tabular format
107 for ( int i = 0; i < pupils; i++ ) {
108
109 // output label for row
110 cout << "\nstudentGrades[" << i << "] ";
111
112 // output one grades for one student
113 for ( int j = 0; j < tests; j++ )
114 cout << setw( 5 ) << grades[ i ][ j ];
115
116 } // end outer for
117
118 } // end function printArray

 2003 Prentice Hall, Inc.


All rights reserved.
34
The array is:
[0] [1] [2] [3]
Outline
studentGrades[0] 77 68 86 73
studentGrades[1] 96 87 89 78
studentGrades[2] 70 90 86 81
 
Lowest grade: 68
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75

 2003 Prentice Hall, Inc.


All rights reserved.

You might also like