0% found this document useful (0 votes)
125 views91 pages

Unit 6 (C++) - Arrays

The document discusses arrays in C++. It defines an array as a collection of data storage locations that hold the same type of data. Each storage location is called an element, which is identified by its index position in the array. Arrays allow grouping of repetitive data of the same type. The document covers key concepts such as declaring and accessing arrays, one-dimensional and multi-dimensional arrays, and using for loops to iterate through array elements. It provides an example program that declares an integer array, prompts the user to input values, and prints out the array.

Uploaded by

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

Unit 6 (C++) - Arrays

The document discusses arrays in C++. It defines an array as a collection of data storage locations that hold the same type of data. Each storage location is called an element, which is identified by its index position in the array. Arrays allow grouping of repetitive data of the same type. The document covers key concepts such as declaring and accessing arrays, one-dimensional and multi-dimensional arrays, and using for loops to iterate through array elements. It provides an example program that declares an integer array, prompts the user to input values, and prints out the array.

Uploaded by

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

UNIT SIX

ARRAYS AND STRING

1
Arrays
 An array is a collection of data storage locations, each of which
holds the same type of data.
 Each storage location is called an element of the array.
 An Array consists of a set of objects (called its elements), all of
which are of the same type and are arranged contiguously in
memory.
 Each element is identified by an index which denotes the position
of the element in the array.
 The number of elements in an array is called its dimension.
 The dimension of an array is fixed and predetermined; it cannot
be changed during program execution.
 Arrays are suitable for representing composite data which consist
of many similar, individual items.
 Examples include: a list of names, a table of world cities and their
current temperatures, or the monthly transactions for a bank
account.
2
 The underlying concepts of arrays are derived from matrix
algebra.
 Beside being used to represent matrices ,arrays are also
suited a variety of other purposes because, in C++ ,array
represents a defined number of contiguous (i.e.
consecutive) bytes in memory.
 An array is the grouping of repetitive data (of the same
type) that shares the same name.
 The data shares the same name but each element in the
arrays can be accessed individually.
 Each constituent value of an array is called an element.
 When an array is defined in C++, the programmer
specifies the number of elements in the array.
 The elements of an array can be ordered in different
pattern schemes. 3
 A one-dimensional array can be conceptually viewed as a
single string or row of a predefined number of values.
 For example ,a linear array of six integers could be
envisioned as:
column
0 1 2 3 4 5
row 0 Int1 Int2 Int3 Int4 Int5 int6
 In array notation this arrangement is know as a 1 x 6
array because it consists of single row and six columns.
 In C++ the elements of the dimension are numbered with
that dimension.
 An array including more than one dimension is called a
multi-dimensional array.
 For example, a 3 x 6 integer array could be conceptually
depicted as shown in the following figure. 4
column 0 1 2 3 4 5
row Int1 Int2 Int3 Int4 Int5 int6

column 0 1 2 3 4 5
row Int7 Int8 Int9 Int10 Int11 int12

column 0 1 2 3 4 5
row Int13 Int14 Int15 Int16 Int17 int18

Each of these elements is associated with column number


in the zero to six and a row number in the range of zero to
two.
These positional values are known as subscripts or indices.
If the above array is named example then int12 can be
identified as example[15].
5
 In this case first identification digital inside the square
bracket of array example,i.e.,1 represents that data int12
resides in row 1 and second digital 5 represents that data
int12 resides in 5th column.
 Notice that the total number of elements is the product of
the number of elements in each dimension,i.e.3*6= 18.
 An array in C++ can be differentiated by four attributes:
 Number of dimension (i.e. Nos. of rows and columns)
 Number of elements in each dimensions.
 Data type to the elements.
 Actual value of each element.
 The first two attributes determine the “size "of the array
in the conventional mathematical sense.
6
 While the third attributes determine the amount of required memory
storage and the fourth one determine the value stored in each
memory location.
 The elements of an array are accessed by specifying a subscript
after the arrays variable name.
 The first element of the array has subscript of 0, the next 1.and so
on .
 The last elements has a subscript of n-1 where n is the number of
elements in the array.
 When an array name is referenced without a subscript, the result is
the same as referencing the first elements in the array.
 The name of an array without a subscript is also used as a pointer to
that array.
 Arrays cannot be passed by value (i.e. the whole array) as an
argument in a function call.

7
 They are always passed by reference ( i.e. pointer at the
original array)
 The syntax for declaring array is the same as for simple
variable declaration except that the number of elements in the
array is placed within square brackets behind the variable’s
name.
 The number of element must be a positive integer constant.
 We declare an array by giving the type of its element, the
name of the array, and the number of element.
 The array type can be any C++
 The name can be any C++ identifier.
 The number of elements must be a constant expression with a
value greater than zero.
 For example
int counter [10];
 Declares an array with identifier counter each element is of
type int and there are 10 element allocated. 8
 These 10 data objects occupy 10 consecutive memory
locations and referenced using square brackets [ ] and
indices 0 through 9.
counter [0]
counter [1]
counter [2]
counter [3]
counter [4]
counter [5]
counter [6]
counter [7]
counter [8]
counter [9] 9
Rules for forming Arrays in C++
1. An array name must be chosen according to the same rules
as are used for naming any other variable.
2. The name of the array cannot be the same as that of any
other variable declared within the function.
3.The size of the array(the number of elements) is specified
using the subscript notation.
Example int array[4] , the subscript 4 indicates that the
array can accommodate only 5 elements.
4.The dimension used to declare an array must always be a
positive integer constant. Or an expression that can be
evaluated to a constant when the program is compiled.
5. All element of an array should be of the same type.
In other words, if an array is declared to be type int, it cannot
contain element that are not of type int. 10
 For example, if the variable i has the value 3, x [i] refers to
