You are on page 1of 41

Fundamentals of Programming II

course content:

• Chapter one: Array and String


• Chapter Two: Pointers in C++
• Chapter three: Function
• Chapter Four: Fundamentals of Classes
• Chapter Five: Operator Overloading
• Chapter Six: I/O stream
CHAPTER -1
ARRAY AND STRINGS
Session objective:
At the end of this session the students will be able to
• Define One-dimensional array
• Define Multi-dimensional array
• Explain string
Brainstorming:

• What are the Stages of Program Development?

• Flow control (or control flow)?


• Variable?
• Identifier?
• Data type?
• Array?
• String?
Arrays
– An array is a series of elements of the same type placed
in contiguous memory locations that can be
individually referenced by adding an index to a unique
identifier.
– for example, we can store 5 values of type int in an
array without having to declare 5 different variables,
each one with a different identifier.
– Instead of that, using an array we can store 5 different
values of the same type, int for example, with a unique
identifier.
• For example, an array to contain 5 integer values of type
int called billy could be represented like this:
– where each blank panel represents an element of the array, that
in this case are integer values of type int.
– These elements are numbered from 0 to 4 since in arrays the
first index is always 0, independently of its length.
– Like a regular variable, an array must be declared before it is
used.
– A typical declaration for an array in C++ is:
– type name [elements];
o type is a valid type (like int, float...),
o name is a valid identifier
• elements field (which is always enclosed in square brackets []),
specifies how many of these elements the array has to contain.
• Therefore, to declare an array called billy as the one
shown in the above diagram it is int billy [5];
• NOTE: The elements field within brackets [] which
represents the number of elements the array is going to
hold, must be a constant value, since arrays are blocks of
non-dynamic memory whose size must be determined
before execution.
• Array is a collection of items of same data type that are
referenced by a common name.
• All the variables are referred using an index value.
• The index value starts at 0 i.e., first value is referred.
• The individual values are called elements.
• That element is referred by index of subscript.
Initializing Arrays
• By predetermined sequence/ elements
• By using literal sequence
• By enclosing the text to become a string literal between
double quotes (").

– For example: int mark [5] = { 6, 2, 7, 0, 171 }; This declaration would have created an array
like this:
0 1 2 3 4
mark 6 2 7 0 171
– The amount of values between braces { } must
not be larger than the number of elements that
we declare for the array between square
brackets [ ].
– When an initialization of values is provided for
an array, C++ allows the possibility of leaving
the square brackets empty [ ].
– In this case, the compiler will assume a size for
the array that matches the number of values
included between braces { }:
– int mark [] = { 16, 2, 77, 40, 12071 };
– After this declaration, array mark would be 5 ints long,
since we have provided 5 initialization values.
Accessing the Values of an Array.
• To access the value of any of the array elements
individually as if it was a normal variable, the format is
name[index].
• For the array int mark[5], each element is referred as
• mark[0] mark[1] mark[2] mark[3] mark[4]
• To store the value 75 in the third element of mark, we
could write the following statement: mark[2] = 75;
• To pass the value of the third element of mark to a
variable called a, a = mark[2];
• If we write mark[5], we would be accessing the sixth
element of mark and therefore exceeding the size of the
array.
• In C++ it is syntactically correct to exceed the valid range of
indices for an array.
• This can create problems, since accessing out-of-range
elements do not cause compilation errors but can cause
runtime errors.
• Related to arrays ‘[ ]’ perform two different tasks:
• one is to specify the size of arrays when they are
declared;
• and the second one is to specify indices for concrete
array elements.
• int billy[5]; // declaration of a new array
• billy[2] = 75; // access to an element of the array.
– Assigning values to array once they have already been
declared is not possible.
– That is we are not able to copy blocks of data with an
assignment operation because an array is a constant
pointer pointing to a block of memory. E.g: int a[3];
a={1,2,3}  is invalid.
– Some valid operations with arrays:
– mark[0] = a;
– mark [a] = 75;
– b = mark [a+2];
– mark [mark [a]] = mark [2] + 5;
– Example: //Program to add the elements in an array
#include <iostream.h>
int mark[] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{result += mark[n];
}
cout << result;
return 0;
}
• Array may have several dimensions.
1) One-dimensional
2) Two-dimensional.
1. One-Dimensional Array: This is also called as a
vector or list.
• General form : Type-specifier Identifier-name
[size];
• Eg.: int a[10]; a[0],a[1],a[2],………..,a[9]
• float b[10]; Declares b as an array containing
maximum of 10 real elements.
• Arrays can be initialized at the time of declaration
Eg. int i[5] = {1,2,3,4,5};
• Character arrays hold the strings.
• Format: char array-name [size] = ‘string’;
• Eg., char b[7] = { ‘w’,’e’,’l’,’c’,’o’,’m’,’e’};
• Program 1: To find maximum number in an array.
// to find the maximum element.
#include<iostream.h>
void main()
{
int a[5], i, max;
cout<<”Enter 5 numbers \n”; // inputting the array elements
for( i=0; i<5; i++ )
cin>>a[ i ];
max = a[0]; // searching for the largest element.
for (i=1; i<5; i++)
if (max < a[ i ])
max = a [ i ];
// print the maximum element in the list.
cout << “ Maximum element in the list is : “ << max;
}
2. Two-dimensional arrays:
• This is an array of one-dimensional arrays.
• It can store table of values.
• It is also called as matrix of elements.
• General form: type-specifier array-name [row-size]
[column-size];
• The element declaration here is also done with ‘zero origin
subscript’.

