Basic Array Definition // Subscripts are 0 through 99
Example Definitions Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000; Then the following are all correct array definitions int A[10]; // array of 10 ints char B[MaxStringSize]; // array of 80 chars double C[M*N]; // array of 800 floats int Values[MaxListSize]; // array of 1000 ints Rational D[N-15]; // array of 5 Rationals
Subscripting Suppose int A[10]; // array of 10 ints A[0], … A[9] To access individual element must apply a subscript to list name A A subscript is a bracketed expression also known as the index First element of list has index 0 A[0] Second element of list has index 1, and so on A[1] Last element has an index one less than the size of the list A[9] Incorrect indexing is a common error A[10] // does not exist
Array Elements Suppose int A[10]; // array of 10 uninitialized ints To access an individual element we must apply a subscript to list name A
Array Element Manipulation Consider int i = 7, j = 2, k = 4; A[0] = 1;
Array Element Manipulation Consider int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5;
Array Element Manipulation Consider int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3;
Array Element Manipulation Consider int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3; A[j+1] = A[i] + A[0];
Array Element Manipulation Consider int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3; A[j+1] = A[i] + A[0]; A[A[j]] = 12;
Array Element Manipulation Consider int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3; A[j+1] = A[i] + A[0]; A[A[j]] = 12; cin >> A[k]; // where next input value is 3
Array Initialization During Declaration suppose int x[10] = {8,5,4} x = {8,5,4,0,0,0,0,0,0,0} int y[10] = {0} y = {0,0,0,0,0,0,0,0,0,0}
Array Element Manipulation For loop is the typical construct to be used for array element manipulation Declare and initializes a double type array of ten elements with 10.0 stored at each index/location of the array, use for loop for initialization double arr1[10]; for (int index= 0; index<10; index++) arr1[index] = 10.0;
Array As an Entity Suppose int x[10]; int y[10]; y = x; illegal cin>>x; illegal cout<<y illegal if (x<=y) ... illegal
Array Element Input/Output To fill an array from user’s input double arr1[10]; for (int index= 0; index<10; index++) cin>>arr1[index]; To output an array onto the screen cout<<arr1[index] <<“ “;
Array Element Manipulation Write down a code that declares two double type arrays of 10 elements each, it gets them initialized from the user and finally decides and prints whether the arrays are equal or not.
Array Element Manipulation double arr1[10]; double arr2[10]; for (int index= 0; index<10; index++) { cin>>arr1[index]; cin>>arr2[index]; } if (arr1[index] != arr2[index] ...
Printing in reverse order using arrays How to print an array in the reverse order
Printing in reverse order using arrays int main() { int item[5]= {5,6,7,8,9}; //Declare an array item of five //components for (counter = 4; counter >= 0; counter--) cout << item[counter] << " "; cout << endl; return 0; }
How to check whether an Array is sorted Write down a code that checks whether an array (named arr2 of 10 ints, already initialized) is already sorted in ascending order or not.
How to check whether an Array is sorted int arr2[10]; …//array initialized bool sorted = true; for (int index=0; index<9; index++) { if (arr2[index + 1]<arr2[index]) {sorted = false; break; }
(Generic and complete code) const int size = 5; int arr2[size]= {1,2,3,4,5}; bool sorted = true; for (int index=0; index<size-1; index++) { if (arr2[index +1]<arr2[index]) {sorted = false; break; }
(Generic and complete code) if (sorted==true) cout<< "sorted"; else cout<< "unsorted";
Max of an array How to start? Write down a code that finds out the element having maximum value within the array, the code finds out the location of the max as well. How to start?
Max of an array const int listSize= 100; int list[listSize]; int index; for (index = 0; index < listSize; index++) cin>>list[index]; int maxIndex = 0; //Assume the first element is the largest for (index = 1; index < listSize; index++) if (list[maxIndex] < list[index]) maxIndex = index; cout<<list[maxIndex]<<“ “<< maxIndex;
Sorting of Arrays Bubble Sort (Ascending order) Compare the first element with the second one, swap if second is smaller Do the same process with element 2 and 3, and so on, till the end of the array (Name this process as a “Pass”) Choose the worst case that is an array already sorted in descending order to find out the number of passes Choose the following array to apply the above algorithm {9, 8,7, 5, 4, 3, 2, 1} Find out the number of comparisons/pass and no. of passses
Sorting of arrays 9 8 6 4
Sorting of arrays 8 9 6 4
Sorting of arrays 8 6 9 4
Sorting of arrays 8 6 4 9 One “Pass” completed
Sorting of arrays 8 6 4 9
Sorting of arrays 6 8 4 9
Sorting of arrays 6 4 8 9
Sorting of arrays 6 4 8 9 2nd “Pass” completed
Sorting of arrays 6 4 8 9
Sorting of arrays 4 6 8 9
Sorting of arrays 4 6 8 9
Sorting of arrays 4 6 8 9 3rd “Pass” completed. Sorting completed.
Sorting (Bubble Sort) int main() { const int arraySize = 10; int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; int hold; // temporary variable // bubble sort // loop to control number of passes for ( int pass = 0; pass < arraySize - 1; pass++ ) // loop to control number of comparisons per pass for ( int j = 0; j < arraySize - 1; j++ )
Sorting (Bubble Sort) // compare side-by-side elements and swap them if // first element is greater than second element if ( a[ j ] > a[ j + 1 ] ) { hold = a[ j ]; a[ j ] = a[ j + 1 ]; a[ j + 1 ] = hold; } // end if return 0; } // end main
Base Address of a Function int main() { int myList[5] = {0, 2, 4, 6, 8}; int yourList[5]; cout << "Line 3: Base address of myList: " << myList << endl; return 0; }
Base Address of a Function A sample run of this program is: // Line 3: Base address of myList: 0012FEC4 This is hexadecimal representation of the binary number 00000000000100101111111011000100 The decimal representation of this number is 1,244,868
Passing Arrays to Functions Passed by reference only The symbol & not used Normally size of the array also passed as another int type variable Functions cannot return a value of type array
Passing Arrays to Functions const int ARRAY_SIZE = 10; void fillArray(int x[],int sizeX); int main() { int listA[ARRAY_SIZE] = {0}; fillArray(listA, ARRAY_SIZE); return 0; } void fillArray(int list[], int listSize) { int index; for (index = 0; index < listSize; index++) cin >> list[index]; }
Passing Arrays to Functions We can prevent an array from being changed by the function being called by using the reserve word “const”
Passing Arrays to Functions const int ARRAY_SIZE = 10; int sumArray(const int x[],int sizeX); void fillArray(int x[],int sizeX); void copyArray(const int x[], int y[], int length); int main() { int listA[ARRAY_SIZE] = {0}; int listB[ARRAY_SIZE]; fillArray(listA, ARRAY_SIZE); cout << sumArray(listA, ARRAY_SIZE) << endl; copyArray(listA, listB, ARRAY_SIZE); return 0; }
Passing Arrays to Functions int sumArray(const int list[], int listSize) { int index; int sum = 0; for (index = 0; index < listSize; index++) sum = sum + list[index]; return sum; } void copyArray(const int listOne[], int listTwo[], int listOneSize) for (index = 0; index < listOneSize; index++) listTwo[index] = listOne[index];
Character Arrays Character Array: An array of Characters Can be declared by user Its size is determined by the user’s statement E.g. char name[5]= {‘A’, ‘l’, ‘i’} char name[5]=“Ali” char name[]=“Ali”
C Strings A predefined data type in C++, that is similar to character arrays, but has the following differences Size of strings is automatic A string always terminates at null character (‘\0’) We shall use the concept of character arrays and strings interchangeably therefore we redefine the previous examples as follows char name[5]= {‘A’, ‘l’, ‘i’, ‘\0’} char name[5]=“Ali” char name[]=“Ali” Now we can treat them as strings
Length of the character array Write down a code segment that finds out and displays the length (excluding the null character), of a character array. character array is obviously null terminated and defined and initialized somewhere else in the code. int len =0; while (arr1[len] != '\0') { len++; }
Question Write down a code segment that finds the smallest number present in five different int arrays. The arrays are already initialized and have the names arr1 having arrSize1 arr2 having arrSize2 and so on Last array is arr5 having arrSize5 Use a general function smallestNumber to find the smallest within an array. You can use this function repeatedly to solve the problem. You can use a temporary array having size equal to 5, if required. Do not declare or initialize the actual five arrays, they are already declared and initialized.
Two dimensional arrays A collection of fixed number of components arranged in rows and columns dataType arrayName[int rows][int cols] For example double sales[10][5]
Two dimensional arrays [0][0] [0][1] [0][2] [0][3] [0][4] [1][0] … [9][4]
Two dimensional arrays (Initialization) const int NUMBER_OF_ROWS = 6; const int NUMBER_OF_COLUMNS = 5; int board[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS] = {0}; 0 0 0 0 0
Two dimensional arrays (Initialization) const int NUMBER_OF_ROWS = 6; const int NUMBER_OF_COLUMNS = 5; int board[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS] = {{23, 5}, {4, 16, 24, 67, 10}, {12, 54, 23, 76, 11}, {1, 12, 34, 22, 8}, {81, 54, 32, 67, 33}, };
Two dimensional arrays (Initialization) 23 5 0 0 0 4 16 24 67 10 12 54 23 76 11 1 12 34 22 8 81 54 32 67 33 0 0 0 0 0
Two dimensional arrays (Printing) Write down code to print the above mentioned two dimensional array if a difference of 5 spaces is to be printed between two adjacent row elements. int row, col; for (row = 0; row < NUMBER_OF_ROWS; row++) { for (col = 0; col < NUMBER_OF_COLUMNS; col++) cout << setw(5) << board[row][col] << " "; cout << endl; }
Two dimensional arrays (Printing) Write down code to print the above mentioned two dimensional array into a file. int row, col; ofstream o; o.open("d:\\twodARR2.txt"); for (row = 0; row < NUMBER_OF_ROWS; row++) { for (col = 0; col < NUMBER_OF_COLUMNS; col++) o << setw(5) << matrix[row][col] << " "; o << endl; }
Two dimensional arrays int row, col; int X; for (row = 0; row < NUMBER_OF_ROWS; row++) { X = 0; for (col = 0; col < NUMBER_OF_COLUMNS; col++) X = X + matrix[row][col]; cout << X<< endl; } Sum of each individual row
Two dimensional arrays int row, col; int x; for (row = 0; row < NUMBER_OF_ROWS; row++) { x = matrix[row][0]; for (col = 1; col < NUMBER_OF_COLUMNS; col++) if (x < matrix[row][col]) x = matrix[row][col]; cout << x << endl; } Largest element in each row
Two dimensional arrays (diagonal reversing algo ) 1 2 3 4
Two dimensional arrays (diagonal reversing algo ) 4 2 3 1
Two dimensional arrays (diagonal reversing algo ) 4 3 2 1
Two dimensional arrays (diagonal reversing algo ) for (row=0; row<ROWS/2; row++){ temp = matrix[row][row]; matrix[row][row] = matrix[ROWS-1-row][ROWS-1-row]; matrix[ROWS-1-row][ROWS-1-row] = temp; }
Passing Two D Arrays to Functions C++ stores a 2d array as if it is a collection of 1d arrays placed row wise with in the memory Therefore the function call must have the number of columns within it e.g. Consider the following function definition void funone(int table[][5], int rowSize) i.e A two d array having 5 columns is accepted as a parameter. Row size comes as a separate parameter.
Passing Two D Arrays to Functions const int ROWS = 6; const int COLUMNS = 5; void printMatrix(int matrix[][COLUMNS], int ROWS); void sumRows(int matrix[][COLUMNS], int ROWS); void largestInRows(int matrix[][COLUMNS], int ROWS); int main() { int board[ROWS][COLUMNS] = {...}; printMatrix(board, ROWS); sumRows(board, ROWS);
Passing Two D Arrays to Functions void sumRows(int matrix[][COLUMNS], int noOfRows) { int row, col; int sum; for (row = 0; row < noOfRows; row++) sum = 0; for (col = 0; col < COLUMNS; col++) sum = sum + matrix[row][col]; cout << "Sum of row " << (row + 1) << " = " << sum<< endl;