0% found this document useful (0 votes)
14 views44 pages

chapter 06 Arrays and strings

Chapter Six of the Fundamentals of Programming discusses arrays and strings in C++. It covers array initialization, value accessing, multidimensional arrays, passing arrays as parameters, and string manipulation techniques. Key concepts include the declaration of arrays, initialization methods, and functions for string operations.

Uploaded by

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

chapter 06 Arrays and strings

Chapter Six of the Fundamentals of Programming discusses arrays and strings in C++. It covers array initialization, value accessing, multidimensional arrays, passing arrays as parameters, and string manipulation techniques. Key concepts include the declaration of arrays, initialization methods, and functions for string operations.

Uploaded by

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

Fundamentals of Programming

[CoEng1112]

Chapter Six:
Arrays and Strings
6.1 Arrays initialization and
value accessing
• Arrays are a series of elements (variables) of the
same type placed consecutively in memory that
can be individually referenced by adding an
index to a unique name. The index value starts
at 0 i.e., first value is referred.
• For example, an array to contain 5 integer
values of type int called billy could be
represented this way:

2
Cont’d
• A typical declaration for an array in C++ is:
type name [elements];
• where
– type is a valid object type (int, float...),
– name is a valid variable identifier and
– the elements field, that is enclosed within
brackets [], specifies how many of these
elements the array contains.
• Example: int billy [5];
3
Initializing arrays
• When declaring an array of local scope
(within a function), if we do not specify
otherwise, 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.

4
Cont’d
• If in the global scope we declare:
int billy [5];
every element of billy will be set initialy to
0:

• But additionally, when we declare an


Array, we have the possibility to assign
initial values to each one of its elements
using curly brackets { }. 5
Cont’d
• For example:
• int billy [5] = { 16, 2, 77, 40, 12071 };
• this declaration would have created an
array like the following one:

• The number of elements in the array that


we initialized within curly brackets { } must
match the length in elements that we
declared for the array enclosed within 6

square brackets [ ].
Cont’d
• 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 };

7
Access to the values of an Array
• Format:
name[index]
• Following the previous examples in which
billy 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:

8
Cont’d
• At this point it is important to be able to
clearly distinguish between the two uses
that brackets [ ] have related to arrays.

int billy[5]; // declaration of a new


Array (begins with a type name)

billy[2] = 75; // access to an element of


the Array. 9
// arrays example 12206
#include <iostream.h>
int x[] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += x[n];
}
cout << result;
return 0;
}
10
6.2 Multidimensional Arrays
• can be described as arrays of arrays.
• For example, a bidimensional array can be
imagined as a bidimensional table of a
uniform concrete data type.

• jimmy represents a bidimensional array of


3 per 5 values of type int. The way to
declare this array would be:
int jimmy [3][5]; 11
Cont’d

• Multidimensional arrays are not limited to


two indices (two dimensions). They can
contain as many indices as needed,
although it is rare to have to represent
more than 3 dimensions.
• For example:
char century [100][365][24][60][60]; 12
// To find sum of matrix elements. enter the order of
#include<iostream.h> matrix
int main() 2
{ 2
int a[10][10], i, j, sum, m, n; enter the elements
cout <<”enter the order of matrix of the matrix one by
\n”; one
cin>>m>>n; 45
cout<<”enter the elements of the 23
matrix one by one \n”; sum of the elements
for(i=0; i<m; i++) of the matrix is : 14
for(j=0; j<n; j++)
cin>>a[ i ][j];
13
//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;
return 0;
}

14
Cont’d
• Multidimensional arrays are nothing more
than an abstraction, since we can obtain
the same results with a simple array just
by putting a factor between its indices:
int jimmy [3][5]; is equivalent to
int jimmy [15]; (3 * 5 = 15)

