Download presentation
Presentation is loading. Please wait.
1
CHAPTER 3 ARRAYS
2
Introduction What can you tell about each group of above pictures?
Bugs Airplanes Characters Cards What can you tell about each group of above pictures? - Share similar characteristics - though each one still maintains specific features Everyone of the items on the first picture is an airplane; if you decide to be specific, then you may state that the first airplane of the group is bright green while the second is black; the first and the fourth airplanes don't have helices although all the others do. On the second picture (from left to right), all of these items are bugs; they don't seem to look alike, but everyone of them is still a bug. Everyone of the items on the third picture is a card, same size, same white background, though they display different card values, different character colors (and they would have different effects depending on how your game is going). Whenever you are typing, you are aligning arrays of characters, characters as those of the last picture. This shows that a word or a sentence is actually a group or letters.
3
Array in C++ Collection of objects of the same type stored contiguously in memory under one name Why arrays? large quantities of similar data: list of scores, prices, Assigning a unique variable (and name) to each piece of data is tedious: float score1, score2, score3, score4,……;
4
Array in C++ (cont..) A single value in an array is called an element.
The contents of each element are of the same type. Could be an array of int, double, char, … We can refer to individual elements by giving the position number (subscript) of the element in the array.
5
Declaring An Array element_type array_name[number_of_elements];
element_type can be any C++ variable type. array_name can be any valid variable name. number_of_elements can be an expression.
6
Memory and Arrays foo[0] foo[1] int foo[6]; foo[5] 4 bytes
Each int is 4 bytes 507 foo[0] foo[1] int foo[6]; foo[5] Array type Array name Array size Array value Array subscript
7
Initialization You can initialize an array when you declare it (just like with variables): int foo[5] = { 1,8,3,6,12}; double d[2] = { 0.707, 0.707}; char s[] = { 'R', 'P', 'I' }; You don’t need to specify a size when initializing, the compiler will count for you.
8
If only millenniums started at 0 …
C++ Arrays start at 0 !!!!!!! The first element is the 0th element! If you declare an array of n elements, the last one is number n-1. If you try to access element number n it is an error! If only millenniums started at 0 …
9
foo[17] foo[i+3] foo[a+b+c]
Array Subscripts The element numbers are called subscripts. foo[i] Array name subscript A subscript can be any integer expression: These are all valid subscripts: foo[17] foo[i+3] foo[a+b+c]
10
Array Example int main(void) {
//use initializer list to initialize array n int n[5]={32,27,64,18,95}; cout<<“Element”<<setw(13)<<“Value”<<endl; //output each array element’s value for(int i=0; i<5;i++) cout<<setw(7)<<i<<setw(13)<<n[i]<<endl; return 0; } Result: Element Value
11
More Example /* Specifying an array’s size with a constant variable and setting array elements with calculations. */ int main() { //constant variable used to specify an array size const int arraySize=5; int s[arraySize]; //arrays has 5 elements for(int i=0; i<arraySize; i++) s[i]=2+2*i; cout<<“Element”<<setw(13)<<“Value”<<endl; //output contents of arrays in tabular format for(int j=0; j<arraySize; j++) cout<<setw(7)<<j<<setw(13)<<s[j]<<endl; return 0; } Result: Element Value
12
Operations of arrays Display array By using ‘for’ operation – looping
for(i=0; i<10; i++) cout<<A[i]; or cout<<A[0]; cout<<A[1]; cout<<A[2]; . cout<<A[9]; Display Reverse order for(i=9; i>=0; i++) cout<<A[i]; or cout<<A[9]; cout<<A[8]; cout<<A[7]; . cout<<A[0];
13
Operations of arrays (Continue)
Sum. ∑ A[i] int i, sum; sum=0; for(i=0; i<10; i++) sum=sum+A[i]; cout<<sum;
14
Operations of arrays (Continue)
Traversing i) *temp=A[0]; A[0]=A[1]; A[1]=A[2]; A[2]=A[3]; A[3]=A[4]; A[4]=A[5]; *A[5]=temp; temp=A[0]; for(i=0; i<5; i++) A[i]=A[i+1]; A[5]=temp; ii) Temp=A[5]; A[5]=A[4]; A[4]=A[3]; A[3]=A[2]; A[2]=A[1]; A[1]=A[0]; A[0]=temp; temp=A[5]; for(i=5; i>0; i--) A[i]=A[i-1]; 1 2 3 5 4 5 4 3 2 1
15
Operations of arrays (Continue)
iii) temp=A[0]; A[0]=A[1]; A[1]=temp; temp=A[2]; A[2]=A[3]; A[3]=temp; temp=A[4]; A[4]=A[5]; A[5]=temp; for(i=0; i<6, i=i+2) { temp=A[i]; A[i]=A[i+1]; A[i+1]=temp; } 5 4 3 2 1
16
Inserting items Case: Adding new items to the array. Items may be inserted anywhere. How? To insert an item at the end of array There must be sufficient space (to hold the new item). 64 60 89 88 53 73 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
17
Inserting items To insert in the middle Each item must be moved.
71 60 89 88 53 73 64 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] Before insert 71 at 3rd element 60 89 71 88 53 73 64 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] After insert 71 at 3rd element
18
Algorithm Inserting Items
Suppose: linear array A with N elements A[0], A[1], A[2],….A[n] New item = ITEM (to be inserted) position = k The algorithm (insert): 1. Initialize counter let j = counter of similar size of N. 2. While j≥k 2.1 Move each j-th element downward (increase position of j-th by one). 2.2 Decrease counter j by one. 3. Repeat (2) until all elements at j≥k moved downward. eg: A[j] = A[j-1] 4. Insert the new element: ITEM to k-th position. 5. Repeat size of an array Size should be N+1 – after adding a new data item. 6. Exit
19
Flow chart: Inserting items
Initialize j = N Insert k (position) A[j] = A[j-1] j-- j ≥ k A[k] = new item end Yes No for ( j = N; j ≥ k; j--) { A[j] = A[j-1]; } A [k] = ITEM; N = size array k = position to be inserted ITEM = value of new item
20
Deleting items To delete in the middle Each item must be moved.
60 89 71 88 53 73 64 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] Before delete 88 at 4th element 60 89 71 53 73 64 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] After delete 88 at 4th element
21
Algorithm Deleting items
Suppose: linear array A with N elements A[0], A[1], A[2],….A[n] Delete item = ITEM (to be deleted) position = k The algorithm (delete): Initialize counter. Let j be a counter similar size to k. 2. While j is less than or equal to N-1 2.1 Move each j-th element upward. This is done by decreasing the position of every j-th element by one from its previous position. 2.2 Increase counter j by one. Repeat step 2 until all the j-th elements at location less than or equal to the k-th has been moved upward. The k-th element will be deleted Reset the size of A. 5. Exit.
22
Flow chart: Deleting items
Delete k (position) Initialize j = k A[j] = A[j+1] j++ j <N end Yes No for ( j = k; j < N; j++) { A[j] = A[j+1]; } N = size array k = position to be deleted
23
Inserting & Deleting Items Example
//Basic program to insert & delete #include<iostream> using std::cout; using std::cin; using std::endl; void main() { int A[6] = {1,2,3,4,5}; int i,in,data,del; for(i=0; i<5; i++) cout<<A[i]<<" "; cout<<endl; //to insert cout<<"index to insert: "; cin>>in; cout<<"new data to insert: "; cin>>data; for(i=5; i>in; i--) A[i] = A[i-1]; A[in]=data; for(i=0;i<5+1;i++) //to delete cout<<"index to delete: "; cin>>del; for(i=del; i<5; i++) A[i] = A[i+1]; } Result:
24
Linear Search Arrays Search array for a key value
Compare each element of array with key value Start at one end, go to other returns the index of the element in the array that matches the key, else return -1 Useful for small and unsorted arrays Inefficient If search key not present, examines every element Search until the key matches an element in the list or the list is exhausted without a match being found
25
Linear Search Animation
Key List 3 6 4 1 9 7 3 2 8 3 6 4 1 9 7 3 2 8 3 6 4 1 9 7 3 2 8 3 6 4 1 9 7 3 2 8 3 6 4 1 9 7 3 2 8 3 6 4 1 9 7 3 2 8
26
Linear Search Arrays Code Snippets
/** The method for finding a key in the list */ int linearSearch(int[] list, int key, int arraySize) { for (int i = 0; i < arraySize; i++) if (key == list[i]) return i; return -1; } Trace the method int[] list = {1, 4, 4, 2, 5, -3, 6, 2}; int i = linearSearch(list, 4, 8); // returns 1 int j = linearSearch(list, -4, 8); // returns -1 int k = linearSearch(list, -3, 8); // returns 5
27
Linear Search Arrays Example
//Linear search of an array. #include<iostream> using std::cout; using std::cin; using std::endl; int linearSearch(const int[], int, int); int main() { const int arraySize=100;/*size of array a */ int a[arraySize];//create array a int searchKey;/* value to locate in array a */ for(int i=0; i<arraySize; i++) a[i]=2*i;//create some data cout<<“Enter integer search key: “; cin>>searchKey; /*attempt to locate searchKey in array a */ int element=linearSearch(a, searchKey, arraySize); //display results if(element !=-1) cout<<“Found value in element”<<element<<endl; else cout<<“Value not found”<<endl; return 0; } /*compare key to every element of array until location is found */ int linearSearch(const int array[], int key, int sizeOfArray) { for(int j=0; j<sizeOfArray; j++) if(array[j]==key)//if found return j;//return location of key return -1;//key not found Result: Enter integer search key: 37 Value not found Result: Enter integer search key: 36 Found value in element 18
28
Insertion Sort Keeping expanding the sorted portion by one
Basic Idea: Keeping expanding the sorted portion by one Insert the next element into the right position in the sorted portion Algorithm: Start with one element [is it sorted?] – sorted portion While the sorted portion is not the entire array 2.1 Find the right position in the sorted portion for the next element 2.2 Insert the element 2.3 If necessary, move the other elements down 2.4 Expand the sorted portion by one
29
Insertion Sort (cont..) int[] myList = {2, 9, 5, 4, 8, 1, 6}; //Unsorted The insertion sort algorithm sorts a list of values by repeatedly inserting an unsorted element into a sorted sublist until the whole list is sorted. The main operation of the algorithm is insertion. The task is to insert a value into the sorted part of the array. Red fonts are the sorted part, while black fonts are the unsorted part. Array is imaginary divided into two parts - sorted one and unsorted one. At the beginning, sorted part contains first element of the array and unsorted one contains the rest. At every step, algorithm takes first element in the unsorted part and inserts it to the right place of the sorted one. When unsorted part becomes empty, algorithm stops. Sketchy, insertion sort algorithm step looks like this:
30
Insertion Sort Animation
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted 2 9 5 4 8 1 6 2 9 5 4 8 1 6 2 5 9 4 8 1 6 2 4 5 9 8 1 6 2 4 5 8 9 1 6 1 2 4 5 8 9 6 1 2 4 5 6 8 9
31
Insertion Sort Code Snippets
/** The method for insertion sort */ void insertionSort(int[] arr, int arraySize) { int next, moveItem, insert; for (next = 1; next < arraySize; next ++) insert = arr[next]; moveItem = next; while (moveItem > 0 && arr[moveItem - 1] > insert) arr[moveItem] = arr[moveItem - 1]; moveItem --; } arr[moveItem] = insert;
32
Arrays of Arrays You can create an array of arrays: int a[2][2];
for (int i=0;i<2;i++) for (int j=0;j<2;j++) a[i][j] = i+j;
33
2-D Array: int A[3][4] Col 0 Col 1 Col 2 Col 3 Row 0 Row 1 Row 2
34
2-D Memory Organization
{ A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2] A[2][0] A[2][1] A[2][2] A[3][0] A[3][1] A[3][2] char A[4][3]; A[0] A[1] A[2] A[3] { A is an array of size 4. Each element of A is an array of 3 chars { {
35
2-D Array Example const int NumStudents = 10; const int NumHW = 3;
double grades[NumStudents][NumHW]; for (int i=0;i<NumStudents;i++) { for (int j=0;j<NumHW;j++) { cout << “Enter HW “ << j << “ Grade for student number “ << i << endl; cin >> grades[i][j]; } Available via the course home page in code/arrays/2darray.cpp
36
Dynamic Arrays Normal arrays require that the programmer determine the size of the array when the program is written What if the programmer estimates too large? Memory is wasted What if the programmer estimates too small? The program may not work in some situations Dynamic arrays can be created with just the right size while the program is running
37
Dynamic Arrays (cont..) A dynamic array is an array whose size is determined when the program is running, not when you write the program Static arrays are declared prior to runtime and are reserved in stack memory.
38
Creating Dynamic Arrays
Dynamic arrays are created using the new operator Example: To create an array of 10 elements of type double: double *table; table = new double[10]; table can now be used as if it were an ordinary array! This could be an integer variable!
39
Deleting Dynamic Arrays
When finished with the array, it should be deleted to return memory to the freestore by using delete operator Example: delete [] table; The brackets tell C++ a dynamic array is being deleted so it must check the size to know how many indexed variables to remove Forgetting the brackets, is not legal, but would tell the computer to remove only one variable
40
Dynamic Arrays Example
#include <iostream> using namespace std; int main () { int i,n; int * p; cout << "How many numbers would you like to type? "; cin >> i; p = new int[i]; if (p == 0) cout << "Error: memory could not be allocated"; else { for (n=0; n<i; n++) cout << "Enter number: "; cin >> p[n]; } cout << "You have entered:"; cout << p[n] << ", "; delete[] p; } return 0;}
41
c++ program to add two matrices
#include<iostream> using namespace std; main() { int m, n, c, d, first[10][10], second[10][10], sum[10][10]; cout << "Enter the number of rows and columns of matrix "; cin >> m >> n; cout << "Enter the elements of first matrix\n"; for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) cin >> first[c][d]; cout << "Enter the elements of second matrix\n"; for ( c = 0 ; c < m ;c++ ) cin >> second[c][d]; for ( c = 0 ; c < m ; c++ ) sum[c][d] = first[c][d] + second[c][d]; cout << "Sum of entered matrices:-\n"; cout << sum[c][d] << "\t"; cout << endl; } return 0; c++ program to add two matrices
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.