Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR www.msc-it-m.wapka.mobi/index.xhtml.

Similar presentations


Presentation on theme: "Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR www.msc-it-m.wapka.mobi/index.xhtml."— Presentation transcript:

1 Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR www.msc-it-m.wapka.mobi/index.xhtml

2 Objectives The contents we are going to cover in this chapter: Concept of Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 2

3 Arrays Introduction An array is a group of consecutive memory locations with same name and data type. Simple variable is a single memory location with a unique name and a data type. But an array is a collection of adjacent memory locations. All these memory locations have one collective name and data type. o In above figure arr is the name of the Integer array (contiguous memory locations) with 10 random values. The contents of memory locations in the array are known as elements of array. Each element of an array has its own index (Integer) with reference to its position in the array. Each element in the array has a unique index. The index of: o First element is 0 o Last element is length-1 The value of the index is written in square brackets along with the name of array. o Example: cout << arr[0]; // output is 12 CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 3 arr 0123456789 124502614 204755

4 Advantages / Uses of Arrays Arrays are used to store a large amount of similar kind of data. Suppose the user wants to store the marks of 100 students and declares 100 variables. This process is so tedious & time consuming to use these variables individually. This process can be simplified by using array. An array of 100 elements can be declared to store these values instead of 100 individual variables. Advantages of Arrays Arrays can store a large number of values with single name. Arrays are used to process many values easily and quickly. The values stored in an array can be sorted easily. A search process can be applied on arrays easily. CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 4

5 Single Dimensional / Simple Array A type of array in which all elements are arranged in the form of a list is known as Single Dimensional or simply An Array or Linear Array. It consists of one column or one row. Declaration of an Array The process of specifying data-type of an array, it name & length is called Array Declaration Syntax – dataType valid_identifier[length] ; Example int marks[5]; The above example declares an integer array namely marks of five elements. It allocates five consecutive locations in memory. The index of first element is 0 and index of last element is 4. CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 5 marks marks[0]marks[1]marks[2]marks[3]marks[4]

6 Array Initialization The process of assigning values to array elements at the time of array declaration is Array Initialization. In initialization process, user has provides a list of initial values for array elements. The values are separated with commas and enclosed within curly braces { }. There must be at least one initial value between braces to initialize the entire array element with single value. A syntax error occurs if the values in braces are more than the length of array. If the number of initial values is less than the array size, the remaining array elements are initialized to zero. Syntax dataType identifier[Length] = { value1, value2,…, valueN }; Example – int marks [5] = {70, 54, 82, 96, 49}; The above statement declares integer array marks with five elements. The size / length of the array can be omitted when it is initialized in the declaration as follows: int age[] = {23, 56, 87, 92, 38,12, 15,6,3}; In this case complier will automatically calculates the length of the array CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 6 marks 70 54 82 96 49 marks[0]marks[1]marks[2]marks[3]marks[4]

7 Accessing Individual Elements of Array To access individual element of an array, we have to specify the following: o Name of array o Index of element Syntax – A rrayName[Index]; Example Code Snippet #include int main() { int marks[5]; marks[0] = 20; marks[1] = 50; marks[2] = 70; marks[3] = 80; marks[4] = 90; return 0; } CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 7