array element number 3 ( which is actually the fourth from
0).
 Thus the ideal C++ construct to manipulate arrays is the
for loop.
 The following loop reads six integers into an array , which
consists of six elements.
for (i=0; i<6; i++)
cout <<[i];
 Variable i in this loop offer is called the index variable
because it is used to “index” the desired elements of the
array.
 The body of the loop is executed six times. The first time i
has the value 0.
 The second time, i has the value 1, and so forth.
 The sixth and last time the loop executes, i has the value11 5.
 When i is incremented to 6, the loop test fails and the loop terminates.
 This format of the for loop is used so often with arrays that it is
almost worth memorizing.
 This loop also illustrates an important fact about array:
 An entire array cannot be read in all at once.
 Each elements of an array must be read in separately, either with a
loop as shown above or with a call to function in which each element
is specified separately.
 An entire array cannot be assigned to another array (this rule has no
exception).
 Even if both x and y are declared to be arrays of the same type and
size, and all the elements of x have been assigned values, a statement
such as
y=x; is illegal in C++

12
 For example, Array Elements
long LongArray[25]; declares an array of 25 long integers,
named LongArray.
 When the compiler sees this declaration, it sets aside enough
memory to hold all 25 elements.
 Because each long integer requires 4 bytes, this declaration sets
aside 100 contiguous bytes of memory.
 You access each of the array elements by referring to an
offset from the array name.
 Array elements are counted from zero. Therefore, the first
array element is arrayName[0].
 In the LongArray example, LongArray[0] is the first array
element, LongArray[1] the second, and so forth.
 This can be somewhat confusing.
 The array SomeArray[3] has three elements. They are
SomeArray[0], SomeArray[1], and SomeArray[2].
13
Example 1
//Program to implement integer Arrays
#include <iostream.h>
#include<conio.h>
int main() {
clrscr ();
//Declare an array with size of 5
int myArray[5];
//Declare index variable
int i;
//For loop to count five elements of an array
for ( i=0; i<5; i++) { // 0-4
cout<<"Value for myArray ["<<i<< "]: ";
cin >>myArray[i];
} 14
cout<<endl<<endl;
cout<<"The Output of the program is as follows:"<<endl<<endl;
//For loop to print each value of the array
for (i = 0; i<5; i++)
{
cout<<"Integers ["<<i<< "] :"<< myArray[i] << "\n";
}
return 0;
}
Line 7 declares an array called myArray, which holds five
integer variables.
Line 9 establishes a loop that counts from 0 through 4,
which is the proper set of offsets for a five-element array.
The user is prompted for a value, and that value is saved at
the correct offset into the array. 15
 The first value is saved at myArray[0], the second at
myArray[1], and so forth.
 The second for loop prints each value to the screen.
 The output of the program is as follows when users enter
data from 1 to 5:

16
Example 2
/*program to illustrate of the way in which an array of five
elements can be stored in memory printed out again */
#include<iostream.h>
#include<conio.h>
main () {
clrscr ();
//Declaration of an array
int array[5];
//Declaration of index variable
int i;
//For loop to count elements of the array
for(i=0; i<5; i++) {
//Input the five integers in to array "array"
cout<<"Enter integer number ["<<i +1<<“]:" ;
cin>>array[i]; 17
}
cout<<endl<<endl;
cout<<"Output of the Program is:"<<endl<<endl;
//For loop to Print out the integers stored in array
for(i=0; i<5; i++)
cout<<"Integers ["<<i+1 <<"]="<<array[i]<<"\n";
}
The integer array array is declared to contain five elements.
Array is not a reserved word in C++ but is not a very
original name to give to an array.
The variable i is declared for use as an index.
 All index variables must be of type int or a compatible type
such as short or char
A prompt is displayed, asking the user to enter five
integers.
18
 A loop is then executed to read in the integers, the user is
prompted for each integer, and each one read in is
assigned to the array element subscripted by i.
 Notice that the prompt for the individual element uses the
expression i+ 1 rather than i as you might have expected
when printing the element number.
 This approach enables the user to see the numbering of
the elements in the natural way, starting with 1 rather
than 0.
 When the body of the loop has been executed five times,
the user is informed “Output of the program is:” using for
loop.
 Again the element number is printed out using i +1,
though i still is used as the actual subscript.
19
Array Initialization
 When declaring an array of local scope (within a
function), it will not be initialized, so its content is
undetermined until we store some values in it.
 If we declare a global array (outside any function) its
content will be initialized with all its elements filled with
zeros. Thus, if in the global scope we declare:
int billy [5];
int main (){
}
every element of billy will be set initially to 0:

0 1 2 3 4
billy 0 0 0 0 0

Fig: Dinamic Initialization of an array 20


 But additionally, when we declare an array, we have the
possibility to assign initial values to each one of its elements
using curly brackets { }.
 For example:
int billy [5] = {16, 2, 77, 40, 12071};
this declaration would have created an array like the following
one:
0 1 2 3 4
billy
16 2 77 40 12071

 The number of values we initialize to each elements in the


