0% found this document useful (0 votes)
52 views10 pages

Itp Lab 10

The document discusses multi-dimensional arrays in C++. It defines what multi-dimensional arrays are, how to declare and initialize two-dimensional arrays, and how to access elements within two-dimensional arrays using indices. Examples of declaring, initializing, and accessing two-dimensional arrays are provided.

Uploaded by

Sahab
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)
52 views10 pages

Itp Lab 10

The document discusses multi-dimensional arrays in C++. It defines what multi-dimensional arrays are, how to declare and initialize two-dimensional arrays, and how to access elements within two-dimensional arrays using indices. Examples of declaring, initializing, and accessing two-dimensional arrays are provided.

Uploaded by

Sahab
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/ 10

DEPARTMENT OF TELECOMMUNICATION ENGINEERING

MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO


INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 10
ST

________________________________________________________________________
Name: _____________________________________________ Roll No: _____________

Score: ____________Signature of the Lab Tutor: _____________ Date: 07/02/2018


________________________________________________________________________

To Familiarize with Multi-Dimensional Arrays in C++

PERFORMANCE OBJECTIVE

Upon successful completion of this experiment, the student will be able to:

• To be able to declare a two-dimensional array.


• To be able to perform fundamental operations on a two-dimensional array.
• To be able to pass two-dimensional arrays as parameters.
• To be able to view a two-dimensional array as an array of arrays

Definitions:

An array is a collection of elements, all of the same type, that are stored in consecutive memory
locations. The type of each element in an array can be a simple type, such as a char or an integer
or double, or a more complex type such as objects of type String or a user-defined type such as
Time or Product (such as a product in a grocery store). Individual elements of an array are
accessed using an index or subscript. So far, we have only used one-dimensional arrays. A one-
dimensional array can be visualized as a linear list of elements, with each element accessed by a
single index.

Multi-dimensional arrays, like one-dimensional arrays, contain elements all of the same type and
are stored in memory in consecutive locations. However, a multi-dimensional array requires more
than one index to access an individual element. A two-dimensional array can be visualized as a
table with rows and columns OR as an array of arrays (a list of one-dimensional arrays (rows)!).
To access an individual element one needs to specify both a row index and a column index.
Three-dimensional arrays require 3 indices; 4-dimensional arrays require 4 indices, and so on.

Declaring Arrays

C++ allows multidimensional arrays. Here is the general form of a multidimensional array
declaration:

type name[size1][size2]...[sizeN];

For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:

int threedim[5][10][4];
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 10
ST

________________________________________________________________________
Two-Dimensional Arrays

The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array
of size x,y, you would write something as follows:

type arrayName [ x ][ y ];

Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.

A two-dimensional array can be think as a table, which will have x number of rows and y number
of columns. A 2-dimensional array a, which contains three rows and four columns can be shown
as below:

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is
the name of the array, and i and j are the subscripts that uniquely identify each element in a.

Initializing Two-Dimensional Arrays

Multidimensioned arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row have 4 columns.

int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};


DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 10
ST

________________________________________________________________________
Accessing Two-Dimensional Array Elements

An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example:

int val = a[2][3];

The above statement will take 4th element from the 3rd row of the array. You can verify it in the
above digram.

#include <iostream>
using namespace std;

int main () {
// 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 << "]: ";
cout << a[i][j]<< endl;
}

return 0;
}

When the above code is compiled and executed, it produces the following result:

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 10
ST

________________________________________________________________________
As explained above, you can have arrays with any number of dimensions, although it is likely
that most of the arrays you create will be of one or two dimensions.

To declare a multidimensional array, one must specify the type of the elements, and the number
of elements in each dimension (for example, in a two-dimensional array the number of elements
in each row and each column). Some examples:

double hourlyTemp[31][24]; //array to store the hourly temperature for


//each hour in each day of a month – the row represents the day of the month, the
//column the hour of the day
double tempTable[12][31][24]; //array to store the hourly temperature for
//each hour in each day for every day of a year. The first index represents the month,
//the second the day, and the third the year.

int bitMap[240][320]; //array to store a color code for each pixel in a graphics image that is
//240 rows by 320 columns
Time split[10][3]; //array of objects of type Time (from earlier labs) -- first index represents
//different races, the second the three splits in a 5K race

