arrays in c++ university of the punjab (gujranwala campus) 1 adnan babar mt14028 cr

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

Upload: christopher-short

Post on 29-Dec-2015

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

1

Arrays in C++

U N I V E R S I T Y O F T H E P U N J A B( G U J R A N W A L A C A M P U S )

ADNAN BABARMT14028CR

www.msc-it-m.wapka.mobi/index.xhtml

Page 2: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

2

ObjectivesThe contents we are going to cover in this chapter:

Concept of Arrays

Searching in Arrays

Sorting Arrays

Two-Dimensional Arrays

Multidimensional Arrays

Page 3: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

3

ArraysIntroduction

• 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 0o 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

arr0 1 2 3 4 5 6 7 8 9

12 45 0 26 14 14 20 47 5 5

Page 4: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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

Page 5: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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] ;

• Exampleint 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

marks

marks[0] marks[1] marks[2] marks[3] marks[4]

Page 6: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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

marks70 54 82 96 49

marks[0] marks[1] marks[2] marks[3] marks[4]

Page 7: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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 – ArrayName[Index]; • Example Code Snippet

#include <iostream.h>#include <conio.h>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

Page 8: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

8

Accessing Array Elements using LoopsUse 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 elementsmarks[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

Page 9: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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

Comparison#include <iostream.h>#include <conio.h>int main(){

int marks[100];marks[0] = 75 ;marks[1] = 67 ;marks[2] = 52 ;……………marks[99] = 85 ;return 0;

}

#include <iostream.h>#include <conio.h>int main(){

int marks[100];for(int i=0;i<100;i++)

marks[i] = 1 + rand() % 100;return 0;

}

// Program Completes with few lines

Page 10: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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 <iostream.h>#include <conio.h>#include <stdio.h>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

Enter five integers:784125165

The values in the array: 78, 41, 25, 1, 65

Page 11: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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 Searcho 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

Page 12: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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 <iostream.h>#include <conio.h>int main(){

// initializing an array of integersint 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 locationcout << "Value not found in the array!!!"

<< endl;else

cout << "Value Found in the array at index: "<< location << endl;

return 0;}

CONTENTS

Arrays

Searching in Arrays

Sorting Arrays

Two-Dimensional

Arrays

Multidimensional

Arrays

Enter value to find: 80Value Found in the array at index: 7Press any key to continue . . .

Page 13: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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

Page 14: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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 <iostream.h>#include <conio.h>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 Arrayend = 9; // ending index of the Arraycout<<"Enter an integer (10 ~ 100) to Find: ";cin>>toFind;while( start <= end ){

mid = (start + end)/ 2; // mid of Arrayif(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

Enter an integer (10 ~ 100) to Find: 9090 found at index 8Press any key to continue . . .

Enter an integer (10 ~ 100) to Find: 4040 found at index 3Press any key to continue . . .

Enter an integer (10 ~ 100) to Find: 5151 not foundPress any key to continue . . .

Page 15: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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 Ascendingo Descending

• Ascending Ordero 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 Ordero 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

Page 16: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

16

Sorting Techniques / AlgorithmsSelection 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

Page 17: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

17

Sorting Techniques / AlgorithmsImplementation 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 <iostream.h>#include <conio.h>#include <stdio.h>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" Algorithmfor(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

Enter value of arr[0]: 87Enter value of arr[1]: 21Enter value of arr[2]: 25Enter value of arr[3]: 1Enter 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 87Press any key to continue . . .

Page 18: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

18

Sorting Techniques / AlgorithmsBubble 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

Page 19: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

19

Sorting Techniques / AlgorithmsImplementation 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 <iostream.h>#include <conio.h>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

Enter arr[0]: 6Enter arr[1]: 1Enter arr[2]: 7Enter arr[3]: 5Enter arr[4]: 2The original values in array:6 1 7 5 2The sorted array:1 2 5 6 7Press any key to continue . . .

Page 20: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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

2D 0 1 2

0

1

2

3

2D 0 1 2 3 4

0

1

2D 0 1 2 3 4 5 6 7 8 9 10 11 12 13 140 1 2 3 4

arr[2][0]

cityName[2][7]

Page 21: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

21

Two Dimensional ArraysAccessing individual Elements

• To access the individual element of two dimensional array we need:1. Array name2. Row3. Column

• For example, the following statement arr[0][1] = 100; will store 100 in the 2nd column of 1st 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

Page 22: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

22

Two Dimensional ArraysPopulating 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 1st column of 1st row.arr[0][1] = 20 // 20 stored in 2nd column of 1st row.arr[0][2] = 30 // 30 stored in 3rd column of 1st row.

• The following statements stores data in the second rowarr[1][0] = 40 // 40 stored in 1st column of 2nd row.arr[1][1] = 50 // 50 stored in 2nd column of 2nd row.arr[1][2] = 60 // 60 stored in 3rd column of 2nd 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

Page 23: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

23

Entering Data in 2-D Arrays (Program Example)Write a program which stores marks against ID of 5 students using 2D Array.

#include <iostream.h>#include <conio.h>#include <iomanip.h>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]; // IDcout << "Enter Student "<<row + 1<<"'s Marks: ";cin>>student_data[row][1]; // Markscout << 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

Enter Student 1's ID: 101Enter Student 1's Marks: 89

Enter Student 2's ID: 102Enter Student 2's Marks: 75

You entered the following information

Student ID Student Marks------------------------------ 101 89 102 75 Press any key to continue . . .

Page 24: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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

Page 25: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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<iostream.h>#include <conio.h>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] = 15arr[0][1] = 21arr[0][2] = 9arr[1][0] = 84arr[1][1] = 33arr[1][2] = 72Press any key to continue . . .

CONTENTS

Arrays

Searching in Arrays

Sorting Arrays

Two-Dimensional

Arrays

Multidimensional

Arrays

Page 26: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

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.

SyntaxDataType arrayName[a] [b]......[n];

• a, b, and n are constant expression indicating the length of different dimensions of the array.

Exampleint 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

CONTENTS

Arrays

Searching in Arrays

Sorting Arrays

Two-Dimensional

Arrays

Multidimensional

Arrays

Page 27: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

27

Accessing Multidimensional Arrays

Syntaxarrayname[a][b] ...... [n];

 • a, b and n are expressions indicating the values of different

dimensions of the array.

Examplearr[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.

CONTENTS

Arrays

Searching in Arrays

Sorting Arrays

Two-Dimensional

Arrays

Multidimensional

Arrays

Page 28: Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR

28

Multidimensional Arrays (Program Example)#include <iostream.h>#include<conio.h>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;}

CONTENTS

Arrays

Searching in Arrays

Sorting Arrays

Two-Dimensional

Arrays

Multidimensional

Arrays