array within curly brackets { } must much the length in
elements that we declared for the array enclosed within
square brackets [ ].
21
 For example, in the example of the billy array we have
declared that it had 5 elements and in the list of initial
values within curly brackets { } we have set 5 different
values, one for each element.
 Because this can be considered useless repetition, C++
includes the possibility of leaving the brackets empty [ ]
and the size of the array will be defined by the number of
values included between curly brackets { }.
int billy [ ] = {16, 2, 77, 40, 12071};
 Look the following program, an array of five integers is
declared as a global array.
 As we recall, a global variable is one that is declared
outside any function (usually before main).
 It exist throughout the execution of the program, and is
accessible from any function within the program. 22
 A special features of global array is that they can be
initialized when they are declared.
 This is done by following the array name and dimension
with the equal sign (as used to initialize variables),
followed by a pair of braces.
 These braces contain a series of constant values
separated by commas.
Example 3
#include<iostream.h>
#include<conio.h>
//Declaration of global array with initialized value
int array [6]= {5,6,8,9,2,0};
//Main function
int main () {
clrscr (); 23
//Declaration of index variable
int i;
//print out the integers stored in array
for (i =0; i <6; i++) {
cout<<"Integers:"<<i+1 <<" = "<<array[i]<<"\n";
}
return 0;
}
The output of the program is the following:

24
 Array can be initialized at declaration time when their
initial values are known in advance, as is done in the above
program.
 Using the concepts we have shown you so far, only global
arrays can be initialized at the time of declaration.
 The values used to initialize an array must be constants-
never variables or function calls.
int array [ ]= {5,6,8,9,2,0};
Since the square brackets following the array name are
empty, the compiler determines how many elements to
allocate for the array by counting the number of values
within the curly braces.
This approach can help avoid errors.
But if the dimension is specified explicitly, and curly braces
contain more initialization values than are needed, a syntax
error is flagged by the compiler. 25
 It is not necessary to fill all the elements of an array if
fewer elements than the maximum are needed.
 Sometimes it is not known in advance how many
elements will be needed until execution time, at which
point the array has already been dimensioned.
 When dealing with an arrays, it is easiest to occupy as
many low-numbered elements are needed and leave the
rest unused.
 It is legal to initialize only some of the elements of an
array.
 For example, the statement
int array [4] ={1, 2, 3};
allocates five elements of array, and initialized array [0] to
1, array[1] to 2, and array[2] to 3, setting the remaining
elements to 0. 26
 In such a declaration, the dimension of the array must be
explicitly specified, since if the compiler counts the total
number of initializing values inside the curly braces, then
it would allocate only three elements.
 Moreover, the programmers cannot arbitrarily choose the
elements to be initialized.
 The specified values are assigned to consecutive elements
of the array, beginning with the 0th, element.
 The example initialized elements 0 through 2. It would
not be possible to initialize only elements 1 through 3 or 2
through 4 within the declaration; that would have to be
done using either individual assignments.
 The following example, the constant
MAX_ARRAY_SIZE is defined to be 20.
 In the declaration of the integer array, this constant is
used to dimension the array. 27
 The variable array_size is used to store the actual size of
the array, however, as specified by the user of the
program in response to the initial prompt.
 The variable array_size, rather than the constant
MAX_ARRAY_SIZE, is used in both for the loops as the
upper limit of the index.
Example 4
//Implement maximum array size using #define library
#include<iostream.h>
#define MAX_ARRAY_SIZE 20
//Main Function
int main () {
int array[MAX_ARRAY_SIZE];
int array_size, i; 28
// Enter the number of elements to be stored into the array
cout<<"How many integer will you enter?:";
cin>>array_size;
//Enter the actual elements of the array
cout<<"Please enter "<<array_size<<" "<<"integers:";
for(i=0; i<array_size; i++){
cin>>array[i];
}
//Print out the integer
for(i=0; i <array_size; i++){
cout<<"Integer " <<i+1<<" = "<<array[i] <<"\n";
}
return 0;
} 29
 After the user is prompted to enter the number of
elements to be stored into the array, a further prompt
asks that used to enter the actual elements of the array.
 The number of integers must correspond to the number
specified at the beginning of the program by the user.
 If too few numbers are entered, the computer waits for
the remainder to be typed in
 If too many are provided, the extra ones are ignored.
 After the element of the array have been entered, a
blank line is printed by outputting a single newline
character, and the elements of the array are displayed in
the usual manner.

30
Accessing to the values of an Array
 In any point of the program in which the array is visible
we can access individually anyone of its values for
reading or modifying as if it was a normal variable
 The syntax is:
name[index_variable];
 Suppose the bill array had 5 elements and each of those
elements was of type int, the name which we can use to
refer to each element is the following:
billy[0] billy[1] billy[2] billy[3] billy[4]

 For example, to store the value 75 in the third element of


billy a suitable statement would be written as: billy[2]=75;
 And, for example, to pass(assign) the value of the third
element of billy to the variable a, we could write:
a= billy[2]; 31
 Therefore, for all purposes, the expression billy[2] is like
any other variable of type int.
 Notice that the third element of billy is specified billy[2],
since first is billy[0], the second is billy[1], and therefore,
third is billy[2].
 By this same reason, its last element is billy[4]. Since if we
wrote billy[5], we would be accessing to the six element of
billy and therefore exceeding the size of the array.
 In C++ it is perfectly valid to exceed the valid range of
