You are on page 1of 67

PROGRAMMING-II

C++ language

Instructor:
Elie Abou Zeid
COURSE TOPICS
# Subjects covered
1 String type
2 Pointers
3 Pointers References, Pointer to Function, Arguments
4 Pointers and arrays
5 Data Structures
6 Array of structures manipulation
7 Input/output and files in C++

2
COURSE TOPICS
# Subjects covered
8 Binary files in C++
9 Recursion
10 Array Manipulation (1): sorting
11 Array Manipulation (2): searching methods
12 Array Manipulation (3): insert and delete
13 Operator Overloading

3
TWO- AND MULTIDIMENSIONAL ARRAYS
4
CHAPTER OUTLINE
¢ Reminder on One-Dimensional Arrays

¢ Two-dimensional Arrays
— Definition and Usage
— Declaration
— Initialization During Declaration
— Accessing Array Components
— Enumeration Types
— Processing Two-dimensional Arrays
— Passing Arrays as Parameters to Functions
— Enumeration Types
5
¢ Larger Arrays
TWO- AND MULTIDIMENSIONAL ARRAYS
6 Reminder on One-Dimensional Arrays
ONE-DIMENSIONAL ARRAYS
¢ An array is a collection of a fixed number of components all of the
same data type.

¢ A one-dimensional array is an array in which the components


are arranged in a list form.

¢ The general form for declaring a one-dimensional array is:

intExp
• is any constant expression that evaluates to a positive integer. 7
• specifies the number of components in the array.
ONE-DIMENSIONAL ARRAYS
¢ Example:
— int num[5];
— This declares an array num of 5 components - integers.

¢ Accessing Array Components:


— The general syntax for accessing an array component is:
— The array index starts at 0
— Example:
¢ int list[10];
¢ list[5] = 34; //stores 34 in list[5], which is the 6th component

8
ONE-DIMENSIONAL ARRAYS
¢ Accessing Array Components:
— Examples:

int i = 3;
list[i] = 63;

int i = 4;
list[2 * i - 3] = 58; //list [5] = 58

list[3] = 10;
list[6] = 35;
list[5] = list[3] + list[6];

9
ONE-DIMENSIONAL ARRAYS
¢ When declaring an array, its size must be known.

¢ Example:
const int ARRAY_SIZE = 10;
int list[ARRAY_SIZE];

¢ The following is illegal:


int arraySize;

cout << "Enter the size of the array: ";


cin >> arraySize;
10

int list[arraySize]; //not allowed


ONE-DIMENSIONAL ARRAYS
Processing one-dimensional arrays
¢ Some of the basic operations performed on a one-dimensional array are:
ü initializing
ü inputting data
ü outputting data

¢ If the data is numeric, some other basic operations are:


ü finding the largest and/or smallest element
ü the sum and average of the elements.

¢ Each of these operations requires the ability to step through the


elements of the array.
— Using a loop! 11
ONE-DIMENSIONAL ARRAYS
Array Index Out of Bounds!
¢ Example:

double list[10];
int i;

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


list[i] = 0;
— list[10] does not exist.

— The program terminates with an error message.


12
ONE-DIMENSIONAL ARRAYS
Array Initialization
¢ An array can be initialized while it is being declared
¢ Examples:
ü double sales[5] = {12.25, 32.50, 16.90, 23, 45.68};
ü double sales[] = {12.25, 32.50, 16.90, 23, 45.68};

Partial Initialization during declaration


¢ int list [10] = {0};
— initializes all 10 elements to 0

¢ int list[10] = {8, 5, 12};


13
— This example declares list to be an array of 10 elements and initializes
list[0] to 8, list[1] to 5 and list[2] to 12 and all other elements to 0:
ONE-DIMENSIONAL ARRAYS
Partial Initialization of Arrays During Declaration
¢ The size of the array in the declaration statement does matter.
— int list[] = {5, 6, 3};
//declares a list of only 3 elements with values set to 5, 6 and 3
— int list[25] = {5, 6, 3};
//declares a list of 25 elements initialized to 5, 6, 3
//and the remaining 22 elements to 0