• Thus, an array a[3][3] will have


• a[0][0] a[0][1] a[0][2] This may be called as Table or
Matrix as they store
• a[1][0] a[1][1] a[1][2] table of values in rows &
columns.
• a[2][0] a[2][1] a[2][2]
• This can also be initialized by following
declaration.
• int a[2][3], b[3][3];
• Program 4: For a two-dimensional array 3x3 find
(1) sum of all elements.
(2)row-wise sum.
(3)Column –wise sum.
// To sum elements row-wise.
for(i=0; i<m; i++)
{
rsum = 0;
for(j=0; j<n; j++)
rsum += a[i][j];
cout<<"row number:"<<(i+1)<<"\t row sum =
"<<rsum<<" \n";
}
// To sum column-wise
for(j=0; j<n; j++)
{
csum=0;
for(i=0; i<m; i++)
csum += a[i][j];
cout<<"column number:"<<(j+1)<<"\tcolumn sum=
"<<csum<<"\n";
}}
// To find sum of matrix elements.
#include<iostream.h>
main()
{
int a[10][10], i, j, sum, rsum, csum, m, n;
cout <<”enter the order of matrix \n”;
cin>>m>>n;
cout<<”enter the elements of the matrix one by one \n”;
for(i=0; i<m; i++)
for(j=0; j<n; j++)
cin>>a[ i ][j];
• //to sum all elements of matrix.
sum = 0;
for(i=0; i<m; i++)
for(j=0; j<n; j++)
sum += a[i][j];
cout<<”sum of the elements of the matrix is :
“<<sum;
• Arrays as Parameters
– To pass an array to a function as a parameter.
– In C++ it is not possible to pass a complete block of
memory by value as a parameter to a function, but we
can pass its address.
– In practice this has almost the same effect and it is a
much faster and more efficient operation.
– In order to accept arrays as parameters the only thing
that we have to do when declaring the function is to
specify in its parameters the element type of the array,
an identifier and a pair of void brackets [].
– E.g: void procedure (int arg[]): accepts a parameter
of type "array of int" called arg.
– In order to pass to this function an array declared
as:
– int myarray [40];
– it would be enough to write a call like this:
– procedure (myarray); where name of the array is
the address of the array.
 Example program: // arrays as parameters

#include <iostream>
void printarray (int arg[], int length)
{ for (int n=0; n<length; n++)
cout << arg[n] << " ";
cout << "\n"; }
int main ()
{ int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0;}
 The first parameter (int arg[]) accepts any array
whose elements are of type int, whatever be its
length.
 A second parameter is included that tells the
function the length of each array that we pass to it
as its first parameter.
 This allows the for loop that prints out the array to
know the range to iterate in the given array without
going out of range.
– In a function declaration it is also possible to
include multidimensional arrays.
2. STRINGS
• A String is an array of characters i.e., they are
defined between the single quotes.
• A string is a character array terminated by a null
character.
• Null character is specified as ‘ \0 ’.
• So, the size should be equal to maximum no. of
characters in the string plus one.
• Eg: char name [5] = { ‘j’ , ‘o’, ‘n’, ‘y’, ‘\0’}
• Declaration of string variable:
• char string-name [size] { Size — No. of characters in the
String-name }
• Eg., char sname[30],country[40];
• Reading strings: cin operator can be used to read a string
eg., char name[50];
• cin>>name; — terminates when first blank character is
encountered.
• Thus, usually we use a new command to read entire line
• cin.getline(name,50); — reads entire string until
terminated by the ----enter key or 49 characters are
read.
• Strings are in fact sequences of characters & so
can represent them as plain arrays of char elements.
• For example char jenny [20]; is an array that can
store up to 20 elements of type char.
• In this array we can store sequences of characters up
to 20 characters long or shorter sequences.
• Therefore, since the array of characters can store
shorter sequences than its total length, a special
character is used to signal the end of the valid
sequence:
• the null character, whose literal constant can be written as
'\0'.
• Our array of 20 elements of type char, called jenny, can be
represented storing the characters sequences "Hello" and
"Merry Christmas“.
• As: Notice how after the valid content a null character ('\0')
has been included in order to indicate the end of the
sequence.
• The panels in gray color represent char elements with
undetermined values.
Initialization of Null-terminated Character Sequences
I. To initialize an array of characters with some predetermined sequence
of characters
1. We declared an array of 6 elements of type char initialized with the
characters that form the word "Hello" plus a null character '\0' at the
end.
a. char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
2. Using string literals:
• By enclosing the text to become a string literal between double quotes
(").
• For example: "the result is: " is a constant string literal. So string
literals enclosed between double quotes always have a null character ('\
0') automatically appended at the end.
a. char myword [] = "Hello";
Using Null-terminated Sequences of Characters
– Null-terminated sequences of characters are the
natural way of treating strings in C++, so they can
be used as such in many procedures.
– For example, cin and cout support null-terminated
sequences as valid containers for sequences of
characters,
– so they can be used directly to extract strings of
characters from cin or to insert them into cout.
Eg. #include <iostream>
int main ()
{ char question[] = "Please, enter your first name: ";
first array ‘question’ the size was
char yourname [80]; implicitly defined by the length of
cout << question; the literal constant initialized.
While for array ‘yourname’ we
cin >> yourname; have explicitly specified that it has
a size of 80 chars.
cout << “hello” << yourname << "!";
return 0;
}
– Sequences of characters stored in char arrays can
easily be converted into string objects just by using the
assignment operator:
– string mystring;
– char mychar[]="some text";
• mystring = mychar;
String handling functions (string.h file to be included)
a) Length of a string (strlen): defines the length or
number of characters in the specified string.
//Program to implement strlen function:
#include<iostream.h>
#include<string.h>
main()
{
char name[80];
int a;
cout<<” Enter the string \n”;
cin>>name;
a= strlen(name);
cout<<” \n length of string is “<<a;
}
b) String Concatenation (strcat):
This function adds 2 strings & places in the first
string.
i.e., the function appends the second string to the
first.
• Program to test the strcat function.
#include<iostream.h>
#include<string.h>
main() {
char n1[100], n2[50];
int i, c;
cout<<” enter the first string \n”;
cin>>n1;
cout<<”Enter the second string \n”;
cin>>n2;
strcat(n1,n2);
cout<<” Concatenated strings are :”<< n1;
}
Activity :suppose
• N1= “world”;
• N2 =“hello”
• strcat(n1,n2); ???
c) Copying two strings (strcpy):
This will assign the contents of one string or character
array to the string variable.
Eg. strcpy(n, "Ethiopia") Stores the character array
’Ethiopia’ in string n.
• strcpy(n1,n2) Stores the contents of n2 to n1 erasing the
contents of n1 if any.
d) Comparing two strings (strcmp):
• This function is used to compare two strings.
• This compares the ASCII values of the strings.
For example strcmp(s1,s2) will return:
(i) Zero if s1 & s2 are equal.
(ii) Positive value if s1>s2.
(iii) Negative value if s1<s2.
• The comparison is done on their ASCII values.
• [viz., ASCII value of A=65, Z=90, a=97, z=122]
e) Reversing the String (strrev):
• This function is used to reverse the given string.
Summary:
• One-dimensional array
• Multi-dimensional array
• String

You might also like