indices for an array, which can create problems since they
do not cause compilation errors but they can cause
unexpected results or serious errors during execution.
 The reason why this is allowed will be seen further a head
when we begin to use pointers.
32
 The brackets [ ] used in arrays perform two different
tasks:
i) To set the size of the arrays when declaring them
 Look the following example to set the size of the array:
int billy[5]; //declaration of a new array
ii) To specify indices for a concrete array element when
referring to it.
 Look the following Statement:
billy[2]=75; //Access to an element of the array
 The other valid operations with arrays are:
billy[0] =a;
billy[a]=75;
b=billy [a+1];
billy[billy[a]]=billy[2]+5;
33
Example 5
//C++ Program to access the values of an array
#include<iostream.h>
//Global Array declaration and initialization of values
int billy []={16, 2, 77, 40, 12};
int n, result=0;
int main()
{
for(n=0; n<5; n++)
{
result +=billy[n];
}
cout<<result;
return 0;
}
34
Reversing of the Array
 It is designed for reversing the elements of the array. Look the
program below to implement reversing elements of the array.
Example 6
//Program to implement reversing the elements of an array
#include<iostream.h>
#define ARRAY_SIZE 5
int main () {
int array[ARRAY_SIZE]; //An array
int i; // A loop index
//Read in the array
cout<<"Please Enter"<<" "<<ARRAY_SIZE<<" "<<"integers:";
for (i=0; i<ARRAY_SIZE; i++){
cin>>array[i];
}//End of for loop ()
cout<<"\n";
//Print the original array
cout<<"The original array is the following :"<<"\n"<<"\n"; 35
for(i=0; i<ARRAY_SIZE; i++)
{
cout<<array[i]<<",";
} //End of for loop
cout<<"\n"<<"\n";
//Print the array in reverse order
cout<<"The reversed array is as follows:"<<"\n"<<"\n";
//Index goes from the highest to the lowest
for(i=ARRAY_SIZE-1; i>=0; i--)
{
cout<<array[i]<<",";
} //End of for loop
return 0;
} //End of main ()
36
 In the above example, the array of integers is read in the
usual manner, although the limit this time has been
defined as 10 elements and all 10 must be read in.
 After the array has been echoed back, a blank line is
printed.
 The array then is displayed backwards by a for loop,
which is instead of incrementing its index from 0 to
ARRAY_SIZE-1, decrements from ARRAY_SIZE-1 to
0.
 This demonstrates that the elements of an array do not
have to be accessed in any specific order.
 The order is determined by the programmer, based on
the requirements of the problem at hand.
37
Passing Arrays as Arguments to Functions
 An array can be passed to a function when function is
called from any other program.
 Look the following C++ program to illustrate passing
arrays as an argument to functions to print the contents of
array and calculate sum of the contents of array :
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
//Declaration of Functions
void Print(int a[ ], int n);
int Sum(int a[ ], int n);
//Main Function
int main()
{
clrscr (); 38
//Declaration of Array with some initial value
int list[ ] = { 2, 4, 6, 8 };
//Declaration of variables local to main ()
int sum;
// Call a Function to print the contents of the array
Print(list, 4);
// Call the function Sum()
sum=Sum(list, 4);
//Display Sum
cout<<"Sum of the contents of array="<<sum<<endl;
return 0;
}//End of main ()
//Define a Function to print the array
void Print(int a[ ], int n)
{ 39
//For loop to print the content of array
for ( int i = 0; i < n; i++ )
{
cout<<setw(4)<<a[i] << " ";
}//End of for loop
cout<<endl;
} //End of print ()
//Define a function to sum the contents of the array
int Sum(int a[ ], int n) {
int result = 0;
for ( int i = 0; i < n; i++ )
result += a[i];
return result;
} 40
 As shown in the print function’s declaration and
definition:
void print(int a[ ], int n)
 When an array formal parameter is declared, its square
brackets are left empty.
 The programmer can supply a number within the square
brackets, but it is ignored by the compiler.
 When calling a function that accepts an array parameter,
as in: print(list, 4);
the programmer must pass the array’s size along with the
array name.
 This is because an array simply references a block of
memory and has no notion of its size.
 An undecorated array name by itself in C++ source code
behaves like a constant pointer to the beginning element of
the array. 41
 Consequently, when an array is passed as an actual
parameter during a function call,
print(list, 4);
the function is passed the address of the array—the array’s
address is bound to the formal parameter.
 So, while the function cannot affect the address of the
array itself, the function has total access to the array’s
contents.
 Let’s see the following C++ program to demonstrate
passing arrays as argument to the function and the
function clear( ) or modifies the contents of any array
sent to it, making all the elements zero.

42
Example 8
/*Program to illustrate passing arguments to a function and
function clear( ) modifes the contents of any array */
#include <iostream.h>
#include<conio.h>
#include<iomanip.h>
// Declaration of functions
void print(int a[], int n);
void clear(int a[], int n);
//Main Function ()
int main() {
//Declaration of Array
int list[] = { 2, 4, 6, 8 };
// Call Print function to print the contents of the array
print(list, 4);
// Call Clear function to make zero out the array
clear(list, 4); 43
// Call Print Function to reprint the contents of the array
print(list, 4);
return 0;
} //End of main ()
//Define Function to print contents of array
void print(int a[], int n) {
for ( int i = 0; i < n; i++ ){
cout <<setw(2)<<a[i]<< " ";
}//End of for loop()
cout<<endl<<endl;
}//End of print ()
/*Define a function to modify contents of array, the content of array
all becomes zero*/
void clear(int a[ ], int n) {
for ( int i = 0; i < n; i++ ){
a[i] = 0;
}//End of for loop ()
} //End of clear () 44
 The clear function actually modifies the contents of
