0% found this document useful (0 votes)
8 views

Lecture_3 Array - part2

array inplc

Uploaded by

Ahmed Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture_3 Array - part2

array inplc

Uploaded by

Ahmed Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Computer Programming

Lecture 3
Multidimensional Arrays
Introduction
you have used one-dimensional arrays to model linear
collections of elements.
You can use a two-dimensional array to represent a
matrix or a table.
For example, the following table that describes the
distances between the cities can be represented using a
two-dimensional array.

Aden Ataq Mukalla


Aden 0 352 810
Ataq 352 0 280
Mukalla 810 280 0
Distance Table (in Km)
3.2
Two-dimensional array
Two-dimensional Array: a collection of a fixed number of
components arranged in two dimensions
The syntax for declaring a two-dimensional array is:

dataType arrayName[intexp1][intexp2];

where intexp1 and intexp2 are expressions yielding positive


integer values
Here is a two-dimensional array containing 3 rows and 4:

3.3
Initialization of two-dimensional array

we can initialize a multidimensional array in more than


one way.
Initialization of two-dimensional array

int x[2][3] = {2, 4, 5, 9, 0, 19};

The above method is not preferred. A better way to


initialize this array with the same array elements is given
below:
int x[2][3] = { {2, 4, 5},
{9, 0, 19}
};
Column 0 Column 1 Column 2
Row 0 2 4 5
Row 1 9 0 19
3.4
Accessing Two-Dimensional Array Elements

An element in two-dimensional array is accessed by


using the subscripts, i.e., row index and column index of
the array.
For example:

int Array[3][7];

Array[3][7]

3 rows 7 Columns

3.5
Accessing Two-Dimensional Array Elements

Caution

• It is a common mistake to use matrix[2,1] to access the


element at row 2 and column 1.
• In C++, each subscript must be enclosed in a pair of square
brackets, for example matrix[2][1];

3.6
Processing a 2-D Array
A one-dimensional array is usually processed via a for
loop. Similarly, a two-dimensional array may be processed
with nested for loops:
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

// output each array element's value


for ( int i = 0; i < 5; i++ )
{
for ( int j = 0; j < 2; j++ )
cout << a[i][j] << " "; 0 0
cout <<endl; 1 2
} 2 4
3 6
4 8

output
3.7
Example: Taking Input for Two Dimensional Array
#include <iostream>
using namespace std;
We have used a nested
for loop to take the
int main() { input of the 2d array.
int numbers[2][3];
Once all the input has
cout << "Enter 6 numbers: " << endl; been taken, we have
used another nested
// Storing user input in the array
for (int i = 0; i < 2; ++i) { for loop to print the
for (int j = 0; j < 3; ++j) { array members.
cin >> numbers[i][j];
}
} Enter 6 numbers:
1
cout << "The numbers are: " << endl; 2
3
// Printing array elements 4
for (int i = 0; i < 2; ++i) { 5
for (int j = 0; j < 3; ++j) { 6
cout << "numbers[" << i << "][" << j << "]: The numbers are:
" << numbers[i][j] << endl; numbers[0][0]: 1
}
numbers[0][1]: 2
}
cin.get();
numbers[0][2]: 3
return 0;} numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6
3.8
Example: Sum by Row 0 0 0
The following for loop finds the sum of each row of a 1 1 1
matrix. 2 2 2
3 3 3
#include <iostream>
using namespace std; 4 4 4

int main() { matrix[5][3]


int sum;
// an array with 5 rows and 3 columns.
int matrix[5][3] = { {0,0,0}, {1,1,1}, {2,2,2}, {3,3,3},{4,4,4}};
for (int row = 0; row < 5; row++)
{
sum = 0;
for (int col = 0; col < 3; col++)
sum = sum + matrix[row][col];
cout << "Sum of row " << row + 1 << " = " << sum << endl;
}
cin.get(); Sum of row 1 = 0
return 0; Sum of row 2 = 3
} Sum of row 3 = 6
Sum of row 4 = 9
Sum of row 5 = 12

