Upload
prosper-greene
View
232
Download
0
Embed Size (px)
Citation preview
C++ ProgrammingLecture 14
Arrays – Part I
ByGhada Al-MashaqbehThe Hashemite UniversityComputer Engineering Department
The Hashemite University 2
Outline
Introduction. Arrays declarations and
initialization. Const variables. Character arrays. Static arrays. Examples.
The Hashemite University 3
Introduction Arrays
Structures of related data items. Static entity - same size throughout program.
Structures and classes are also static entities that group related data items.
In chapter 5 dynamic arrays concepts will be introduced in which you can change the ize of the array throughout the program based on pointers concepts.
Queues, vectors, link lists, and stacks are some examples of dynamic arrays in C++ which are based on pointers.
The Hashemite University 4
Arrays I Array
One type of data structures. Consecutive group of memory locations Same name and type Static data structure in which its size remain
the same during the program execution. To refer to an element, specify
Array name and position number Format: arrayname[ position number ]
First element at position 0 n element array c:
c[ 0 ], c[ 1 ]…c[ n - 1 ]
The Hashemite University 5
Arrays II Array elements are like normal variables
c[ 0 ] = 3;cout << c[ 0 ];
Performing operations in subscript. If x = 3,c[ 5 – 2 ] == c[ 3 ] == c[ x ]
ith element in an array has the index (or subscript) of i – 1.
Array element i has a an index of i. The subscript must be an integer value, where
it could be: Constant. Variable. Expression. A result of a function call.
The Hashemite University 6
Arrays III
c[6]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
Name of array (Note that all elements of this array have the same name, c)
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
Position number of the element within array c
The Hashemite University 7
Declaring Arrays Declaring arrays - specify:
Name Type of array Number of elements Examples
int c[ 10 ];
float hi[ 3284 ];
Declaring multiple arrays of same type Similar format as other variables Example
int b[ 100 ], x[ 27 ];
The Hashemite University 8
Arrays Initialization Two methods to initialize an array:
Using a loop. Using an initializers list.
Initializersint n[ 5 ] = { 1, 2, 3, 4, 5 }; If not enough initializers, rightmost elements become 0 If too many initializers, a syntax error is generated
int n[ 5 ] = { 0 } Sets all the elements to 0 since the first element is
initialized to 0 and the rest are implicitly initialized to 0.
If size omitted, the initializers determine itint n[] = { 1, 2, 3, 4, 5 }; 5 initializers, therefore n is a 5 element array
The Hashemite University 9
1 // Fig. 4.4: fig04_04.cpp
2 // Initializing an array with a declaration3 #include <iostream>45 using std::cout;6 using std::endl;78 #include <iomanip>910 using std::setw;1112 int main()13 {14 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };15 16 cout << "Element" << setw( 13 ) << "Value" << endl;1718 for ( int i = 0; i < 10; i++ )19 cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;2021 return 0;22 }
Element Value 0 32 1 27 2 64 3 18 4 95 5 14 6 90 7 70 8 60 9 37
Notice how they array is declared and elements referenced.
The Hashemite University 10
const Variables Also called named constants or read-only variables. Reserve space in memory. Must be initialized when declared to avoid getting a syntax
error. A constant variable cannot be modified throughout the
program after it is being declared. Arrays sizes are usually declared with type const since they
are static. If you want to declare the size of an array using a variable
this variable must be declared const, otherwise you will get a syntax error, e.g.:int x = 10;int c_class[x]; // syntax error
//Butconst int x = 10;int c_class[x]; //Correct
The Hashemite University 11
1 // Fig. 4.7: fig04_07.cpp
2 // A const object must be initialized
3
4 int main()
5 {
6 const int x; // Error: x must be initialized
7
8 x = 7; // Error: cannot modify a const variable
9
10 return 0;
11 }
Fig04_07.cpp:Error E2304 Fig04_07.cpp 6: Constant variable 'x' must be initialized in function main()Error E2024 Fig04_07.cpp 8: Cannot modify a const object in function main()*** 2 errors in Compile ***
Notice that const variables must be initialized because they cannot be modified later.
The Hashemite University 12
Character Arrays I Strings is the same as array of characters. All strings end with NULL or '\0' Character array initialization:
With string literal, Examples:char string1[] = "hello";
With initializers, Examples:char string1[] = { 'h', 'e', 'l', 'l', 'o', '\0’ };
Input from keyboardchar string2[ 10 ];cin >> string2;
Takes user input Side effect: if too much text entered, data written
beyond array
The Hashemite University 13
Character Arrays II Subscripting is the same as for a normal array
String1[ 0 ] is 'h'string1[ 2 ] is 'l'
Remember that cin stop reading from keyboard at the first white space.
If you enter a string with smaller size than the array size using cin, cin will automatically add a NULL at the end of the string within the array.
cout stop printing an array of character when it reaches the ‘\0’.
Character arrays that do not terminate with NULL (i.e. not strings) cannot be printed using cout , it will enter an infinite loop logical error.
The Hashemite University 14
1 // Fig. 4_12: fig04_12.cpp2 // Treating character arrays as strings3 #include <iostream>45 using std::cout;6 using std::cin;7 using std::endl;89 int main()10 {11 char string1[ 20 ], string2[] = "string literal";1213 cout << "Enter a string: ";14 cin >> string1;15 cout << "string1 is: " << string116 << "\nstring2 is: " << string217 << "\nstring1 with spaces between characters is:\n";1819 for ( int i = 0; string1[ i ] != '\0'; i++ )20 cout << string1[ i ] << ' ';2122 cin >> string1; // reads "there"23 cout << "\nstring1 is: " << string1 << endl;2425 cout << endl;26 return 0;27 }
Enter a string: Hello therestring1 is: Hellostring2 is: string literalstring1 with spaces between characters is:H e l l o string1 is: there
Notice how string elements are referenced like arrays.
Inputted strings are separated by whitespace characters. "there" stayed in the buffer.
The Hashemite University 15
Static Arrays
Similar to static storage variable you can define an array to be static.
So this array will not be destroyed when you outside the scope in which it exists.
If you do not initialize a static array, by default the compiler will initialize all its elements to 0.
The Hashemite University 16
Examples
On board: Drawing histograms. Average, sum, product, and display of
an array. Static arrays.
The Hashemite University 17
Notes
Going outside the range of an array is a logical error in C++.
There are additional examples of using arrays in the textbook, study them.
The Hashemite University 18
Additional Notes
This lecture covers the following material from the textbook: Fourth Edition
Chapter 4: Sections 4.1 – 4.4