main’s list array.
 The function works on the array’s actual elements, not
copies of its elements.
 Arrays, therefore, by default are passed by reference with
respect to the elements they contain.
 By default, an array’s contents are open to corruption by
errant functions.
 In order to protect an array so that a function may read
its contents but not modify its contents, the parameter
must be declared const, as in
int sum(const int a[], int n)
 In the previous exercise, there is no reason why the print
function should be able to modify the contents of their
array parameters, so the const specifier should be added
to their definitions. 45
 As a general rule, all functions that accept array
parameters should declare the array contents as const
unless they need to modify the elements of the array.
 For example, use
int sum(const int a[], int n)
rather than
int sum(int a[], int n)
 If the sum function must be able to examine the contents
of the array but is not intended to modify its contents.
Exercise
1. Write C++ program to calculate average of different
numbers of subject matter by declaring and defining the
necessary functions and arrays. Assuming that the program
accepts score of the student and number of subjects from
the user as an input. 46
Multi-dimensional Arrays
 The arrays we have seen thus far have been one
dimensional- simple sequences of values.
 C++ supports an array more than one dimensions(i.e.;
two, three or higher).
 A two-dimensional array is a block of memory that is
best visualized as a table with rows and columns.
 For example, the statement int a[2][3];
declares a to be a two-dimensional array of integers.
 A two-dimensional array is sometimes called a matrix.
 In this case, the declaration specifies that array a
contains two rows and three columns.
 The following figure shows the logical structure of the
array created by the following sequence of code:
;
int a[2][3]; // a is a 2D array
a[0][0] = 5;
a[0][1] = 19;
a[0][2] = 3;
a[1][0] = 22;
a[1][1] = -8;
a[1][2] = 10; Figure: 2 x 3 two-dimensional array
The two-dimensional array a is said to be a 2 x 3 array,
meaning it has two rows and three columns (as shown in
the above figure).
 Rows are arranged horizontally, and the values in
columns are arranged vertically.
In each of the assignment statements above, for example
48
a[1][0] = 22;
 The first index (here 1) signifies the row and the second
index (here 0) denotes the column of the element within
the array.
 Using a syntax similar to the initialization lists of one-
dimensional arrays, the two-dimensional array a from
above could have been declared and initialized as
follows:
int a[2][3] = { { 5, 19, 3 }, { 22, -8, 10 } };
 Note that each row appears within its own set of curly
braces, and each row looks like 1D array initialization list.
 You may omit the first index, as shown here:
int a[][3] = { { 5, 19, 3 }, { 22, -8, 10 } };
 For two-dimensional arrays initialized in this manner the
first subscript is optional, but the second subscript (that is,
the size of each column) is required. 49
 To access an element of a two-dimensional array, use two
subscripts:
a[r][c] = 4; // Assign element at row r, column c
// Display element at row m, column n
cout << a[m][n] << endl;
 Note:- Processing a multidimensional array is similar to a one-
dimensional array, but uses nested loops instead of a single loop.
Example 1
 Let’s see the following C++ program to illustrates two
dimensional array. Though we use nested for loop to perform the
operation of multi-dimensional array, the following program use
one for loop to read rows of an array and the other for loop to
count number of columns because the array contains initialized
value.