The output 3.9


Sum by Column?

0 0 0
1 1 1
Assignment 1 2 2 2
3 3 3
4 4 4

Save the file as (sum_by_column.cpp)

3.10
Example: Largest element in each row 0 1 3
The following C++ code determines the largest element in 4 7 3
each row of the matrix 5 9 8
#include <iostream> 9 6 2
using namespace std; 7 3 1
int main() {
int largest; matrix[5][3]
// an array with 5 rows and 3 columns.
int matrix[5][3] = { {0,1,3}, {4,7,3}, {5,9,8}, {9,6,2},{7,3,1}};
for (int row = 0; row < 5; row++)
{
largest = matrix[row][0]; //Assume that the first element
//of the row is the largest.
for (int col = 1; col < 3; col++)
if (matrix[row][col] > largest)
largest = matrix[row][col];
cout << "The largest element in row " << row + 1 << " = "<<
largest << endl;
}
The largest element in row 1 = 3
cin.get(); The largest element in row 2 = 7
return 0; The largest element in row 3 = 9
}
The largest element in row 4 = 9
The largest element in row 5 = 7
3.11
Largest element in each column?

0 1 3
4 7 3
Assignment 2 5 9 8
9 6 2
7 3 1
Save the file as (Largest_clm.cpp)
matrix[5][3]

3.12
Higher-Dimensional Arrays
An array can be declared with multiple dimensions.

3.13
Initializing Three-Dimensional Array
Initialization in Three-Dimensional array is same as that of
Two-dimensional arrays. The difference is as the number of
dimension increases so the number of nested braces will also
increase.
Method 1:
int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 1, 1,
3, 4, 5, 6, 6, 6, 6, 9, 9, 9, 9};
4 columns
Better Method:
int x[2][3][4] =

3 rows
Array 1
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,1,1} },
{ {1,3,4,5}, {6,6,6,6}, {9,9,9,9} }
Array 2
};

x[2][3][4]

2 Arrays 4 Columns
3 Rows 3.14
Initializing Three-Dimensional Array

You can use loops to process multidimensional arrays.


For example, the nested for loops:

int x[10][5][7];

for (int i = 0; i < 10; i++)


for (int j = 0; j < 5; j++)
for (int k = 0; k < 7; k++)
x[i][j][k] = 0;

3.15
Processing a 3-D Array
• Following is a simple C++ program to initialize three-dimensional
(3D) array of dimensions 2*3*4, then it will access some
elements present in the array and display the element on the
screen :

int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,


14, 15, 16, 17, 18, 19, 20, 21, 22, 23};

for ( int i = 0; i < 2; i++ )


{
for ( int j = 0; j < 3; j++ )
{
for (int k=0; k<4; k++)
0 1 2 3
cout << x[i][j][k] << "\t";
4 5 6 7
cout <<endl;
8 9 10 11
}
cout <<endl;
12 13 14 15
}
16 17 18 19
20 21 22 23
output 3.16
Searching Arrays with Linear Search

It may be necessary to determine whether an array


contains a value that matches a certain key value.
The process of finding a particular element of an array is
called searching
The linear search compares each element of an array
with a search key .Because the array is not in any
particular order.

3.17
Two-Dimensional Array Manipulation
3x3 arrays' subscripts and
The following example prints the 3 x 3 array’s their respective elements
subscript and their element. --------------------------
[0][0]=10
#include <iostream> [0][1]=25
using namespace std; [0][2]=33
int main() [1][0]=21
{ [1][1]=32
int i, j; [1][2]=43
int x[3][3]={{10,25,33}, [2][0]=20
{21,32,43},{20,42,51}}; [2][1]=42
cout<<"\n3x3 arrays' subscripts and\n"; [2][2]=51
cout<<"their respective elements\n";
cout<<"--------------------------\n";
// the outer for loop, reading the row by row...
for(i=0; i<3; i++)
// the inner loop,read every column by column...
for(j=0; j<3; j++)

cout<<"["<<i<<"]"<<"["<<j<<"]"<<"="<<x[i][j]<<"\n";
system("pause");
return 0;
}