Accessing Elements (Components) of An Array


As with one-dimensional arrays, C++ indexes each dimension beginning with 0. In the above
examples, hourlyTemp[2][22] would refer to the value in the row with index 2 (physically the third
row) and column index 22 (the 23rd column) -- that is, it would be the temperature on the 3rd day
of the month at 11pm. bitMap[100][230] would refer to the pixel in position (100,230) on a
graphics image. The three-dimensional array tempTable can be thought of as an array of two-
dimensional arrays. In this example, each two-dimensional array is an array of hourly
temperatures for a month. Hence, tempTable[3] is the temperature table for the month with index
3 (that would be the 4th month -- April); tempTable[3][4][8] would represent the temperature in
April, on the day with index 4 (so the 5th) at the hour with index 8 (that would be 9am) -- hence, it
represents the temperature at 9am on April 5.

Consider the array declared as follows:

int grade[5][4];
//The row indices go from 0 to 4; the column indices go from 0 to 3. The //following code would
read numbers into the array:
for (int row = 0; row < 5; row++)
for (int col = 0; col < 4; col++)
cin >> grade[row][col];
The filled array can be visualized as follows:

row 0 = grade[0] 75 79 85 62
row 1 = grade[1] 79 76 55 99
row 2 = grade[2] 98 35 77 81
row 3 = grade[3] 63 95 78 60
row 4 = grade[4] 88 92 88 91
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 10
ST

________________________________________________________________________
The element grade[1][2] is the number in row 1, column 2 which is 55. The element grade [4][3] is
the number in row 4, column 3 which is 91.

How Arrays Are Stored


Multi-dimensional arrays must be stored in the linear memory of the computer. C++ stores multi-
dimensional arrays in row major order. For a two-dimensional array that means that the first row
of the array (the one with index 0) is stored first, followed by the second row and so on. The
above array would be stored as follows:

75
Row
0 79
85
62

79
76
Row 1
55
99

98
35
Row 2
77
81

63
95
Row 3
78
60

88
92
Row 4
88
91

Processing a Two-Dimensional Array


To "do something" to every element of a two dimensional array, nested for loops come in handy
(assuming you know how many rows and columns are in the array). For example,
if numRows and numColshave been defined and contain the number of rows and columns,
respectively, in a two-dimensional array salary, the following code, increases each entry in the
array by 5%:
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 10
ST

________________________________________________________________________
for (int row = 0; row < numRows; row++)
for (int col = 0; col < numCols; col++)
salary[row][col] = 1.05 * salary[row][col];

Often it is convenient to use the fact that a two-dimensional array is an array of one-dimensional
arrays. For example, suppose you have a function that does a sequential search of a one-
dimensional array. Assume it takes the array, the target, and the number of elements in the array
as parameters, and returns either -1 (if it doesn't find the target) or the index of the target.
Assume the declaration (prototype or profile) is as follows:

int seqSearch(int a[], int target, int numElems);


The following segment of code could be used to search a two dimensional array twoDArray for
the target lookFor. Assume the number of elements in each row of twoDArray (which is the
number of columns in the array) is stored in the variable numCols and the
variable numRows contains the number of rows in the array.
Assume twoDArray, lookFor, numRows and numCols have all been defined.

int colIndex = -1; //initialize colIndex to "not found"


int rowNum = 0; //initialize the row number to 0

while (rowNum < numRows && colIndex == -1)


{
// call seqSearch to search row rowNum of the array
colIndex = seqSearch(twoDArray[rowNum], lookFor, numCols);
rowNum++;
}
if (colIndex != -1)
{
cout << lookFor << " was found in row " << rowNum - 1;
cout << ", column " << colIndex << endl;
}
else
cout << lookFor << " was not found." << endl;

To process a single row of a two-dimensional array generally you need just one for loop. For
example, to "do something" to row i of the two-dimensional array twoDArray you would have a
loop similar to the following:

for (int j = 0; j < numCols; j++)


{
do whatever to element twoDArray[i][]j]
}
Note in the above that the number of elements in a row is equal to the number of columns in the
matrix.