8 Accessing Array Elements using Loops Use of Loops in Arrays Mechanism An easier and faster way of accessing array elements is using loops. The following example shows how can we access individual elements of an array using for loop. int marks[5]; for(int i = 0; i < 5; i++) { // populating array elements marks[i] = i * 10; } The above example uses for loop to populate array elements. It uses the counter variable i as an index. In each iteration, the value of i is changed. The statement marks[i] refers to different array element in each iteration. CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 8

9 Input and Output Values of an Array The process of input and output with arrays is similar to the input and output with simple variables. The cin object of istream class is used to input values in the arrays. The cout object of ostream class is used to display values of arrays. However, the use of these objects with each individual element becomes very time-consuming because each element is treated as a simple variable. Various looping structures are frequently used to input and output data in an array. The use of loops with arrays makes the process of input and output faster and easier. It also reduces the code written for this purpose. CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 9 Comparison #include int main() { int marks[100]; marks[0] = 75 ; marks[1] = 67 ; marks[2] = 52 ; …………… marks[99] = 85 ; return 0; } #include int main() { int marks[100]; for(int i=0;i<100;i++) marks[i] = 1 + rand() % 100; return 0; } // Program Completes with few lines

10 Program Example Write a program that inputs five integers from the user and stores them in an integer-array and display the contents of array. #include void main() { int arr[5]; cout << "Enter five integers:"<<endl; cin>> arr[0] >> arr[1] >> arr[2] >> arr[3] >> arr[4]; cout << "\n\nThe values in the array:\n" ; cout <<"\t"<<arr[0]<<", "<<arr[1]<<", " << arr[2]<<", "<< arr[3]<<", "<<arr[4]<<endl; getch(); } CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 10 Enter five integers: 78 41 25 1 65 The values in the array: 78, 41, 25, 1, 65

11 Searching in Arrays Searching is a process of finding the required data in the array. Searching becomes more important when the length of the array is very large. Here we discuss two types of searching o Sequential Search o Binary Search Sequential search is also called Linear Search or Serial Search. It is a simple way to search an array for the desired value. It follows the following steps to search a value in array: 1.Visit the first element of the array and compare its value with the required value. 2.If the value of array matches with the desired value, the search is complete. 3.If the value of current element of array does not match, move to next element and repeat same process until the entire array is not visited. Loops are frequently used to visit elements of array for searching. A programmer can start the counter variable of loop from 0 and move it to last index of array. CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 11

12 Sequential Search (Program Example) Write a program that initializes an array. It inputs a value from the user and searches the number in the array. #include int main() { // initializing an array of integers int arr[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; int counter, toFind, location = -1; cout<<"Enter value to find: "; cin >>toFind; for (counter = 0 ; counter < 10; counter++) { if(arr[ counter ] == toFind) // if value found location = counter; // copy the index in location } if(location == -1) // if no change in the location cout << "Value not found in the array!!!" << endl; else cout << "Value Found in the array at index: "<< location << endl; return 0; } 12 CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays Enter value to find: 80 Value Found in the array at index: 7 Press any key to continue...

13 Binary Search Binary Search is a quicker method of searching for value in the array. It takes less time than sequential search. Binary Search requires sorting of array either ascending or descending. The procedure of binary search is discussed as: 1.It locates the middle element of array and compares with the required value. 2.If they are equal, search is successful and the index of middle element is returned. 3.If they are not equal, reduces the search to half of the array. 4.If the search number is less than the middle element, the first half of the array search-target, otherwise the second half of the array is search-target. 5.The process continues until the required number is found or loop completes without successful search. Binary search is very quick but it can search an array only if it is sorted. It cannot be applied on an unsorted array. CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 13

14 Binary Search (Program Example) Write a program that initializes an array 0f ten integers. It inputs an integer from the user and searches the value in the array using binary search. #include int main() { // Sorted Array (As prerequisite) int arr[10] = {10,20,30,40,50,60,70,80,90,100}; int toFind, mid, start, end, loc; loc =- 1;// temporarily value start = 0;// starting index of Array end = 9;// ending index of the Array cout<<"Enter an integer (10 ~ 100) to Find: "; cin>>toFind; while( start <= end ) { mid = (start + end)/ 2;// mid of Array if(arr[mid] == toFind) { loc = mid; break;// value found! } else if( toFind < arr[mid]) end = mid - 1; else start = mid + 1; } if(loc == -1) cout<<toFind<<" not found"<<endl; else cout<<toFind<<" found at index "<<loc<<endl; return 0; } CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 14 Enter an integer (10 ~ 100) to Find: 90 90 found at index 8 Press any key to continue... Enter an integer (10 ~ 100) to Find: 40 40 found at index 3 Press any key to continue... Enter an integer (10 ~ 100) to Find: 51 51 not found Press any key to continue...

15 Sorting Arrays Sorting is a process of arranging the values of array in a particular order. An array can be sorted in two orders: o Ascending o Descending Ascending Order o In ascending order, the smallest value is stored in the first element of array. o Second smallest value is stored in the second element and so on. o The largest value is stored in the last element. Descending Order o In descending order, the largest value is stored in the first element of array. o Second largest value is stored in the second element and so on. o The smallest value is stored in the last element. CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 15

16 Sorting Techniques / Algorithms Selection Sort Selection sort is a technique that sorts an array. It selects an element in the array and moves it to its proper position. Selection sort works as follows: 1.Find the smallest value in the list. 2.Swap it with the value in the first position. 3.Sort the remainder of the list excluding the first value. CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 16

17 Sorting Techniques / Algorithms Implementation of Selection Sort in C++ Program Write a program that gets five inputs from the user in an array and then sorts this array in ascending order. #include void main() { int arr[5]; for(int i = 0 ; i < 5 ; i++) { cout<<"Enter value of arr["<<i<<"]: "; cin>>arr[i]; } cout<<"\nThe Original Array: \t"; for(int i = 0; i < 5 ; i++) cout<<arr[i]<<" "; // Applying "Selection Sort" Algorithm for(int i = 0 ; i < 5 ; i++) for(int j = i + 1 ; j < 5 ; j++) { if(arr[i] > arr[j]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // end of inner for-loop cout<<"\n\nAfter Applying \"Selection Sort\" Algorithm:"<<endl; cout<<"The Sorted Array: \t"; for(int i = 0; i < 5 ; i++) cout<<arr[i]<<" "; getch(); } CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 17 Enter value of arr[0]: 87 Enter value of arr[1]: 21 Enter value of arr[2]: 25 Enter value of arr[3]: 1 Enter value of arr[4]: 49 The Original Array: 87 21 25 1 49 After Applying "Selection Sort" Algorithm: The Sorted Array: 1 21 25 49 87 Press any key to continue...

18 Sorting Techniques / Algorithms Bubble Sort Bubble Sort is also known as Exchange Sort. It repeatedly visits the entire array and compares two items at a time. It swaps these two items if they are in the wrong order. It continues to visit the array until no swaps are needed that means the array is sorted. Bubble sort in context of ascending sort works as follows: 1.Compare adjacent elements, if the first is greater than the second, swap them. 2.Repeat this for each pair of adjacent elements, starting with the first two and ending with the last two. At this point the last element should be the greatest. 3.Repeat the steps for all elements except the last one. 4.Keep repeating for one fewer elements each time until there are no pairs to compare. CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 18

19 Sorting Techniques / Algorithms Implementation of Bubble Sort Write a program that stores five values in an array. It sorts the array using bubble sort. It also displays the values of unsorted and sorted array. #include void main() { int arr[5]; for(int i = 0 ; i < 5 ; i++) { cout<<"Enter arr["<<i<<"]: "; cin>>arr[i]; } cout<<"The original values in array:\n"; for( int i = 0 ; i < 5; i++) cout<<arr[i]<<" "; for(int y = 0 ; y < 5; y++) { for ( int k = 0; k < 5 - 1 - y ; k++ ) if(arr[k] > arr[k+1]) { int temp = arr[k+1]; arr[k+1] = arr[k]; arr[k] = temp; } cout<<"\nThe sorted array:\n"; for(int i=0; i<5; i++) cout<<arr[i]<<" "; cout << endl; } CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 19 Enter arr[0]: 6 Enter arr[1]: 1 Enter arr[2]: 7 Enter arr[3]: 5 Enter arr[4]: 2 The original values in array: 6 1 7 5 2 The sorted array: 1 2 5 6 7 Press any key to continue...

20 Two Dimensional Arrays Two-dimensional array can be considered as a table that consists of rows and column. Each element in 2-D array is referred with the help of two indexes. One index is used to indicate the row and the second index indicates the column of the element. Syntax datatype identifier[rows][cols]; Example # 1 int arr[4][3]; An integer array with 4 rows & 3 columns Example # 2 double d_array[2][5]; An array with 2 rows & 5 columns of double data type Example # 3 char cityNames[5][15]; An array with 5 rows & 15 columns to store strings CONTENTS Arrays Searching in Arrays Sorting Arrays Two Dimensional Arrays Multi-Dimensional Arrays 20 2D012 0 1 2 3 01234 0 1 01234567891011121314 0 1 2 3 4 arr[2][0] cityName[2][7]

21 Two Dimensional Arrays Accessing individual Elements T o access the individual element of two dimensional array we need: 1.Array name 2.Row 3.Column For example, the following statement arr[0][1] = 100; will store 100 in the 2 nd column of 1 st row in the 2-D Array namely arr. The index for row or column of 2-D array can be given using variables. The following example will work similar to the line above: r = 0; c = 1; arr[r][c] = 100; CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 21

22 Two Dimensional Arrays Populating 2D Arrays Programmer can enter data in any element of the array by using the name of array and indexes of the element. For example, the following statements stores data in the first row of a 2-D array: arr[0][0] = 10 // 10 stored in 1 st column of 1 st row. arr[0][1] = 20 // 20 stored in 2 nd column of 1 st row. arr[0][2] = 30 // 30 stored in 3 rd column of 1 st row. The following statements stores data in the second row arr[1][0] = 40 // 40 stored in 1 st column of 2 nd row. arr[1][1] = 50 // 50 stored in 2 nd column of 2 nd row. arr[1][2] = 60 // 60 stored in 3 rd column of 2 nd row. The nested loops are frequently used to enter data in 2-D array. The outer loops are normally used to refer to the rows in array. Similarly, the inner loops are normally used to refer to the columns of the rows. CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 22

23 Entering Data in 2-D Arrays (Program Example) Write a program which stores marks against ID of 5 students using 2D Array. #include int main() { const int ROWS = 5; const int COLS = 2; int student_data[ROWS][COLS]; for(int row = 0; row < ROWS; row++) { cout << "Enter Student "<<row + 1<<"'s ID: "; cin>>student_data[row][0]; // ID cout << "Enter Student "<<row + 1<<"'s Marks: "; cin>>student_data[row][1]; // Marks cout << endl; } cout << "\nYou entered the following information" <<endl; cout <<"\nStudent ID"<<setw(20)<<"Student Marks"<<endl; cout<<"------------------------------"<<endl; for(int row = 0; row < ROWS; row++) { cout<<setw(10)<<student_data[row][0]; cout<<setw(20)<<student_data[row][1]<<endl; } return 0; } CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 23 Enter Student 1's ID: 101 Enter Student 1's Marks: 89 Enter Student 2's ID: 102 Enter Student 2's Marks: 75 You entered the following information Student ID Student Marks ------------------------------ 101 89 101 89 102 75 102 75 Press any key to continue... Press any key to continue...

24 Initializing 2-D Arrays The two dimensional arrays can also be initialized at the time of declaration. The process of initialization is performed by assigning the initial values in braces separated by commas. The values of each row can further be assigned in nested braces. Some important points to initialize 2-D arrays are as follows: o The elements of each row are enclosed within braces and separated by commas. o All rows are enclosed within the braces. o For number arrays, if the values for all elements are not specified, the unspecified elements are initialized by zero. In this case, at least one value must be given. o Examples are as follows: int arr[3][4) = {{12, 5, 22, 84}, {95,3,41,59}, { 77, 6, 53, 62} }; o OR int arr[3][4) = {{12, 5, 22, 84}, {95,3,41,59} {77, 6, 53, 62} }; The initialization can also be performed without using the inner braces as follows: Example: int arr[3][4]={12, 5, 22, 84, 95, 3,41, 59, 77, 6, 53, 62 }; CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 24

25 Initializing 2-D Arrays (Program example) Write a program that initializes a two dimensional array of two rows and three columnsand then displays its values. #include void main() { int i, j, arr[2][3] = {15,21,9,84,33,72}; for(i=0; i<2; i++) { for(j=0; j<3;j++) cout<<"arr["<<i<<"]["<<j<<"] = "<<arr[i][j]<<"\t"<<endl; } return 0; } OUTPUT: arr[0][0] = 15 arr[0][1] = 21 arr[0][2] = 9 arr[1][0] = 84 arr[1][1] = 33 arr[1][2] = 72 Press any key to continue... CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays 25

26 Multidimensional Arrays Multidimensional array is also called as array of arrays. Multidimensional arrays are not limited to two indices, instead may have three, four or more dimensions. The amount of memory needed for an array rapidly increases with each dimension. Syntax DataType arrayName[a] [b]......[n]; a, b, and n are constant expression indicating the length of different dimensions of the array. Example int arr[10][5][7]; The above statement declares a three-dimensional array arr. The first element in the array is designated as arr[0][0][0] and the last element as arr[9] [4] [6]. The total numbers of elements in the array is 10 *5 * 7 = 350 26 CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays

27 Accessing Multidimensional Arrays Syntax arrayname[a][b]...... [n]; a, b and n are expressions indicating the values of different dimensions of the array. Example arr[0][0][0] = 10; arr[0][0][1] = 10; arr[0][0][2] = 10;... arr[9][4][0] = 10; The above statements access the individual elements of three dimensional array and store integer values in them. The nested loops are frequently used to enter data in multidimensional array. 27 CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays

28 Multidimensional Arrays (Program Example) #include void main() { int i, j, k, max, min, tot = 0; float avg; int temp[3][7][4]; for( i = 0; i < 3; i++) for(j=0; j<7; j++) for(k=0; k<4; k++) { cout<<"Enter Temperature: "; cin>>temp[i][j][k]; } max = min = temp[0][0][0]; for(i=0; i<3; i++) for(j=0; j<7; j++) for(k=0; k<4; k++) { tot = tot + temp[i][j][k]; if(temp[i][j][k] > max) max = temp[i][j][k]; if(temp[i][j][k] < min) min = temp[i][j][k]; } avg = (float)tot/(3*7*4); cout<<"Maximum temperature of month: "<<max<<endl; cout<<"Minimum temperature of month: "<<min<<endl; cout<<"Average temperature of month; "<<avg<<endl; } 28 CONTENTS Arrays Searching in Arrays Sorting Arrays Two-Dimensional Arrays Multidimensional Arrays


Download ppt "Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR www.msc-it-m.wapka.mobi/index.xhtml."

Similar presentations


Ads by Google