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

Topic 3 Arrays

Uploaded by

fain22776
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Topic 3 Arrays

Uploaded by

fain22776
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

Topic 3

Arrays
Introduction to Array
• An array is a collection of data values.
• A single array can store a large number of
values during the execution of a program.
• An array stores multiple values of the
same type.
• An element in an array can be assessed
using an index.
Declaring Arrays
• Array Declaration

<data type> <variable>[ ]

• Examples
i. float marks[10];
ii. const int SIZE =50;
double number[SIZE];
iii. double myList[100];
Declaring Arrays(cont.)
float marks[10]; float myList[100];

marks[0] myList[0]

marks[1] myList[1]
Element
marks[2] myList[2] value
.. Array ..
element at
.. index 2 ..
.. ..

marks[9] myList[99]
Accessing Array Elements
• The array elements are accessed through the
integer index.
double rainfall[12];

0 1 2 3 4 5 6 7 8 9 1 1
0 1

This indexed expression


The index of the first rainfall[2] refers to the element at
position in an array is 0. position #2
Array Initializers
• C++ allows array to be initialized as follows:

double myList[4] = {1.9, 2.9, 3.4, 3.5};

• The above statement declares and initializes the array


with four elements and it is equivalent to the statements
shown below:

double myList[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
Array Initializers(cont.)
• Like other data types, it is possible to
declare and initialize an array at the same
time.
int number[5] = { 2, 4, 6, 8, 10};
int measure [] = {0, 0, 0, 0};
double samplingData[] = { 2.443, 8.99, 12.3,
45.009, 18.2,9.00, 3.123, 22.084, 18.08 };
char monthName[12][10] = {"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December" };

number 5 elements of int


samplingData 9 elements of double
monthName 12 elements of char
Processing One-Dimensional Arrays
• Basic operations performed on
one-dimensional array:
– Initialization
– Input
– Output
– Find sum
– Find average
– Find largest
– Find smallest
• These operations requires the ability to step
through the elements of the array=>loop
Processing One-Dimensional Arrays
• When processing array elements, a for loop is often
used because:
• All of the elements in an array are of the same type.
They are evenly processed in the same way using a
loop.
• Since the size of the array is known, it is natural to
use a for loop.

• Assume the array is declared as follows:

const int ARRAY_SIZE = 10;


double myList[ARRAY_SIZE];

• Examples of processing arrays:


1. Initializing arrays with input values
• The following loop initializes the array myList with user
input values.

cout<<“Enter “<<ARRAY_SIZE <<“ values: “;


for (int i = 0; i < ARRAY_SIZE; i++)
cin >> myList[i];
2. Initializing arrays with random values
• The following loop initializes the array myList with
random values between 0 and 99.

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


myList[i] = rand() % 100;
3. Printing arrays
• To print an array, you print each element in it, using a
loop like the following:

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


cout<< myList[i] << “ “;
3. Printing arrays
//print string array

#include <iostream>
using namespace std;
int main()
{ string name[] = {"ali", "siti", "ken",
"lulu"};
for (int i=0;i<4;i++)
cout<<name[i]<<endl;
return 0;
}
3. Printing arrays
//print character array

#include <iostream>
using namespace std;
int main()
{ char name[4][10] = {"ali", "siti",
"ken", "lulu"};
for (int i=0;i<4;i++)
{ cout<<name[i];
cout<<endl;
}
return 0;
}
3. Printing arrays
//print character array
#include <iostream>
using namespace std;
int main()
{ char monthName[12][10] = {"January",
"February", "March","April", "May", "June", "July",
"August", "September", "October",
"November", "December" };

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


{ cout<<monthName[i];
cout<<endl;
}
return 0;
}
4. Copying arrays
• Suppose you have two arrays, list and myList. Can
you copy myList to list using the following syntax?

list = myList;

• This is not allowed in C++. You must copy individual


elements from one array to the other as follows:

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


list[i] = myList[i];
5. To sum all elements
• Use a variable named total to store a sum. Initially, total is
0. Add each element in the array to total using a loop:

double total = 0.0;


for (int i = 0; i < ARRAY_SIZE; i++)
total += myList[i];
6. Finding the largest element
• Use a variable named max to store the largest element.
Initially, max is myList[0]. To find the largest element in
the array myList, compares each element in it with max,
and then update max if the element is greater than max.

double max = myList[0];


for (int i = 1; i < ARRAY_SIZE; i++)
if (myList[i] > max)
max = myList[i];
7. Finding the index of the largest element
• Use a variable named max to store the largest element
and indexOfMax to store the index of the largest
element. Initially, max is myList[0]. To find the largest
element in the array myList, compares each element in
it with max, and then update max and indexOfMax if the
element is greater than max.

double max = myList[0];


int indexOfMax = 0;
for (int i = 1; i < ARRAY_SIZE; i++)
if (myList[i] > max)
{ max = myList[i];
indexOfMax = i;
}
8. Finding the lowest element
• Use a variable named min to store the smallest element.
Initially, min is myList[0]. To find the smallest element
in the array myList, compares each element in it with
min, and then update min if the element is less than
min.

double min = myList[0];


for (int i = 1; i < ARRAY_SIZE; i++)
if (myList[i] < min)
min = myList[i];
9. Finding the index of the lowest element
• Use a variable named min to store the lowest element
and indexOfMin to store the index of the lowest
element. Initially, min is myList[0]. To find the lowest
element in the array myList, compares each element in
it with max, and then update max and indexOfMax if the
element is less than max.

double min = myList[0];


int indexOfMin = 0;
for (int i = 1; i < ARRAY_SIZE; i++)
if (myList[i] < min)
{ min = myList[i];
indexOfMin = i;
}
Processing array to find average
double rainfall[12];
double annualAverage,
sum = 0.0;
for (int i = 0; i < 12; i++) {

cout<<“Enter rainfall for each month”;


cin>>rainfall[i];
sum += rainfall[i];
}

annualAverage = sum / 12;


What is the output of the following code?
int list[] = {1, 2, 3, 4, 5, 6}

for (int i = 1; i < 6; i++)


list[i] = list[i – 1];

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


cout<<list[i] <<“ “;

//1 1 1 1 1 1
Write C++ statements to do the following.
a. Declare an array to hold 10 double values.
b. Input the array
c. Display the sum of the first two elements.
d. Write a loop that computes and display
the sum of all elements in the array.
e. Write a loop that finds and display the
minimum element in the array.
f. Assign value 5.5 to the last element in the
array and display the entire array.
What is the output of the following code?
double findMin(double arr[],int s)
{ double min = arr[0];
for (int i = 1; i < s; i++)
if (arr[i] < min)
min = arr[i];
return min;
}
Passing Array as Parameter to Functions
• In C++ , arrays are passed by reference only.
// arrays as parameters
#include <iostream>
using namespace std;
void printarray (const int arg[], int length)
{ for (int n=0; n < length; ++n)
cout << arg[n] << “ “;
cout << endl;
}
int main ()
{ int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
}

Output:
5 10 15
2 4 6 8 10
Passing Array as Parameter to Functions
#include <iostream>
using namespace std;

void printArray(int list[], int arraySize);//function prototype

int main ()
{ int numbers[5] = {1, 4, 3, 6, 8};
printArray (numbers,5); //call or invoke the function
return 0;
}

void printArray (int list[], int arraySize)


{ for (int i=0; i < arraySize; i++)
cout << list[i] << “ “;

}
Output:
1 4 3 6 8
Passing Array as Parameter to Functions(cont.)
// arrays as parameters
#include <iostream>
using namespace std;
int main ()
{ // an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;
}
double getAverage(int arr[], int size)
{ int i, sum = 0; double avg;
for (i = 0; i < size; ++i)
{ sum += arr[i];
}
avg = double(sum) / size;
return avg;
}

Output:
Average value is: 214.4
Passing Array as Parameter to Function(cont.)
Eg 1
void funcArrayAsParameter(int one[], double two[])
{…..
}
Eg 2
void initializeArray(int list[], int size)
{ int index;
for (index = 0; index< size; index++)
list[index] = 0;
}
Passing Array as Parameter to Function(cont.)
Eg 3
void inputArray(int list[], int size)
{ int index;
for (index = 0; index< size; index++)
cin>>list[index];
}
Eg 4
void printArray(const int list[], int size)
{ int index;
for (index = 0; index< size; index++)
cout<<list[index]<<“ “;
}
Passing Array as Parameter to Function(cont.)
Eg 5
int sumArray(const int list[], int size)
{ int index; int sum = 0;
for (index = 0; index< size; index++)
sum = sum +list[index];
return sum;
}
Eg 6
int findMax(int list[], int size)
{ int index; int max = list[0];
for (index = 1; index< size; index++)
if (list[index] > max)
max = list[index];
return max;
}
Passing Array Element as Parameter to Function
void printArray (int arg[], int length)
{ for (int n=0; n < length; ++n)
cout << arg[n] << ' ';
cout << '\n';
}
void passArrayElement (int e)
{ cout<<e<<endl;}

void main ()
{ int firstArray[] = {5, 10, 15};
int secondArray[] = {2, 4, 6, 8, 10};
printArray (firstArray,3); Output:
printArray (secondArray,5); 5 10 15
passArrayElement(firstArray[1]); 2 4 6 8 10
passArrayElement(secondArray[4]); 10
... 8
}
Passing Array as Parameter to Function
void printArray (int arg[], int length)
{ for (int n=0; n < length; ++n)
cout << arg[n] << ' ';
cout << '\n';
}
void modifyArray2 (int arg[],int size)
{ for (int n=0; n < size; ++n)
arg[n] = 0;
}
void main ()
{ int firstArray[] = {5, 10, 15};
int secondArray[] = {2, 4, 6, 8, 10}; Output:
printarray (firstArray,3); 5 10 15
printarray (secondArray,5); 2 4 6 8 10
modifyArray2 (firstArray,3); 000
modifyArray2 (secondArray,5); 000
printarray (firstArray,3);
printarray (secondArray,5);
}
Passing Array as Pointer to Function
#include<iostream>
using namespace std;
void printArray(int *list, int arraySize);//function
prototype

int main ()
{ int numbers[5] = {1, 4, 3, 6, 8};
printArray (numbers,5); //call or invoke the
function
return 0;
}
Output:
void printArray (int *list, int arraySize) 14368
{ for (int i=0; i < arraySize; i++)
cout << list[i] << " "; // output array using array
subscript notation
//cout<<*(list + i)<<” “;// output array using
pointer, both ways can be used
Relationship between Array and Pointer
• Arrays and pointers are intimately related in C++ and may be used
almost interchangeably. An array name can be thought of as a constant
pointer. Pointers can be used to do any operation involving array
subscripting.
#include <iostream>
using namespace std;
int main()
{ int b[] = { 10, 20, 30, 40 }; // create 4-element array b
int *bPtr = b; // set bPtr to point to array b

// output array b using array subscript notation


cout << "Array b printed with:Array subscript
notation"<<endl;

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


cout << "b[" << i << "] = " << b[ i ] << " "<<endl;
Relationship between Array and Pointer
// output array b using the array name and pointer/offset notation
cout << "Pointer/offset notation where "<< "the pointer is the array
name"<<endl;

for ( int offset1 = 0; offset1 < 4; offset1++ )


cout << "*(b + " << offset1 << ") = " << *( b + offset1 ) << " "<<endl;
// output array b using bPtr and array subscript notation
cout << "Pointer subscript notation";

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


cout << "bPtr[" << j << "] = " << bPtr[ j ] << " "<<endl;

cout << "Pointer/offset notation";

// output array b using bPtr and pointer/offset notation


for ( int offset2 = 0; offset2 < 4; offset2++ )
cout << "*(bPtr + " << offset2 << ") = "<< *( bPtr + offset2 ) << " "<<endl;
return 0;// indicates successful termination
}
Relationship between Array and Pointer
Parallel Arrays
• A parallel array is a structure that contains multiple arrays.
• Each of these arrays are of the same size and the array
elements are related to each other. All the elements in a
parallel array represent a common entity.
https://www.tutorialspoint.com/cplusplus-program-to-implement-parallel-array
Parallel Arrays(cont)
#include <iostream>
#include <string>
using namespace std;
int main() {
int max = 0, index = 0;
string empName [ ] = {"Harry", "Sally", "Mark", "Frank",
"Judy" };
string empDept [ ] = {"IT", "Sales", "IT", "HR", "Sales"};
int empSal[ ] = {10000, 5000, 20000, 12000, 5000 };
int n = sizeof(empSal)/sizeof(empSal[0]);
for(int i = 0; i < n; i++) {
if (empSal[i] > max) {
max = empSal[i];
index = i;
}
}
cout << "The highest salary is "<< max <<" and is earned by
"<<empName[index]<<" belonging to "<<empDept[index]<<"
department";
return 0;
}
https://www.tutorialspoint.com/cplusplus-program-to-implement-parallel-array
Parallel Arrays
#include <iostream>
#include <string>

using namespace std;


int main() {
int max = 0, index = 0;
string empName [ ] = {"Harry", "Sally", "Mark", "Frank", "Judy" };
string empDept [ ] = {"IT", "Sales", "IT", "HR", "Sales"};
int empSal[ ] = {10000, 5000, 20000, 12000, 5000 };
int n = sizeof(empSal)/sizeof(empSal[0]);

for(int i = 0; i < n; i++) {


if (empSal[i] > max) {
max = empSal[i];
index = i;
}
}
cout << "The highest salary is " << max <<" and is earned by
"<<empName[index]<<" belonging to " <<empDept[index]<<" department" ;
return 0;
}

https://www.tutorialspoint.com/cplusplus-program-to-implement-parallel-array
Dynamic Variables
• C++ does not automatically initialize variable.
Pointer variables must be initialized if you do not
want them to point to anything.
int *p = 0;
int *p = NULL;
• You learned how to declare pointer
variables, how to store the address of a
variable into a pointer variable of the same
type as the variable, and how to manipulate
data using pointers.
Dynamic Variables
• The power behind pointers is that pointers can be
used to allocate and deallocate memory during
program executions.
• Variables that are created during program
execution are called dynamic variables.
• With the help of pointers, C++ creates dynamic
variables.
• C++ provides two operators:
– new to create dynamic variables
– delete to destroy dynamic variables
Operator new
• The operator new has two forms: one to allocate a
single variable and another to allocate an array of
variables. The syntax to use the operator new is:
new datatype; // to allocate a single variable
new datatype[intExp]; //to allocate an array of variables

• The operator new allocates memory(a variable) of


the designated type and returns a pointer to it- that
is, the address of this allocated memory.
Moreover, the allocated memory is uninitialized.
Operator new
• Consider the following declaration:
int *p;
char *q;
int x;
• The statement: p = &x; stores the address of x
in p. No new memory is allocated.
• Consider the following statement:
p = new int;
• This statement creates a variable during program
execution somewhere in memory and stores the
address of the allocated memory in p.
• The allocated memory is accessed via pointer
dereferencing- namely, *p.
Operator new
• Similarly, the statement:
q = new char[16];
• This statement creates an array of 16 components
of type char somewhere in memory and stores the
base address of the array in q.
• Because a dynamic variable is unnamed, it cannot
be accessed directly. It is accessed indirectly by
the pointer returned by new.
Operator new
Example:
int *p; //p is a pointer of type p
char *name;//name is a pointer of type char
string *str;//str is a pointer of type string
p = new int;//allocates a memory of type int
//and stores the address of the
//allocated memory in p
*p = 28;//stores 28 in the allocated memory
cout<<*p;//28
cout<<p;//address of dynamic variable
cout<<&p;//address of p
name = new char[5];//allocates memory for an
//array of five components of type char and
//stores the base address of the array in
//name
Operator new
strcpy(name, “John”);//stores John in name
str= new string;//allocates memory of type
string and stores the address of the
allocated memory in str
*str = “Sunny Day”;//stores the string “Sunny
//Day” in the memory pointed to by str
Operator delete
• When a dynamic variable is no longer
needed, it can be destroyed; that is, its
memory can be deallocated.
• The C++ operator delete is used to destroy
dynamic variables. The syntax of operator delete
has two forms:
delete pointerVariable; //to deallocate a single
dynamic variable
delete [] pointerVariable; //to deallocate a
dynamically
created array
Operator delete
• Suppose you have the following
declaration:
int *p;
char *name;
string *str;
p = new int;
*p = 28;
name = new char[5];
delete p; //deallocate the memory space pointer p points to
delete[]name;//deallocate the memory space pointer name
points to
delete str;//deallocate memory space pointer str points to
• Remember: the memory allocated using the new
operator is persistent and exists until it is
Dynamic Array
• The array discussed so far is static array because
the size was fixed at compile time.
• Arrays that are created during program execution
are called dynamic arrays.
• To create a dynamic array:
– int *p; //declares p to be a pointer of type int
– p = new int[10]; //allocates 10 contiguous memory
locations, each of type int, and stores the address of the
first memory location into p
– *p = 25; //stores 25 into the first memory location
– p++; //p points to the next array component
– *p = 35; //stores 35 into the second memory location
Dynamic Array(cont.)
Dynamic Array
• Delete dynamic array
delete [] p;
Array and Pointers
• A pointer can store the address of a single
variable, it can also store the address of cells of an
array.
• Consider this example,
int *ptr;
int arr[5];
// store the address of the first
// element of arr in ptr
ptr = arr;

• The code is equivalent to the following:

int *ptr;
int arr[5];
ptr = &arr[0];
Array and Pointers
• A C++ array name is actually a constant pointer to
the first element in the array.
• Suppose you declare an array of int values as
follows:
int list[] = {11, 12, 13, 14, 15, 16};
• The following statement displays the starting
address of the array:
cout<<“The starting address of the array is
“<< list << endl;
• C++ allows you to access the elements in the array using
the dereference operator.
*list, *(list + 1), *(list + 2), *(list + 3), *(list
+ 4), *(list + 5),
Array and Pointers
• Array list points to the first element in the array.

list[0] list[1] list[2] list[3] list[4] list[5]

list list+1 list+2 list+3 list+4 list+5

*list *(list+1) *(list+2) *(list+3) *(list+4)*(list+5)


Array and Pointers
#include<iostream>
#include<conio>
int main()
{ int list[6] = {11, 12, 13, 14, 15, 16};
for (int i = 0; i < 6; i++)
{
cout<<"Address: "<< (list + i) <<" value: "<<
*(list + i) <<" " <<" value: "<<list[i]<<endl;
}
getch();
return 0;
}
Array and Pointers
#include<iostream>
#include<conio>
int main()
{ int list[6] = {11, 12, 13, 14, 15, 16};
for (int i = 0; i < 6; i++)
{
cout<<"Address: "<< list + i <<" value: "<<
*list + i <<" " <<" value: "<<list[i]<<endl;
}
getch();
return 0;
}
Array and Pointers
• Caution
– *(list + 1) is different from *list + 1.
– The dereference operator (*) has precedence over +.
So, *list + 1 adds 1 with the value of the first element
in the array while *(list + 1) dereferences the element
at address (list + 1) in the array.
Array and Pointers
• C-strings are often referred to as pointer-based strings,
because they can be conveniently accessed using
pointers. For example:

char city[7] = “Dallas”;


char * pCity = “Dallas”;

• You can access city or pCity using the array syntax or


pointer syntax. For example:
cout << city[1]<<endl; //a
cout << *(city + 1)<<endl; //a
cout << pCity[1]<<endl; //a
cout << *(pCity + 1)<<endl; //a
Multi-Dimensional 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];
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.
Two-Dimensional Arrays
• Two-dimensional arrays are useful in representing
tabular information.
Declaring Two-Dimensional Arrays
• A two-dimensional array can be think as a table,
which will have x number of rows and y number of
columns.
• Declaration
<data type> [][] <variable> //variation 1
<data type> <variable>[][] //variation 2

• Where data type can be any valid C++ data


type and variable or arrayname will be a
valid C++ identifier.
Declaring Two-Dimensional Arrays(cont.)
Example 1: int a [3][4];

• A 2-dimensional array a, which contains three


rows and four columns can be shown as
below:
a 0 1 2 3

2
Declaring Two-Dimensional Arrays(cont.)

• 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};
Accessing Two-Dimensional Arrays Elements
• An element in a two-dimensional array is
accessed by its row and column index.
Processing Two-Dimensional Arrays
•A two-dimensional array can be processed
in three ways:
1. Process the entire array. Eg. Initializing and
printing the array
2. Process a particular row of the array, called
row processing. Eg. Find the largest element
in a row, find the sum of a row
3. Process a particular column of the array,
called column processing. Eg. Find the
largest element in a column, find the sum of
column
Processing Two-Dimensional Arrays(cont.)
• Given the following declarations:

const int rowNo = 7;


const int columnNo = 7;
int matrix[rowNo][columnNo];
int row, col , sum, largest,
temp;
Initialization
•To initialize all array elements
for (row=0;row<rowNo;row++)
for (col=0;col<columnNo;col++)
matrix[row][col] = 0;
• To initialize row number 4
row=4;
for (col=0;col<columnNo;col++)
matrix[row][col]= 0;
Print
•To print the components of matrix, one row
per line

for (row=0;row<rowNo;row++)
{ for (int col=0;col<columnNo;col++)
cout<<matrix[row][col]<<“ “;
cout<<endl;
}
Input
•To input to all components of matrix
for (row=0;row<rowNo;row++)
for (col=0;col<columnNo;col++)
cin>>matrix[row][col];
•To input data into row number 4
row=4;
for (int col=0;col<columnNo;col++)
cin>>matrix[row][col];
Sum
•To sum all components of matrix
for (row=0;row<rowNo;row++)
{ for (col=0;col<columnNo;col++)
{ sum = sum +matrix[row][col];
}
}
Sum by Row
•To sum row number 4
row=4;
for (int col=0;col<columnNo;col++)
sum = sum +matrix[row][col];
Sum by Row
•To sum each individual row
for (row=0;row<rowNo;row++)
{ sum = 0;
for (col=0;col<columnNo;col++)
sum = sum +matrix[row][col];
cout<<“Sum of row”<< row + 1<<“=“<<sum<<endl;
}
Sum by Column
•To sum each individual column
for (col=0;col<colNo;col++)
{ sum = 0;
for (row=0;row<rowNo;row++)
sum = sum +matrix[row][col];
cout<<“Sum of column”<< col + 1<<“ = “<<sum<<endl;
}
•To sum column number 4
col=4;
for (row=0;row<rowNo;row++)
sum = sum +matrix[row][col];
Largest Element in Array
largest = matrix[0][0];
for (row=1;row<rowNo;row++)
for (col=1;col<colNo;col++)
{ if (largest < matrix[row][col])
largest = matrix[row][col];
}