To process a two-dimensional array of objects, one generally must use the accessor functions to
access the data members of the object one wants to process. Recall that the Time class had a
function showTime() that printed the time. To print the times in the split array defined above, one
could use the following segment of code:

int i, j; //array indices


for (i = 0; i < 10; i++)
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 10
ST

________________________________________________________________________
{
for (j = 0; j < 3; j++)
split[i][j].showTime();
cout << endl;
}

Two-Dimensional Arrays as Parameters to Functions


To pass a two-dimensional array to a function generally one uses pointers (a pointer is
an address of a variable, in the case of arrays one would use the address of the first element in
the array), a topic not covered in CPSC 150. To pass the array without pointers the declaration of
the formal parameter to the function MUST specify the number of columns in the array. For
example,
void someFunction (int twoDArray[][10], int numRows);
An array that is passed to this function MUST have been declared to have 10 columns, even if all
of them are not used. As with one-dimensional arrays the actual parameter is just the name of the
array. So, the following would be a legal call to the function above:
int a[4][10];

someFunction(a, 4);

Passing Multi-dimensional Arrays as Function Parameters

In C++, arrays are always passed by reference. Whenever an array is passed as a parameter, its
base address is sent to the called function.

Generally, functions that work with arrays require 2 items of information as actual parameters: the
beginning address of the array (in memory), and the number of elements to process in the
array. When passing multi-dimensional arrays as function parameters, all subscripts except the
first must contain a value of the size of that particular index.

Below is an example of the function that prints a 2-dimensional array. (Note: The second
subscript has a value.)

For example (Function PrintArray):

void PrintArray(const int Array[][10], int ArraySize)


{
for (int row = 0; row <= ArraySize - 1; row++) {
for (int col = 0; col <= 9; col++) {
cout << "array[" << row << "][" << col << "] = ";
<< Array[row][col] << endl;
}
cout << endl;
}
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 10
ST

________________________________________________________________________
Lab Assignment:
1) For both problems, turn in the program listing and the output. Include the standard
header in each program.
a. Complete and run the following program.

// strstuff.cpp
#include <iostream>
#include <string>

using namespace std;

void print_forward(string s);


void print_reverse(string s);

int main()
{
string sentence, first, last;

cout << "Enter your first name: ";


cin >> first;

cout << "Enter your last name: ";


cin >> last;

sentence = "Your whole name is ";


sentence += first + " " + last + ".";

cout << endl


<< "This sentence was created by used string concatenation:"
<< endl
<< sentence << endl;

for (int i = 0; i <= sentence.length() - 1; i++)


sentence[i] = toupper(sentence[i]);

cout << endl


<< "This is the same sentence printed in upper case letters:"
<< endl
<< sentence << endl << endl;

cout << "The length of this sentence is " << sentence.length() << '.'
<< endl;

cout << endl


<<"This is the sentence printed one character at time." << endl;
print_forward(sentence);
cout << endl;

cout << endl


<<"This is the sentence printed backwards." << endl;
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 10
ST

________________________________________________________________________
print_reverse(sentence);
cout << endl;

return 0;

void print_forward(string s)
{
for (int i = 0; i <= s.length(); i++)
cout << s[i];
cout << endl;
}

void print_reverse(string s)
{
// Complete the code
}

b) Complete and run the following program. This program creates and prints the
multiplication table for 0 to 9.

//mtable.cpp
#include <iostream>
#include <iomanip>

using namespace std;

const int MAX = 10;

void create_table(int table[][MAX], int size);


void print_table(const int table[][MAX], int size);

int main()
{
int mtable[MAX][MAX];

create_table(mtable, MAX);
print_table(mtable, MAX);

return 0;
}

void create_table(int table[][MAX], int size)


{
for (int row = 0; row <= size - 1; row++)
for (int col = 0; col <= size -1; col++)
table[row][col] = row * col;
}
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 10
ST

________________________________________________________________________

void print_table(const int table[][MAX], int size)


{
// Complete the code
}

2) Write the general format of a loop to process the elements in column j of a two-
dimensional array.
3) Compile all the programs into C++ compiler and study the working of Multi-
dimensional arrays.

You might also like