50
#include <iostream.h>
#include <conio.h>
//Main Function
int main()
{
clrscr ();
//Declaration of two dimensional Array and initialize them
int SomeArray[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
cout<<"Output of the program is as follows:"<<endl<<endl;
//Outer For Loop to count number of rows
for (int i = 0; i<5; i++)
{
//Inner For loop to count number of columns
for (int j=0; j<2; j++)
{
cout << "SomeArray[" << i << "][" << j << "]: "; 51
cout << SomeArray[i][j]<<endl;
} //End of inner for loop
}//end of outer for loop
return 0;
} //End of main ()
 Line 8 declares SomeArray to be a two-dimensional
array.
The first dimension consists of five integers; the second
dimension consists of two integers.
This creates a 5x2 grid or matrix.
The values are initialized in pairs, although they could be
computed as well.
Lines 11 and 14 create a nested for loop.
The outer for loop ticks through each member of the first
(row) dimension.
52
 For every member in that dimension, the inner for loop
ticks through each member of the second(column)
dimension.
 This is consistent with the printout. SomeArray[0][0] is
followed by SomeArray[0][1].
 The first dimension is incremented only after the second
dimension is incremented by 1.
 Then the second dimension starts over.
 The output of the above C++ program is looks like the
following:

53
Activity
1. Refer the programs in Example 1 in slides (51 &
52) used to illustrate multi-dimensional arrays by
assigning a value by the programmer. Rewrite the
previous program to implement multi-dimensional
array, assuming that the program accept values of
each elements of the array from the user (or not to
initialized a value at the time of declaration).

54
Example 2
2. Let’s see the following C++ program to implement the two-
dimensional arrays. The program first declare maximum
rows and columns and then accept the number of rows and
columns (i.e;. 3x3) as an input from the users and the users
enter actual values of elements of an array and display the
result:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//Declaration of constant Global Variables
const int MAX1=10;
const int MAX2=10;
//Main Function
int main (){
clrscr (); 55
//Declaration of two-dimensional array
int M[MAX1][MAX2];
//Declaration of Variables local to main () to accept rows and columns
int NbRows, NbColumns;
//Declaration of Index Variables
int i, j;
//User Assign the number of Rows and columns
cout<<"Enter number of Rows:";
cin>>NbRows;
cout<<"Enter number of Columns:";
cin>>NbColumns;
// Outer for Loop to read number of rows
for(i=0; i<NbRows; i++){
// Inner for loop to read number of columns
56
for(j=0; j<NbColumns; j++){
cout<<"Enter M["<<i<<"]["<<j<<"]:";
cin>>M[i][j];
}//End of inner for loop
} //End of outer for loop
//Print the matrix you entered using for loop
cout<<"The matrix you entered is:"<<"\n";
for(i=0; i<NbRows; i++){
for(j=0; j<NbColumns; j++){
cout<<setw(3)<<M[i][j];
}//End of Inner for loop
cout<<endl;
}//End of Outer for loop
return 0;
}//End of main () 57
Passing two-dimensional Arrays as Arguments to
Functions
 The following function prints the contents of a ROWS X
COLUMNS two-dimensional array of doubles:
void Print_Matrix(int M[ROWS][COLUMNS], int NbRows,
int NbColumns) {
for(int row=0;row<NbRows;row++) {
for(int col=0;col<NbColumns;col++ ){
cout<<setw(5)<<M[row][col];
} //End of inner loop
cout<<endl;
} //End of outer loop
} //End of Print_Matrix()

58
Example 3
 Look the following Program with two-dimensional arrays
and pass arguments to the Read_Matrix and Print_Matrix
function.
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
//Declaration of Constant Variables
const int ROWS = 3, COLUMNS = 3;
//Declaration of functions
void Read_Matrix(int M[ROWS][COLUMNS], int, int);
void Print_Matrix(int M[ROWS][COLUMNS], int, int);
//Declaration of Array
int M[ROWS][COLUMNS];
//Main Function
void main() { 59
clrscr ();
// Declaration of Variables local to main ()
int NbRows, NbColumns;
cout<<"Enter Number of Rows:";
cin>>NbRows;
cout<<"Enter Number of Columns:";
cin>>NbColumns;
// call a function to read rows and columns as input
Read_Matrix(M,NbRows, NbColumns);
// Call a function to Print the array
Print_Matrix(M, NbRows,NbColumns);
}
// Define a function to enter the elements of a matrix
void Read_Matrix(int M[ROWS][COLUMNS], int NbRows, int NbColumns) {
for (int row=0;row<NbRows;row++) {
cout<<"Enter Row #"<<row<<" "<<"having 3 values :"; 60
for(int col=0;col<NbColumns;col++){
cin>>M[row][col];
} //End of inner loop
} //End of outer loop
} //End of Read_Matrix()
//Define a function to print the array
void Print_Matrix(int M[ROWS][COLUMNS], int NbRows,
int NbColumns) {
for(int row=0;row<NbRows;row++) {
for(int col=0;col<NbColumns;col++ ){
cout<<setw(5)<<M[row][col];
} //End of inner loop
cout<<endl;
} //End of outer loop
} //End of Print_Matrix()
61
Example 4
/*Program to calculate Addition of two matrix entered by the user, say
(2x2) matrix without defining and declaring a function */
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
int main (){
clrscr ();
//Declaration of two-dimensional array
int M1[2][2], M2[2][2],M3[2][2];
//Declaration of Variables local to main () to accept rows and columns
int NbRows, NbColumns;
//Declaration of Index Variables
int i, j;
//User Assign the number of Rows and columns
cout<<"Enter number of Rows:";
cin>>NbRows; 62
cout<<"Enter number of Columns:";
cin>>NbColumns;
//Nested For Loop to accept inputs for the first Matrix
for(i=0; i<NbRows; i++){
cout<<"Enter Row #"<<i<<" "<<"of the first matrix having 3 values :";
for(j=0; j<NbColumns; j++){
cin>>M1[i][j];
}//End of inner for loop
}//End of outer for loop
cout<<endl<<endl;
//Nested For Loop to accept inputs for the second Matrix
for(i=0; i<NbRows; i++){
cout<<"Enter Row#"<<i<<""<<"of the second matrix having 3
values :";
for(j=0; j<NbColumns; j++){
cin>>M2[i][j];

63
}//End of inner for loop
} //End of outer for loop
//Nested for loop to hold the product of two matrix
for(i=0; i<NbRows; i++){
for(j=0; j<NbColumns; j++){
M3[i][j]=M1[i][j] + M2[i][j];
}//End of inner for loop
}//End of outer for loop
cout<<endl;
//Nested for loop to Print the product of two matrix
cout<<"The Sum of the two Matrix is:"<<"\n";
for(i=0; i<NbRows; i++){
for(j=0; j<NbColumns; j++){
64
cout<<setw(3)<<M3[i][j];
}//End of Inner for loop
cout<<endl;
}//End of Outer for loop
return 0;
}//End of main ()
Activity
1. Rewrite the above program to implement(perform)
addition of matrix for (3x3) matrix?
2. Refer the above program as information and declare and
define the necessary functions and call the functions from the
main program and pass the array as an argument to a
function and perform addition of the three matrix.
65
Assignment
3. Write C++ program to find sum, product and subtraction
of three matrix by declaring and defining the necessary
functions. The program perform the required operation
when a function is called from the main program. And the
program accept inputs from the users for first, second and
third matrix and also accept inputs for the number of rows
and columns of the matrix
4. Write C++ program for lower and upper triangular matrix
separately and then write one program together for
both(lower and upper triangular matrix).

66
C++ Strings : Arrays of Char type
 A string is a series of characters.
 The only strings you've seen until now have been unnamed
string constants used in cout statements, such as: cout <<
"hello world.\n";
 In C++ a string is an array of chars ending with a null
character.
 You can declare and initialize a string just as you would any
other array. For example,
char Greeting[] ={‘H’,‘e’, ‘l’,‘l’,‘o’,` `,`W','o','r','l','d', `\0' };
 The last character, `\0', is the null character, which many C+
+ functions recognize as the terminator for a string.
 Although this character-by-character approach works, it is
difficult to type and admits too many opportunities for error.
 C++ enables you to use a shorthand form of the previous
line of code.
67
 It is rewritten as:
char Greeting[] = "Hello World";
 You should note two things about this syntax:
1. Instead of single quoted characters separated by commas
and surrounded by braces, you have a double-quoted
string, no commas, and no braces.
2. You don't need to add the null character because the
compiler adds it for you.
 The string Hello World is 12 bytes.
 Hello is 5 bytes, the space 1, World 5, and the null
character 1.
 You can also create uninitialized character arrays.
 As with all arrays, it is important to ensure that you don't
put more into the buffer than there is room for.
 The following simple C++ program demonstrates the use
of an uninitialized buffer. 68
#include <iostream.h>
#include <conio.h>
//Main Function
int main() {
clrscr ();
//Declaration of Char Array Type without initialization
char buffer[80];
//Users Enter the String
cout<<"Enter the string: ";
cin>>buffer;
//Display the String
cout<<"Here's the buffer:"<<buffer<<endl;
return 0;
}
69
Output: Enter the string: Hello World
Here's the buffer: Hello
On line 7, a buffer is declared to hold 80 characters.
This is large enough to hold a 79-character string and a
terminating null character.
On line 10, the user is prompted to enter a string, which is
entered into buffer on line 10.
It is the syntax of cin to write a terminating null to buffer
after it writes the string.
There are two problems with the previous program:
First, if the user enters more than 79 characters, cin writes
past the end of the buffer.
Second, if the user enters a space, cin thinks that it is the
end of the string, and it stops writing to the buffer.
To solve these problems, you must call a special function
on cin.get(). 70
 cin.get() takes three parameters:
 The buffer to fill
 The maximum number of characters to get
 The delimiter that terminates input. The default delimiter
is newline.
 Let’s see the following C++ program to demonstrate
cin.get:
#include <iostream.h>
#include <conio.h>
//Main Function
int main() {
clrscr ();
//Declaration of Char Array Type without initialization
char buffer[80];
//Users Enter the String
cout<<"Enter the string: "; 71
cin.get(buffer, 79); // get up to 79 or newline
//Display the String
cout<<"Here's the buffer:"<<buffer<<endl;
return 0;
}
Output: Enter the string: Hello World
Here's the buffer: Hello World
Line 10 calls the function get() of cin.
The buffer declared in line 7 is passed in as the first
argument.
The second argument is the maximum number of
characters to get.
In this case, it must be 79 to allow for the terminating null.
There is no need to provide a terminating character because
the default value of newline is sufficient. 72
 Variables that can store non-numerical values that are longer
than one single character are known as strings.
 A string is a variable that stores a sequence of letters or
other characters, such as "Hello" or "May 10th is my
birthday!".
 The C++ language library provides support for strings
through the standard string class.
 This is not a fundamental type, but it behaves in a similar
way as fundamental types do in its most basic usage.
 A first difference with fundamental data types is that in
order to declare and use objects (variables) of this type we
need to include an additional header file in our source code:
<string.h>.
 As we discussed previously, strings are arrays of characters.
73
 In the arrays of characters, the null character is always
added to the end of the characters.
 The null character is ’\0’; with ASCII value of 0.
 In C++ there is no means to check the array bounds.
 Therefore, be careful when putting data into arrays not to
exceed its maximum bounds.
 For example the inbuilt C++ function setw(bound) helps
to read characters as much as size of bound.
 When we display strings, characters inside an array are
displayed until a null (‘\0’) character is encountered.
 Let’s see the following C++ program that reads your
name from keyboard and displays it, the cin.get()
function is also used.
74
//Program to read your first name and last name
//And display the result
#include<iostream.h>
#include<conio.h>
//Main Function{}
void main (){
//Declaration of string array type
char name [20];
cout<<"Enter Full Name:";
//Call cin.get() function
cin.get(name,20);
//Display the string
cout<<“My name is :"<<name;
} 75
Reading Multiple Lines of strings
 Some time it is necessary to read multiple lines of string
from the key board.
 The default terminating character is the new line (‘\n’)
character.
 But it is possible to override the default character with some
other characters so that we can read multiple lines of text
until that terminating character is typed.
 This can be achieved by adding the terminating character in
the cin.get ( ) function as an argument.
 Example
//Program to reads multiple lines of text and stores in arrays
#include<iostream.h>
#include<conio.h>
//Main Function
void main ()
{ 76
clrscr ();
//Declaration of String as an Array
char str[100];
//Users Enter a string
cout<<"Enter a String and $ When finishes:";
/*Call cin.get() function and pass the terminator as an argument */
cin.get(str, 100,'$');
//Display the String
cout<<"\n"<<"The String you entered is:"<<str;
}//End of main ()

Note:-The above program passes array name, maximum


size and terminator ($) as an argument when cin.get()
function is called
77
Arrays of strings
 Like arrays of arrays, it is also possible to have arrays of
strings.
 This is important to store arrays of names of people, or
other strings for some other purpose.
 To define such constructions, we should write the size of
the array and the maximum size of each string.
Example
//Program stores list of names in an array and display it
#include<iostream.h>
#include<conio.h>
//Main Function ()
void main( ) {
clrscr ();
/*Declaration of two-dimensional Arrays of Strings with
some Initial Value */ 78
char name[5][10]={"kebede","Ayele","Tufa","Almaz",
"Kasa"};
//For Loop to Print the Contents of Strings of an array
for (int i=0; i<5;i++){
cout<<name[i]<<'\n';
}//End of For Loop
}//End of main ()

79
String Manipulation
1. strlen( ):
 is C++ library function that finds the length of a string.
 determines how many characters are in the string,
excluding the null (‘\0’) character.
 This function takes the name of the string variable or
constant as an input (argument) and returns an integer
value.
 We must include the <string.h> header file to use this
function.
/*Program that takes your name and tells the length of your
name */
#include<iostream.h>
//Header Files for String Characters
#include<string.h>
#include<conio.h> 80
//Main Function ()
void main()
{
clrscr();
//Declaration of String Array
char name[25];
//Users Enter the String
cout<<"Enter your name: ";
cin>>name;
//Display the name
cout<<"My name is:"<<name<<"\n";
//Call Streln() function to determine the length of the string
cout<<"It is"<<" "<<strlen(name)<<" "<<"characters long";
} //End of main ()
81
2. strcpy()
 It is a common process to copy one string into another.
 You can have many ways to copy a string.
 Copying a string character by character is one option to do
so.
 It needs to access characters of a string character by
character.
 Using the built in function strcpy() to copy a string is
another easier method.
/*Program to implement strcpy()function to copy a string
character by character */
#include<iostream.h>
#include<string.h>
#include<conio.h> 82
//Declaration of Global Variables
const int SIZE=100;
//Main Function ()
void main ()
{
clrscr ();
//Declaration of String Array
char str1[SIZE];
char str2[SIZE];
//Users Enter a String
cout<<"Enter a string on str1:";
//Call Function cin.get() and pass arrays as an argument
cin.get(str1,SIZE);
83
//Call Strcpy Function to Copy a String in str1 to str2
strcpy(str2,str1);
//Display Copy of the string
cout<<"\n"<<"Copy of your string to str2 is:"<<str2;
} //End of Main ()
strcpy( ) takes two arguments and copies the second
variable ( the right hand side) to the first (left hand side)
variable.

84
3. strcat( ):
This function takes two arguments and concatenates
(appends) the second variable to the first one.
/*Program to concatenate (append) one String with the
other */
#include<iostream.h>
#include<conio.h>
#include<string.h>
//Main Function
void main ( )
{
clrscr();
//Declaration of two String Array one having a String
char ch1[50];
char ch2[100]="I am proud of";
cout<<ch2<<endl; 85
//Users Enter The String need to Append
cout<<"Enter a string to concatenate :";
//Call cin.ge() to pass array and array size as an argument
cin.get(ch1,50);
//Call A strcat() function to append a string in str2 to str1
strcat(ch2,ch1);
//Display The concatenated String
cout<<"The concatenated String is:"<<ch2;
}//End of main ()

86
4. strcmp( )
This function takes two string arguments and
compares them.
The result of the comparison is an integer value of
either negative, positive, or zero based on the following
facts.
 Example strcmp(str1,str2);
0 if str1 is the same as str2
+ve (>0) if str2 comes first alphabetically
-ve (<0) if str1 comes first alphabetically
Example: the following program takes two words
from a user and compares their alphabetical
precedence.
87
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
const int p=15;
char ch1[p],ch2[p];
cout<<"Enter first string: ";
cin>>ch1;
cout<<"enter second string: ";
cin>>ch2;
if(strcmp(ch1,ch2)==0)
{
88
cout<<"The two words are the same";
}
else if(strcmp(ch1,ch2)>0){
cout<<ch2<<"Comes first alphabetically";
}
else if(strcmp(ch1,ch2)<0) {
cout<<ch1<<"Comes first alphabetically";
}
else{
cout<<"None of all the above";
}
}
89
Example
//Another C++ program reads your name from keyboard and
//display it in reverse order
 #include<iostream.h>
#include<conio.h>
#include<string.h>
#include<iomanip.h>
void main ( )
{ char name[20];
cout<<"Enter your name \t";
cin>>setw(20)>>name;
for(int i=(strlen(name)-1);i>=0;i--)
cout<<name[i];
getch();
}
90
Assignment
1. Write C++ program that reads string of text and display
the string by changing all the characters in upper case.
Use toUpper ( ) function , by including the header file
ctype.h

91

You might also like