¢ With partial initialization, all of the elements that follow the last
uninitialized elements must be uninitialized. Therefore, the
following statement will result in a syntax error:
û
14
— int list[10] = {2, 5, 6, , 8};
ONE-DIMENSIONAL ARRAYS
Restrictions on Array Processing
¢ To copy one array into another array, you must copy it one component at
a time.
int myList[5] = {0, 4, 8, 12, 16};
int yourList[5];

yourList = myList;
û for (int index = 0; index < 5; index ++)
yourList[index] = myList[index]; ü
¢ To read data into yourList, you must read one component at a time:

û
15
cin >> yourList; for (int index = 0; index < 5; index ++)
cin >> yourList[index]; ü
ONE-DIMENSIONAL ARRAYS
Restrictions on Array Processing
¢ Similarly, the following operations must be done also element by
element:
— determining whether 2 arrays have the same elements.
— printing the contents of an array.

¢ The following statements are illegal; they do not generate syntax


errors; however, they do not give the desired results.

cout << yourList; û if (myList <= yourList)


...
û
16
ONE-DIMENSIONAL ARRAYS
Functions Cannot Return a Value of the Type Array
¢ C++ does not allow functions to return a value of the type array.

Arrays as Parameters to Functions


¢ Arrays are passed by reference only.
— Thus, the symbol & when declaring an array as a formal parameter is not
required.

¢ In addition to declaring an array as a formal parameter, we declare the


number of elements:
void initialize(int list[], int listSize)
{
int i;
for (i = 0; i < listSize; i++) 17

list[i] = 0;
}
ONE-DIMENSIONAL ARRAYS
Arrays as Parameters to Functions
¢ Even though an array is always passed by reference, you can still
prevent the function from changing the actual parameter.
void example(int x[], const int y[], int sizeX, int sizeY)
{
...
}

The function example can modify the array x, but not the array y.
Any attempt to change y results in a compile-time error.
18
ONE-DIMENSIONAL ARRAYS
Complete Example:
void initializeArray (int list[], int listSize)
{
int index;
for (index = 0; index < listSize; index++)
list[index] = 0;
}

void fillArray (int list[], int listSize) void printArray (const int list[], int listSize)
{ {
int index; int index;
for (index = 0; index < listSize; index++) for (index = 0; index < listSize; index++)
cin >> list[index]; cout << list[index] << " ";
} } 19
ONE-DIMENSIONAL ARRAYS
Complete Example:
int sumArray(const int list[], int listSize)
{
int index;
int sum = 0;
for (index = 0; index < listSize; index++)
sum = sum + list[index];
return sum; int indexLargestElement (const int list[], int listSize)
} {
int index;
int maxIndex = 0;
for (index = 1; index < listSize; index++)
if (list[index] > list[maxIndex])
maxIndex = index; 20
return maxIndex;
}
ONE-DIMENSIONAL ARRAYS
Complete Example:
const int ARRAY_SIZE = 10;

void main()
{
int listA[ARRAY_SIZE] = {0};
int listB[ARRAY_SIZE];

printArray(listA, ARRAY_SIZE);

initializeArray(listB, ARRAY_SIZE);
printArray(listB, ARRAY_SIZE);
21
fillArray(listA, ARRAY_SIZE);
printArray(listA, ARRAY_SIZE);
ONE-DIMENSIONAL ARRAYS
Complete Example:

cout << "The sum of the elements of listA is: "


<< sumArray(listA, ARRAY_SIZE) << endl;

cout << "The position of the largest element in listA is: "
<< indexLargestElement(listA, ARRAY_SIZE) << endl;

cout << "The largest element in listA is: "


<< listA[indexLargestElement(listA, ARRAY_SIZE)] << endl;

}
22
TWO- AND MULTIDIMENSIONAL ARRAYS
23 Two-dimensional Array - Definition and Usage
TWO-DIMENSIONAL ARRAY - DEFINITION AND USAGE
¢ Suppose that you want to track the number of cars in a particular
color that are in stock at a local dealership.

¢ The dealership sells six types of cars in five different colors.

• The table has 30 entries of the


same type.

• Each entry reflects a given


