You are on page 1of 6

Qatar University

College of Engineering
Dept. of Computer Science & Engineering

Computer Programming
Lab Handbook
Fall 2012 Semester

Lab 9: Arrays
At the end of this lab, you should be able to
Use arrays in C++.
Pass arrays to functions.
Use arrays with files.
Use 2-dimensional arrays.

Quick Review

An array is a group of consecutive memory locations that are related by the fact that they all have
the same name and same type, e.g. double stress[3]; declares a 1-dimensional array of size
3, i.e. the number of elements is 3.
A subscript (sometimes called index) is used to refer to a particular location within the array, e.g.
stress[0], stress[1], etc.
To pass an array to a function, the name of the array is passed, e.g. x=max(stress);
By default arrays are passed to functions using pass-by-reference, e.g. sort(stress);
A 2-dimensional array represents a table of values consisting of information arranged in rows
and columns, e.g. double nodeStress[100][3];
To access a particular element, two subscripts are specified. The first subscript references the
row and the second references the column, e.g. nodeStress[53][1].

1) Compile and run the following program:

#include <iostream>
using namespace std;
int main()
int diameter[] = {20,22,19,23,20,21,23,25,19};
for(int x = 0; x < 9; x++)
cout <<"Diameter["<< x <<"] = " << diameter[x]<<endl;
return 0;


Describe the output of the program?



How many elements are there in the array diameter? _____________________

What is the subscript (index) of the last element of diameter? _____________________
Change the condition of the for-loop to become x<=9 and run the program. What is the
last line of the output? ______________________ Is it correct? ___________________
Change the condition of the for-loop back to x<9 and save your program.
Now, add to your program statements to calculate and output the sum of the diameters
and the average diameter.

2) Compile and run the following program

#include <iostream>
using namespace std;
void replace(int x[],int s, int oldValue, int newValue )
for(int i=0;i<s;i++)
int main()
int a[5]={2,7,4,2,8};
cout<<"Array before calling function replace \n";
for(int i=0;i<5;i++)
cout<<a[i]<< '\t';
replace (a, 5, 2, 9);
cout<<"Array after calling function replace \n";
for(int i=0;i<5;i++)
cout<<a[i]<< '\t';
return 0;

Write down the output of the progam


What does function replace do?

From the example above, we can say that array is passed to a function by _______________.
Assume you have an array called force that has 10 elements and we want to pass that array to
a funtion called sort. Which one of the following is a correct function call:
a) sort(force);
b) sort(force[]);
c) sort(force[10]);
Overload the replace function by providing an implementation that replaces all the
elements in the array x[]of size s, with a value val. Use the following prototype:
replace(int x[], int s, int val);

3) Write a C++ program that reads 10 real numbers into an array called distance, and then
calculates and prints the sum of positive numbers sumPositive, and the sum of negative numbers

Index number

Test your program with the following data:








Modify your program to find and output the largest number.



Sample output

4) Working with Vectors:

a) A column vector x of size n is usually represented, in C++, by a 1-dimensional array. Adding
two vectors x and y then reduces to adding the corresponding elements x[0]+y[0], x[1]+y[1],
Write a C++ function called addVectors() that has four parameters: three integer arrays x, y
and z and their size, n. Let your function store the sum of x and y in the array z.
Write a driver program to test your function using the following data:

and b

Sample output

b) The norm of a vector x, written as x, is a measure of its size (a scalar quantity). One of the
simple vector norms is the Euclidean norm, defined as x =
Add to your program of Question (4a) a function called norm2() that takes as parameters an
integer array, x, and its size, n. Let the function return the double value representing the
Euclidean norm of x.
Add to your program statements to print the norms of the vectors
Sample output


given above.

5) a) Write a C++ program that initializes an array called diameters with the following numbers,
and then stores the numbers into a file named result.dat:
16.25, 18.96, 22.34, 18.94, 17.42, 22.63.
b) Write another C++ program to read the numbers in the result.dat file created in Question-5a
and display the data. Additionally, your program should compute and display the sum and average
of the data.
NOTE: Review the use of files in Lab5 Exercises 4 through 8.

6) The following program initializes the 2-dimensional array marks[][]that represents a table of
marks of five students in three subjects: math, computer and English. Compile and run the program.
#include <iostream>
using namespace std;
int main()
double marks[][3]={
cout<<"Stud# Math Computer English\n";
for(int i=0;i<5;i++)
for(int j=0;j<3;j++)
return 0;

Describe the output of the above program.


The following function returns the average of the elements of a double array x of size n:
double average(double x[], int n)
double sum=0;
for(int i=0;i<n;i++)
return sum/n;

Add the above function to your program and then use it to output the average mark for each
student as shown in the typical output below. (Hint: the ith row of our array is marks[i]; a 1dimensional array of size 3).

Typical Output:

The following function returns the letter grade corresponding to a given mark:
char grade(double mark)
return 'A';
else if (mark>=80)
return 'B';
else if (mark>=70)
return 'C';
else if (mark>=60)
return 'D';
return 'F';

Add the above function to your program and then use it to produce a table of the student
numbers and the corresponding letter grade for each of the three subjects, as well as for the
average grade.
Typical Output:

7) The norm of a

matrix A, written as A, is a measure of its size (a scalar quantity). One of

the famous vector norms is the Frobenius norm, defined as A =

The following function receives a 2-dimensional array (number of rows is to be passed as a

parameter, and number of columns is fixed to be 3), the function finds the Frobenius norm of the
matrix represented by the array a.

double normf(double a[][3], int m)

double sum=0;
for (int i=0;i<m;i++)
for(int j=0;j<3;j++)

// m=rows in the matrix

return sqrt(sum);

True or false: when we pass a 2-dimensional array to a function, the number of columns
should be constant.
Use the function above, to output the Frobenius norm of the marks array of Question (5).

8) Transposing a matrix is swapping rows and columns, for example the matrix

is transposed into
Write C++ program that reads a 2-dimensional array (3 rows, 3 columns), and then transposes this
array. Then display the array after transposing.
I/O Sample (user input is marked in red):
Enter row-1: 1 2 4
Enter row-2: 3 6 7
Enter row-3: 9 5 8
The transpose of the above matrix is:
1 3 9
2 6 5
4 7 8
Press any key to continue . . .

9) Specify whether each of the following C++ array declarations is correct () or wrong ():
____ int a[];


int a[3];

____ int a[]={3,2,1};


int a[5]={3,4};

____ int x=3; int a[x];


int a[3]={0};