3.18
Example1 - Array Size

#include <iostream>
#include <string>
using namespace std;

int main() {
// Declare Array Variable
int array[5]= { 18, 24, 23, 34, 15 };

int size;

size = sizeof(array)/sizeof(int);

//Print size of Array


cout<<"The Size of Array is "<<size <<endl;
system("pause");
return 0;
}
The Size of Array is 5

Output
3.19
EXERCISE 1
Identify error(s), if any, in the following array declarations.
If a statement is incorrect, provide the correct statement.
a. int primeNum[99];

b. int testScores[0];

c. string names[60];

d. int list100[0..99];

e. double[50] gpa;

f. const double LENGTH = 26;


double list[LENGTH - 1];

g. const long SIZE = 100;


int list[2 * SIZE];

3.20
EXERCISE 2
What is the output of the following program segment?
double list[5];
for (int i = 0; i < 5; i++)
list[i] = pow(i, 3) + i / 2.0;
cout << fixed << showpoint << setprecision(2);

for (int i = 0; i < 5; i++)


cout << list[i] << " ";

cout << endl;


list[0] = list[4] - list[2];
list[2] = list[3] + list[1];
for (int i = 0; i < 5; i++)
cout << list[i] << " ";
cout << endl;

3.21
EXERCISE 3
What is stored in list after the following C++ code executes?

int list[8];
list[0] = 1;
list[1] = 2;

for (int i = 2; i < 8; i++)


{
list[i] = list[i – 1] * list[i – 2];
if (i > 5)
list[i] = list[i] - list[i - 1];
}

list ? ? ? ? ? ? ? ?

3.22
EXERCISE 4
Determine whether the following array declarations are
valid. If a declaration is invalid, explain why.
a. int list[61];

b. strings names[20];

c. double gpa[];

d. double[-50] ratings[];

e. string flowers[35];

f. int SIZE = 10;


double sales[2 * SIZE];

g. int MAX_SIZE = 50;


double sales[100 - 2 * MAX_SIZE];

3.23
Assignment 1
uses a two-dimensional array grades to store the grades of a number of
students on multiple exams. ( use 10x3 array)
Show two-dimensional array in a tabular format, along with each student's
semester average.
Show Highest/Lowest grade of any student for the semester.
Show a bar chart of the distribution of all student grades for the semester.
Example of output:
The grades are:
Test 1 Test 2 Test 3 Overall grade distribution:
Average 0-9:
Student 1 87 96 70 84.33 10-19:
Student 2 68 87 90 81.67
20-29:
Student 3 94 100 90 94.67
Student 4 100 81 82 87.67 30-39:
Student 5 83 65 85 77.67 40-49:
Student 6 78 87 65 76.67 50-59:
Student 7 85 75 83 81.00 60-69: ***
Student 8 91 94 100 95.00 70-79: ******
Student 9 76 72 84 77.33
80-89: ***********
Student 10 87 93 73 84.33
90-99: *******
Lowest grade in the grade book is 65 100: ***
Highest grade in the grade book is 100

(Save the file as grades.cpp) 3.24


Assignment 2

Sorting an array containing 0’s, 1’s and 2’s


Given an array A[] consisting 0s, 1s and 2s, write a program that
sorts A[]. The program should put all 0s first, then all 1s and all 2s in
last.

Example a[] = {1,0,2,1,2,1,1,1,2,1,0}


After sorting: {0,0,1,1,1,1,1,1,2,2,2}

Save the file as (sorting012.cpp)

3.25
Bonus Assignment (+2)
Write a program to solve N-Queens puzzle problem by generating random
solutions. The program will stop when a correct solution is found.
Represent the generated solution using NxN matrix as shown in the
example below.

4-Queens puzzle & 4x4 matrix


(Save the file as N-Queens.cpp)
3.26

You might also like