car in a specific color
24
TWO-DIMENSIONAL ARRAY - DEFINITION AND USAGE
¢ Two-dimensional array: A collection of a fixed number of
components arranged in rows and columns (two dimensions),
wherein all components are of the same type.

25
TWO- AND MULTIDIMENSIONAL ARRAYS
26 Two-dimensional Array - Declaration
TWO-DIMENSIONAL ARRAY - DECLARATION
¢ The syntax for declaring a two-dimensional array:

Number of rows Number of columns

constant expressions yielding positive integer values

27
TWO-DIMENSIONAL ARRAY - DECLARATION
Example: double sales[10][5];

¢ declares a two-dimensional
array sales of 10 rows and 5
columns.

¢ in this array, every


component is of type double.

¢ the rows are numbered 0…9


and the columns are
numbered 0…4 28
TWO- AND MULTIDIMENSIONAL ARRAYS
29 Two-dimensional Array - Initialization
TWO-DIMENSIONAL ARRAY - INITIALIZATION
¢ Initializing to 0:
— int x[3][4] = {};

¢ Initializing to specific values other than 0:


— int x[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
— The elements will be filled in the array in the order, first 4 elements from
the left in first row, next 4 elements in second row and so on.

¢ Better Method:
— int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
— Each set of inner braces represents one row. 30
TWO-DIMENSIONAL ARRAY - INITIALIZATION
¢ Two-dimensional arrays with initializer lists can omit (only) the leftmost length
specification: int array[][5] =
{
{ 1, 2, 3, 4, 5 },
ü
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 14, 15 }
};

The compiler can do the math to figure out what the array length is.

¢ However, the following is not allowed:


int array[][] =
{
{ 1, 2, 3, 4 },
û
{ 5, 6, 7, 8 } 31
};
TWO-DIMENSIONAL ARRAY - INITIALIZATION
int board[4][3] = {{2, 3, 1},
{15, 25, 13},
{20, 4, 7},
{11, 18, 14}};

a two-dimensional array of four rows


and three columns

• For number arrays, if you leave some row elements not specified,
they will be initialized to 0.

• In this case, at least one of the rows must be set to initialize the 32

remaining ones to 0.
TWO- AND MULTIDIMENSIONAL ARRAYS
33 Two-dimensional Array - Accessing Components
TWO-DIMENSIONAL ARRAY - ACCESSING COMPONENTS

¢ indexExp1 and indexExp2 are


expressions yielding nonnegative
integer values.

¢ indexExp1 specifies the row


position.

¢ indexExp2 specifies the column


position. 34
TWO-DIMENSIONAL ARRAY - ACCESSING COMPONENTS
¢ Suppose we have the following declaration: int x[3][3];
¢ Elements are commonly referred by x[i][j]
— i is the row number
— j is the column number

35
TWO- AND MULTIDIMENSIONAL ARRAYS
36 Two-dimensional Array - Processing
TWO-DIMENSIONAL ARRAY - PROCESSING
A two-dimensional array can be processed in 3 ways:

1. Process the entire array.

2. Process a particular row of the array, called row processing.

3. Process a particular column of the array, called column


processing.

37
TWO-DIMENSIONAL ARRAY - PROCESSING
¢ Initialization of all the values of an array to 0

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


{
for (int j = 0; j < m; j++)
{
T[i][j] = 0;
}
}

38
TWO-DIMENSIONAL ARRAY - PROCESSING
¢ Initialization of the values of row number 5 to 0
int lign = 5;
for (int j = 0; j < m; j++)
T[lign][j] = 0;

¢ Initialization of the values of column number 5 to 0


int col = 5;
for (int i = 0; i < n; i++)
T[i][col] = 0;

39
TWO- AND MULTIDIMENSIONAL ARRAYS
40 Passing Arrays as Parameters to Functions
PASSING ARRAYS AS PARAMETERS TO FUNCTIONS
¢ Two-dimensional arrays are passed to a function by reference.

¢ C++ stores two-dimensional arrays in row order form.

— Thus, to compute the address of a component correctly, the compiler must


know where one row ends and the next row begins.

— Therefore, when declaring a two-dimensional array as a formal


parameter, you can omit the size of the first dimension, but not the
second (the number of columns).

41
TWO-DIMENSIONAL ARRAY - EXAMPLE
#include <iostream>
using namespace std;