cout<<“The largest element in array ”<<


largest<<endl;
Largest Element in Row Number 4
row = 4;
largest = matrix[row][0];
for (col=1;col<colNo;col++)
{ if (largest < matrix[row][col])
largest = matrix[row][col];
cout<<“The largest element in row ”<<
row + 1<<“ = “<<largest<<endl;
}
Largest Element in Each Row
for (row=0;row<rowNo;row++)
{ largest = matrix[row][0];
for (col=1;col<colNo;col++)
if (largest < matrix[row][col])
largest = matrix[row][col];
cout<<“The largest element in row ”<<
row + 1<<“ = “<<largest<<endl;
}
Largest Element in Each Column
for (col=0;col<colNo;col++)
{ largest = matrix[row][0];
for (row=1;row<rowNo;row++)
if (largest < matrix[row][col])
largest = matrix[row][col];
cout<<“The largest element in column ”<<
col + 1<<“ = “<<largest<<endl;
}
Lowest Element in Array
lowest = matrix[0][0];
for (row=1;row<rowNo;row++)
for (col=1;col<colNo;col++)
{ if (lowest > matrix[row][col])
lowest = matrix[row][col];
}

cout<<“The lowest element in array ”<<


lowest<<endl;
Write C++ statements to do the following.
a. Declare a 2D array to hold 12 double
values.
b. Input the array
c. Write a loop that computes and display
the sum of all elements in the array.
d. Write a loop that finds and display the
minimum element in the array.
e. Assign value 5.5 to the last element in the
array and display the entire array.
f. Find and display the odd numbers only
Passing 2-D Arrays as Parameters to Functions
• Two-dimensional arrays can be passed as parameters to
a function, and they are passed by reference.
• When storing a two-dimensional array in the computer’s
memory, C++ uses the row order form. That is, the first
row is stored first, followed by the second row, followed
by the third row, and so on.
• When declaring a two-dimensional array as a formal
parameter, you can omit the size of the first dimension,
but not the second; that is, you must specify the number
of columns.
Passing 2-D Arrays as Parameters to Functions
• Suppose we have the following declaration:
const int ROW_NO = 6;
const int COLUMN_NO = 5;
• Consider the following printMatrix()
function.
void printMatrix(int matrix[][COLUMN_NO],int noOfRows))
{ for (int row=0;row<noOfRows;row++)
{ for (int col=0;col<COLUMN_NO;col++)
cout<<matrix[row][col]<<“ “;
cout<<endl;
}
}
Passing 2-D Arrays as Parameters to Functions
• The following function outputs the sum of
the elements of each row
void sumRows(int matrix[][COLUMN_NO], int noOfRows))
{ int sum;
for (int row=0;row<noOfRows;row++)
{ sum = 0;
for (int col=0;col<COLUMN_NO;col++)
sum = sum + matrix[row][col];
cout<<“Sum of row ”<< (row + 1)<<“ = “<<
sum<<endl;
}
}
Passing 2-D Arrays as Parameters to Functions
• The following function determines the
largest elements in each row
void largestInRows(int matrix[][COLUMN_NO], int
noOfRows))
{ int largest;
for (row=0;row<noOfRows;row++)
{ largest = matrix[row][0];
for (col=1;col<COLUMN_NO;col++)
if (largest < matrix[row][col])
largest = matrix[row][col];
cout<<“The largest element in row ”<<
row + 1<<“ = “<<largest<<endl;
}
}
Passing 2-D Arrays as Parameters to Functions
#include<iostream.h>
#include<iomanip.h>

using namespace std;

const int ROW_NO = 6;


const int COLUMN_NO = 5;
void printMatrix(int matrix[][COLUMN_NO], int
noOfRows);
void sumRows(int matrix[][COLUMN_NO], int noOfRows);
void largestInRows(int matrix[][COLUMN_NO], int
noOfRows);
Passing 2-D Arrays as Parameters to Functions
void main()
{ int board[ROW_NO][COLUMN-NO]
= { {23, 5, 6, 15, 18},
{4, 16, 24, 67, 10},
{12, 54, 23, 76, 11},
{1, 12, 34, 22, 8},
{81, 54, 32, 67, 33},
{12, 34, 76, 78, 9}};
printMatrix(board, ROW_NO);//call function
cout<<endl;
sumRows(board, ROW_NO);//function call
cout<<endl;
largestInRows(board, ROW_NO);//function call
}

You might also like