Download presentation
Presentation is loading. Please wait.
Published byJanis Gilmore Modified over 6 years ago
1
Arrays Arrays exist in almost every computer language.
An array is a data structure defined in order to hold a group of values or data items of the same data type. Arrays can hold a few data items or tens of thousands. The data items grouped in an array can be simple types such as int, char or float, or user-defined types such as structures and objects. Unlike a structure an array groups items of the same data type. Also, the items in a structure are accessed by name, while those in an array are accessed by an index number.
2
Defining Arrays An array definition specifies a variable type, a name, and a size. The size specifies how many data items the array can contain. All arrays in C++ have indices that start at 0. Accordingly: the size of an array = the last element index +1
3
Defining and Accessing Arrays
The number of array elements ( array size ) must be a constant (literal or symbolic) or an expression that uses constants. Examples of declaring arrays: int monthDays[12]; // with literal constant const int MAX = 30; char studentName[ MAX ]; // with symbolic constant const int SIZE = 40; char studentAddress[ SIZE +1 ]; // with a constant expression Once an array is declared, its elements can be accessed using the index operator [ ]. int anIndex; arrayName [ anIndex ] // where 0 <= anIndex <= array size -1
4
A Simple Program Using an Array
// receive four grades from user, displays them #include <iostream> using namespace std; int main() { float grade[4]; //array ‘grade’ of 4 float values for(int j=0; j<4; j++) //enter 4 grades cout << “Enter a grade: “; cin >> grade [j]; //assign an entered value to an //array element } for(j=0; j<4; j++) //display 4 ages cout << “You entered “ << grade[j] << endl; return 0; Enter a grade: 80.5 Enter a grade: 75 Enter a grade: 90 Enter a grade: 68.5 You entered 80.5 You entered 75 You entered 90 You entered 68.5 Press any key to continue
5
Notes when dealing with Arrays
The items in an array are called elements (members in a structure). An array must be defined before it can be used to store information. Using a constant variable (instead of a number) to specify the array size makes it easier to change the array size: Only one program line needs to be changed to change the array size, loop limits, and anywhere else the array size appears. const int SIZE = 4; float grade[SIZE]; …. Each array element can be initialized when the array is firstly defined: int days_per_month[12] = { 31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31 };
6
Array Initialization. NOTES,
we may ignore the array size when we initialize all the array elements, since the compiler can figure it out by counting the initializing values: int days_per_month[] = { 31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31 }; When an explicit array size doesn’t agree with the number of initializers: a) If there are too few initializers, the missing elements will be set to 0. b) If there are too many (greater than the array size), an error is signaled.
7
Array Initialization. NOTES,
The initializing list may contain a number of initial values that is equal to or less than the number of elements in the initialized array. The compiler assigns the first initializing value to the element at index 0, the second initializing value to the element at index 1, and so on. When an explicit array size doesn’t agree with the number of initializers: a) If the initializers <= the array size, the missing elements will be set to 0. b) If the initializers is greater than the array size, an error will be signaled. we may ignore the array size when we initialize all the array elements, since the compiler can figure it out by counting the initializing values: int days_per_month[] = { 31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31 };
8
Specifying the array size as a constant variable
// receive four grades from user, displays them #include <iostream> using namespace std; int main() { Const SIZE = 4; float grade[SIZE]; //array ‘grade’ of 4 float values for(int j=0; j< SIZE; j++) //enter 4 grades cout << “Enter a grade: “; cin >> grade [j]; //access an array element } for(j=0; j<4; j++) //display 4 ages cout << “You entered “ << grade[j] << endl; return 0; Enter a grade: 80.5 Enter a grade: 75 Enter a grade: 90 Enter a grade: 68.5 You entered 80.5 You entered 75 You entered 90 You entered 68.5 Press any key to continue
9
Accessing Array Elements
In order to access an array element number x: we may write the name of the array, followed by two square brackets enclosing the index of that element (x-1). We may use the address of the first element in the array plus the number of the desired element . Notice that: Assuming an array of size n the first array element is numbered 0 and the last one is numbered (n - 1). Note: Using a variable (instead of a number) makes it easier to change the array size: Only one program line needs to be changed to change the array size, loop limits, and anywhere else the array size appears.
10
Total days from start of year is: 70
// The program shows the days from the start of the year to the date specified #include <iostream> using namespace std; int main() { const int SIZE =12; int month, day, total_days; int days_per_month[SIZE] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; cout << “\n Enter month (1 to 12): “; //get date cin >> month; cout << “Enter day (1 to 31): “; cin >> day; total_days = day; //separate days for(int j=0; j<=month-1; j++) //add days each month total_days += days_per_month[j]; cout << “Total days from start of year is: “ << total_days << endl; return 0; } Enter month (1 to 12): 3 Enter day (1 to 31): 11 Total days from start of year is: 70
11
Multidimensional Arrays
C++ requires declaring a multidimensional array before using it. The declaration starts by the Multidimensional array type followed by a sequence of integer numbers each one is enclosed within a square brackets and specify the size of one dimension. Each number of elements for each dimension must be a constant (literal or symbolic) or an expression that uses constants. All multidimensional arrays in C++ have indices that start at 0. Thus, the number of array elements in each dimension is one value higher than the index of the last element in that dimension.
12
Declaring Multidimensional Arrays
// example 1: declaring a three-dimensional array with 3 literal constants int nIntCube[20][10][5]; // example 2: declaring a two-dimensional array with 2 symbolic constants const int MAX_ROWS = 50; const int MAX_COLS = 20; double fMatrix[MAX_ROWS][MAX_COLS]; // example 3: declaring a two-dimensional array with 2 constant expressions const int MAX_ROWS = 30; const int MAX_COLS = 10;char cNameArray[MAX_ROWS+1][MAX_COLS];
13
Accessing Multidimensional Arrays
Once a multidimensional array was declared, its elements can be accessed using the index operator [ ]. The general syntax for accessing an element in a multidimensional array is: arrayName[indexOfDimension1][indexOfDimension2]... Where 0<=indexOfDimension1<= size of diminsion1 and 0<=indexOfDimension2<= size of diminsion2 . and so on
14
Initializing Multidimensional Arrays
C++ allows you to initialize some or all of the elements of a multidimensional array. The general syntax for initializing a multidimensional array is: type arrayName[numberOfElement1][numberOfElement2] = { value0 ,...,valueN }; The list of initial values appears in a pair of open and close braces and is comma-delimited. The list may contain a number of initial values that is equal to or less than the total number of elements in the initialized array. Otherwise, the compiler generates a compile-time error. The compiler assigns the initializing values in the sequence discussed in the sidebar “Initializing Multidimensional Arrays.” If the list contains fewer values than the number of elements in the array, the compiler assigns zeros to the elements that do not receive initial values from the list.
15
Initializing Multidimensional Arrays
// example 1 double fMat[3][2] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 }; // example 2 int nMat[5][2] = { 1, 2, 3, 4, 5 }; // example 3 double fMat[3][2] = {{ 1.1, 2.2}, {3.3, 4.4}, {5.5, 6.6} }; // example 4 double fMat[3][2] = {{ 1.1, 2.2}, {3.3}, {5.5, 6.6} };
16
A two-dimensional array to store sales values for several districts and several months:
17
// displays sales chart using 2-d array #include <iostream>
#include <iomanip> //for setprecision, etc. using namespace std; const int DISTRICTS = 4, MONTHS = 3; //array dimensions int main() { int d, m; double sales[DISTRICTS][MONTHS]; //two-dimensional array definition cout << endl; for(d=0; d<DISTRICTS; d++) //get array values for(m=0; m<MONTHS; m++) cout << “Enter sales for district “ << d+1; cout << “, month “ << m+1 << “: “; cin >> sales[d][m]; //put number in array } cout << “\n\n”; cout << “ \t\t\tMonth\n”; cout << “ \t\t1 \t 2 \t 3”; for(d=0; d<DISTRICTS; d++) cout <<”\nDistrict “ << d+1; for(m=0; m<MONTHS; m++) //display array values cout << setiosflags(ios::fixed) //not exponential << setiosflags(ios::showpoint) //always use point << setprecision(2) //digits to right << setw(10) //field width << sales[d][m]; //get number from array return 0; } //end main
18
// displays sales chart, initializes 2-d array
#include <iostream> #include <iomanip> //for setprecision, etc. using namespace std; const int DISTRICTS = 4; //array dimensions const int MONTHS = 3; int main() { int d, m; //initialize array elements double sales[DISTRICTS][MONTHS] = { { , , }, { , , }, { , , }, { , , } }; cout << “\n\n”; cout << “ \t\t\tMonth\n”; cout << “ \t\t 1\t 2 \t 3”; for(d=0; d<DISTRICTS; d++) cout <<”\nDistrict “ << d+1; for(m=0; m<MONTHS; m++) cout << setw(10) << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(2) << sales[d][m]; //access array element } cout << endl; return 0;
19
C-strings described as arrays of type char.
// This simple program demonstrates how to deal // with strings using arrays of type char #include <iostream.h> int main() { const int MAX = 80; // max characters in string char str1[MAX]; // string variable str1 char str2[]=“you are wellcome in c++”; // assign a string value cout << “Enter a string: “; cin >> str1; // put string in str1 cout << “You entered: “ << str1 << endl; // value of str1 cout << “The value of str2 is “ << str2 << endl; // value of str2 return 0; }
20
String Constants // initializeing a string to a constant value
# include <iostream.h> int main() { char str[] = “This way enables inserting string with blanks”; cout << str << endl; return 0; }
21
Avoiding Buffer Overflow with C-strings
// tell the >> operator to limit the number of characters it places in // an array to avoid inserting array elements outside an array. #include <iostream.h> #include <iomanip.h> // for setw int main() { const int MAX = 20; // max characters in string char str [ MAX]; // string variable str cout << “\nEnter a string: “; cin >> setw(MAX) >> str; // put string in str, // no more than MAX chars cout << “You entered: “ << str << endl; return 0; }
22
Avoiding Buffer Overflow with C-strings
// To insert text containing blanks we use another function, cin.get(). #include <iostream.h> int main() { const int MAX = 80; //max characters in string char str [MAX]; //string variable str cout << “\n Enter a string: “; cin.get( str, MAX); //put string in str cout << “You entered: “ << str << endl; return 0; }
23
Reading Multiple Lines of strings
The cin::get() function can take a third argument. This argument specifies the character that tells the function to stop reading from the keyboard. The default value for this argument is the newline (‘\n’) character. // call the function with a dollar sign (‘$’) to read characters until typing // ‘$’ then press enter #include <iostream.h> const int MAX = 2000; //max characters in string char str [MAX]; //string variable str int main() { cout << “\n Enter a string: \n”; cin.get ( str, MAX, ‘$’); //terminate with $ cout << “You entered:\n” << str << endl; return 0; } // Note: you must press Enter after typing the ‘$’ character.
24
Copying a String the Hard Way using arrays and loops
#include <iostream.h> #include <cstring> //for strlen() int main() { //initialized string char str1[] = “Wellcom, you are welcome in Egypt “; const int MAX = 80; //size of str2 buffer char str2[MAX]; //empty string for(int j=0; j<strlen(str1); j++) //copy strlen characters str2[j] = str1[j]; // from str1 to str2 str2[j] = ‘\0’; //insert NULL at end cout << str2 << endl; //display str2 return 0; }
25
Copying a String the Hard Way using arrays and loops
// copies a string using strcpy() function #include <iostream.h> #include <cstring> //for strcpy() int main() { char str1[] = “Tiger, tiger, burning bright\n” “In the forests of the night”; const int MAX = 80; //size of str2 buffer char str2[MAX]; //empty string strcpy(str2, str1); //copy str1 to str2 cout << str2 << endl; //display str2 return 0; }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.