15
// multidimensional array // pseudo-multidimensional array
#include <iostream.h> #include <iostream.h>
#define WIDTH 5 #define WIDTH 5
#define HEIGHT 3 #define HEIGHT 3
int jimmy [HEIGHT][WIDTH]; int jimmy [HEIGHT * WIDTH];
int n,m; int n,m;
int main () int main ()
{ {
for (n=0;n<HEIGHT;n++) for (n=0;n<HEIGHT;n++)
for (m=0;m<WIDTH;m++) for (m=0;m<WIDTH;m++)
{ jimmy[n][m]=(n+1)*(m+1); {
} jimmy[n * WIDTH + m] = (n+1) *
return 0; (m+1);
} }
return 0;
}
16
Cont’d
• We have used defined constants (#define)
to simplify possible future modifications of
the program, for example, in case that we
decided to enlarge the array to a height of
4 instead of 3 it could be done by
changing the line:
#define HEIGHT 3 to
#define HEIGHT 4
• with no need to make any other
17
modifications to the program.
6.3 Arrays as parameters
• At some moment we may need to pass an
array to a function as a parameter. In C++
is not possible to pass by value a
complete block of memory as a parameter
to a function, even if it is ordered as an
array, but it is allowed to pass its address.
This has almost the same practical effect
and it is a much faster and more efficient
operation.
18
Cont’d
• In order to admit arrays as parameters the
only thing that we must do when declaring
the function is to specify in the argument
the base type for the array, an identifier
and a pair of void brackets []. For example,
the following function:
void procedure (int arg[])
• admits a parameter of type "Array of int"
called arg.
19
Cont’d
• 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);

20
// arrays as parameters 5 10 15
#include <iostream.h> 2 4 6 8 10
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; 21

}
Cont’d
• As you can see, the first argument (int
arg[]) admits any array of type int,
wathever its length is. For that reason we
have included a second parameter that
tells the function the length of each array
that we pass to it as the first parameter.
This allows the for loop that prints out the
array to know the range to check in the
passed array.
22
Cont’d
• In a function declaration is also possible to
include multidimensional arrays. The
format for a tridimensional array is:
base_type[][depth][depth]
• For example,
void procedure (int myarray[][3][4])
• Notice that the first brackets [] are void
and the following ones are not. Because
the compiler must be able to determine
within the function which is the depth of
23
each additional dimension.
6.4 String initialization and
value assignment
Strings
• In C++ there is no specific elemental
variable type to store strings of characters.
In order to fulfill this feature we can use
arrays of type char, which are successions
of char elements.
For example, the following array (or string of
characters):
char jenny [20];
• can store a string up to 20 characters long.
Cont’d

• The array of characters can store shorter


strings than its total length, a convention
has been reached to end the valid content
of a string with a null character, whose
constant can be written 0 or '\0'.
– For example, jenny could store at some
moment in a program either the string of
characters "Hello" or the string "Merry
christmas".
Cont’d

• Notice how after the valid content a null