const int Nmax = 3;


const int Mmax= 4;

42
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Fill the Array
void fillArray(int T[][Mmax], int n, int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << "T[" << i << "][" << j << "]= ";
cin >> T[i][j];
}
}
}
43
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Print the Array
void printArray(int T[][Mmax], int n, int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
cout << T[i][j] << " ";
cout << endl;
}
}

44
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Sum of all elements in the Array
int sumAllArray(int T[][Mmax], int n, int m)
{
int s = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
s+= T[i][j];
}
}
return s;
} 45
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Sum of a specific row in the Array
int sumOfSpecificRow(int T[][Mmax], int lign, int m)
{
int s = 0;
for (int j = 0; j < m; j++)
{
s+= T[lign][j];
}
return s;
}

46
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Sum of a specific column in the Array
int sumOfSpecificColumn(int T[][Mmax], int n, int col)
{
int s = 0;
for (int i = 0; i < n; i++)
{
s+= T[i][col];
}
return s;
}

47
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Sum by row, of each row in the Array
void sumByRow(int T[][Mmax], int n, int m)
{
int sum;
for (int i = 0; i < n; i++)
{
sum = 0;
for (int j = 0; j < m; j++)
sum = sum + T[i][j];
cout << "Sum of row " << i << " = " << sum << endl;
}
}
48
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Sum by column, of each column in the Array
void sumByColumn(int T[][Mmax], int n, int m)
{
int sum;
for (int j = 0; j < n; j++)
{
sum = 0;
for (int i = 0; i < n; i++)
sum = sum + T[i][j];
cout << "Sum of column: " << j << " = " << sum << endl;
}
}
49
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Max value by row, of each row in the Array
void maxByRow(int T[][Mmax], int n, int m)
{
int max;
for (int i = 0; i < n; i++)
{
max = T[i][0];
for (int j = 1; j < m; j++)
{
if (T[i][j]>max)
max = T[i][j];
}
cout << ”Largest element of row " << i << " = " << max << endl;
} 50
}
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Max value by column, of each column in the Array
void maxByColumn (int T[][Mmax], int n, int m)
{
int max;
for (int j = 0; j < m; j++)
{
max = T[0][j];
for (int i = 1; i < n; i++)
{
if (T[i][j]>max)
max = T[i][j];
}
cout << ”Largest element of column " << j << " = " << max << endl;
} 51
}
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Main Function
int main()
{
int n, m, lign, col, T[Nmax][Mmax];
do
{
cout << "n = ";
cin >> n;
}
while (n<0 || n>Nmax);
do
{
cout << "m = ";
cin >> m; 52
}
while (m<0 || m>Mmax);
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Main Function

fillArray(T,n,m);
printArray(T,n,m);
cout << "Sum of all array elements: " << sumAllArray(T,n,m) << endl;

cout << "Sum per row: " <<endl;


sumByRow(T,n,m);

cout << "Sum per column: " <<endl;


sumByColumn(T,n,m);
cout << "Max per rows: " << endl;
maxByRow(T,n,m);
53
cout << "Max per columns: " << endl;
maxByColumn(T,n,m);
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Main Function

do
{
cout << "Lign = ";
cin >> lign;
}
while (lign<0 || lign>n);
cout << sumOfSpecificRow(T, lign, m) << endl;
do
{
cout << "Column = ";
cin >> col;
}
while (col<0 || col>m);
cout << sumOfSpecificColumn(T, n, col) << endl; 54
return 0;
}
TWO-DIMENSIONAL ARRAY - EXAMPLE
¢ Sample Run:
n=3 Sum of row 2 = 24
m=3 Sum per column:
T[0][0]= 1 Sum of column: 0 = 12
T[0][1]= 2 Sum of column: 1 = 15
T[0][2]= 3 Sum of column: 2 = 18
T[1][0]= 4 Max per rows:
T[1][1]= 5 The largest element of row 0 = 3
T[1][2]= 6 The largest element of row 1 = 6
T[2][0]= 7 The largest element of row 2 = 9
T[2][1]= 8 Max per columns:
T[2][2]= 9 The largest element of column 0 = 7
123 The largest element of column 1 = 8
456 The largest element of column 2 = 9
789 Lign = 0
Sum of all array elements: 45 6
Sum per row: Column = 0 55
Sum of row 0 = 6 12
Sum of row 1 = 15
TWO- AND MULTIDIMENSIONAL ARRAYS
56 Enumeration Types
ENUMERATION TYPES
¢ Enumeration types are new, simple data types that are user-
defined