character ('\0') it is included in order to
indicate the end of the string. The panels in
gray color represent indeterminate values.
Initialization of strings
• we could initialize the string mystring with
values by either of these two ways:
char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char mystring [] = "Hello";
In both cases the array or string of
characters mystring is declared with a
size of 6 characters (elements of type
char).[including the null character '\0']
Cont’d
• We can "assign" a multiple constant to an
Array only at the moment of initializing it.
• The following are not valid for arrays:
mystring = "Hello";
mystring[] = "Hello";
mystring = { 'H', 'e', 'l', 'l', 'o', '\0' };
Assigning values to strings
1) Assign a string of characters to an array
of char using a method like this:
mystring[0] = 'H';
mystring[1] = 'e';
mystring[2] = 'l';
mystring[3] = 'l';
mystring[4] = 'o';
mystring[5] = '\0';
Cont’d
2) Using strcpy function
• strcpy (string copy) is a function defined
in the cstring (string.h) library and format
is:
strcpy (string1, string2);
This does copy the content of string2 into
string1.
Example: strcpy (mystring, "Hello");
// setting value to string Abebe
#include <iostream.h>
#include <string.h>
int main (){
char szMyName [20];
strcpy (szMyName,“Abebe");
cout << szMyName;
return 0;
}
// setting value to string Abebe
#include <iostream.h>
void setstring (char szOut [ ], char szIn [
])
{
int n=0;
do {
szOut[n] = szIn[n];
} while (szIn[n++] != '\0');
}
int main ()
{
char szMyName [20];
setstring (szMyName,“Abebe");
cout << szMyName;
return 0;
}
Cont’d
3) Using cin.getline
• Format is :
cin.getline ( char buffer[ ], int length, char delimiter = ' \n');
Where
buffer is the address of where to store the input (like
an array, for example),
length is the maximum length of the buffer (the size of
the array) and
delimiter is the character used to determine the end of
the user input, which by default - if we do not include
that parameter - will be the newline character ('\n').
// cin with strings
#include <iostream.h>
int main ()
{
char mybuffer [100];
cout << "What's your name? ";
cin.getline (mybuffer,100);
cout << "Hello " << mybuffer << ".\n";
cout << "Which is your favourite team? ";
cin.getline (mybuffer,100);
cout << "I like " << mybuffer << " too.\n";
return 0;
}
// cin with strings What's your name?
#include <iostream.h> Juan
Hello Juan.
int main ()
Which is your favourite
{ team? Inter Milan
char mybuffer [100]; I like Inter Milan too.
cout << "What's your name? ";
cin.getline (mybuffer,100);
cout << "Hello " << mybuffer <<
".\n";
cout << "Which is your favourite
team? "; cin.getline
(mybuffer,100);
cout << "I like " << mybuffer << "
too.\n"; return 0;
}
Cont’d
4) Using cin with the extraction operator (>>)
For example,
cin >> mybuffer;
limitations it has not:
• It can only receive single words (no complete
sentences) since this method uses as a delimiter
any occurrence of a blank character, including
spaces, tabulators, newlines and carriage
returns.
• It is not allowed to specify a size for the
buffer. That makes your program unstable in
case the user input is longer than the array that
will host it.
Converting strings to other types

• The cstdlib (stdlib.h) library provides


three useful functions for this purpose:
atoi: converts string to int type.
atol: converts string to long type.
atof: converts string to float type.
// cin and ato* functions
#include <iostream.h>
#include <stdlib.h>
int main ()
{
char mybuffer [100];
float price;
int quantity;
cout << "Enter price: ";
cin.getline (mybuffer,100);
price = atof (mybuffer);
cout << "Enter quantity: ";
cin.getline (mybuffer,100);
quantity = atoi (mybuffer);
cout << "Total price: " << price*quantity;
return 0;
}
// cin and ato* functions Enter price: 2.75
#include <iostream.h> Enter quantity: 21
#include <stdlib.h> Total price: 57.75
int main ()
{
char mybuffer [100];
float price;
int quantity;
cout << "Enter price: ";
cin.getline (mybuffer,100);
price = atof (mybuffer);
cout << "Enter quantity: ";
cin.getline (mybuffer,100);
quantity = atoi (mybuffer);
cout << "Total price: " <<
price*quantity;
return 0;
}
6.5 Functions for string
manipulation
• The cstring library (string.h) defines many
functions to perform manipulation operations
with C-like strings (like already explained strcpy).
strcat:
char* strcat (char* dest, const char* src);
 Appends src string at the end of dest string.
Returns dest.
strcmp:
int strcmp (const char* string1, const char*
string2);
 Compares strings string1 and string2. Returns 0
is both strings are equal.
Cont’d
strcpy:
char* strcpy (char* dest, const char* src);
Copies the content of src to dest. Returns
dest.
strlen:
size_t strlen (const char* string);
Returns the length of string.
NOTE: char* is the same as char[]

You might also like