¢ Name and values are specified, but not the operations.

¢ Helps to avoid potential system failures.

57
ENUMERATION TYPES
¢ The syntax for enumeration type is:

¢ value1, value2, ... are identifiers called enumerators.

¢ In C++, enum is a reserved word.

¢ If a value has already been used in one enumeration type, it cannot


be used by any other enumeration type in the same block
58
ENUMERATION TYPES
Examples
¢ the following statement defines a new data type called colors, and
the values belonging to this data type are: BROWN, BLUE, RED,
GREEN, and YELLOW.
— enum colors {BROWN, BLUE, RED, GREEN, YELLOW};

¢ enum grades {A, B, C, D, E, F};

¢ enum places {FIRST, SECOND, THIRD, FOURTH};

59
ENUMERATION TYPES
¢ By listing all of the values between the braces, you also specify an
ordering between the values.

¢ That is, value1 < value2 < value3 <....

¢ Thus, the enumeration type is an ordered set of values.

¢ Moreover, the default value assigned to these enumerators starts


at 0.
— the default value assigned to value1 is 0,
— the default value assigned to value2 is 1,
— and so on. 60
ENUMERATION TYPES
¢ Example
int main()
{
enum carType {TOYOTA, BMW};
carType c1 = BMW;
if (c1 == BMW)
cout << "car c1 is of type: BMW" << endl;
else
cout << "car c1 is of type: Toyota" << endl;

carType c[3] = {TOYOTA, BMW, TOYOTA};


for (int i=0; i<3; i++)
{
cout << "car[" << i << "] is of type: ";
if (c[i] == BMW)
cout << "BMW" << endl;
else
cout << "Toyota" << endl;
}
61

return 0;
}
ENUMERATION TYPES
Example 1:
int main()
{
const int NUMBER_OF_ROWS = 2;
const int NUMBER_OF_COLUMNS = 3;
enum carType {TOYOTA, BMW};
enum colorType {BLACK, WHITE, GRAY};
int inStock[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS] = {{1,2,3}, {4,5,6}};
cout << inStock[BMW][BLACK] << endl;
cout << inStock[1][0];
return 0;
}

BLACK WHITE GRAY

TOYOTA 1 2 3
62
BMW 4 5 6
ENUMERATION TYPES Grade0 Grade1

Example 2: Student0 A B
enum grades {A, B, C, D, E, F};
grades g [2][2] = {{A, B},{D, F}};
Student1 D F
for (int i=0; i<2; i++)
{
cout << "Student having the id = " << i << " has the following grades:" << endl;
for (int j=0; j<2; j++)
{
cout << "course id = " << j << ": " ;
switch (g[i][j])
{
case A:
cout << "above 90" << endl;
break;
case B:
cout << "above 80" << endl;
break;
default:
cout << "below 80" << endl;
break; 63
}
}
}
TWO- AND MULTIDIMENSIONAL ARRAYS
64 Larger Arrays
LARGER ARRAYS
¢ We can also define three-dimensional or larger arrays.

¢ In C++, there is no limit on the dimension of arrays.

¢ The general syntax for declaring an n-dimensional array is:


— dataType arrayName[intExp1][intExp2] ... [intExpn];

¢ The syntax to access a component of an n-dimensional


array is:
— arrayName[indexExp1][indexExp2] ... [indexExpn]

65
LARGER ARRAYS
¢ Example:
— double carDealers[10][5][7];

¢ The total number of components in the array carDealers is 10 * 5 * 7 = 350.

¢ You can use loops to process multidimensional arrays:


for (i = 0; i < 10; i++)
for (j = 0; j < 5; j++)
for (k = 0; k < 7; k++)
carDealers[i][j][k] = 0.0;

66
THANK YOU!
67 Questions?

You might also like