0% found this document useful (0 votes)
11 views42 pages

Chapter 6

Chapter Six of the document covers arrays and strings in C++. It discusses array initialization, multidimensional arrays, passing arrays as parameters, and string handling, including initialization and manipulation functions. Key concepts include the use of indices, the null character for strings, and various methods for assigning values to strings.

Uploaded by

bayabayecha
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)
11 views42 pages

Chapter 6

Chapter Six of the document covers arrays and strings in C++. It discusses array initialization, multidimensional arrays, passing arrays as parameters, and string handling, including initialization and manipulation functions. Key concepts include the use of indices, the null character for strings, and various methods for assigning values to strings.

Uploaded by

bayabayecha
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/ 42

Computer Programming

[ECEg-1052]

Chapter Six:
Arrays and Strings

Compiled by Amanuel Z.(MSc.)


Outline
 Arrays initialization and value accessing
 Multidimensional Arrays
 Arrays as parameters
 String initialization and value assignment
 Functions for string manipulation
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:

3
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];

4
Cont’d...
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.

5
Cont’d...
 If in the global scope we declare:
int billy [5];
every element of billy will be set initially 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 { }.

6
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 square brackets [ ].

7
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 { }:
Example
int billy [] = { 16, 2, 77, 40, 12071 };

8
Cont’d...
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:

9
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

10
Cont’d...
// arrays example Output: 12206
#include <iostream>
using namespace std;
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;
}

11
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];

12
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];

13
Cont’d...
Initializing Multidimensional Arrays
 The only prerequisite is a willingness to type a lot of
braces and commas.
For example:
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };

14
Cont’d...
// To find sum of matrix elements. Output:
#include <iostream> enter the order of matrix
2
using namespace std;
2
int main(){ enter the elements of the
int a[10][10], i, j, sum, m, n; matrix one by one
cout <<"enter the order of matrix \n"; 45
23
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];
15
Cont’d...
//to sum all elements of matrix. Output:
sum = 0; sum of the elements of
the matrix is : 14
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;
}

16
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)

17
Cont’d...
// multidimensional array // pseudo-multidimensional array
#include <iostream> #include <iostream>
using namespace std; using namespace std;
#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) *
(m+1);
return 0;
}
} return 0;
}
18
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 modifications to the program.

19
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.

20
Cont’d...

In order to accept 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[])

Accept a parameter of type "Array of int" called arg.

21
Cont’d...

In order to pass to function an array declared as:
int myarray [40];

It would be enough to write a call like this:
procedure (myarray);

22
Cont’d...
// arrays as parameters Output
#include <iostream> 5 10 15
using namespace std; 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;
}
23
Cont’d...
 As you can see, the first argument (int arg[]) accept any
array of type int, whatever 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.

24
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 each additional dimension.

25
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.
26
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'.

For example, jenny could store at some moment in a program
either the string of characters "Hello" or the string "Merry
christmas".


Notice: After the valid content a null character ('\0') is included
in order to indicate the end of the string.

The panels in gray color reperesent indeterminate values.
27
Cont’d...
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']

28
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' };

29
Cont’d...
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';

30
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");

31
Cont’d...
// setting value to string Output
Abe
#include <iostream>
#include <cstring>
using namespace std;
int main (){
char szMyName [20];
strcpy (szMyName,"Abe ");
cout << szMyName;
return 0;
} 32
Cont’d...
// setting value to string
Output
#include <iostream>
Abe
#include <cstring>
using namespace std;
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,"Abe ");
cout << szMyName;
return 0;
} 33
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').

34
Cont’d...
// cin with strings Output
#include <iostream> What's your name?
using namespace std; Abe Kebe

int main (){ Hello Abe Kebe.


Which is your favourite team?
char mybuffer [100];
Walliya
cout << "What's your name? ";
I like Walliya too.
cin.getline (mybuffer,100);
cout << "Hello " << mybuffer << ".\n";
cout << "Which is your favourite team? ";
cin.getline (mybuffer,100);
cout << "I like " << mybuffer << " too.\n";
} 35
Cont’d...
4. Using cin with the extraction operator (>>)
For example,
cin >> mybuffer;

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.

36
Cont’d...
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.

37
Cont’d...
// cin and ato* functions Output
#include <iostream> Enter price: 2.75
#include <stdlib.h> Enter quantity: 21
using namespace std; 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;
} 38
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, char src);

Appends src string at the end of dest string. Returns dest.
strcmp:
int strcmp (const char string1, char string2);

Returns a value < 0 if string1 is less than string2

Returns 0 if string1 and string2 are the same

Returns a value > 0 if string1 is greater than string2

39
Cont’d...
strcpy:
char strcpy (char dest, char src);

Copies the content of src to dest. Returns dest.
strlen:
int strlen (char string);

Returns the length of the string string, excluding the null
character.

40
Example
#include <iostream> Output
#include <cstring> strcpy(str3, str1):Hello
using namespace std; strcat(str1, str2):HelloWorld
int main () { strlen(str1) : 10
char str1[10] = "Hello"; 72
char str2[10] = "World";
char str3[10];
int len ;
strcpy( str3, str1); // copy str1 into str3
cout << "strcpy( str3, str1) : " << str3 << endl;
strcat( str1, str2); // concatenates str1 and str2
cout << "strcat( str1, str2): " << str1 << endl;
len = strlen(str1);
// total lenghth of str1 after concatenation
cout << "strlen(str1) : " << len << endl;
int comp=strcmp(str1, str2);
cout<<comp;
}
41
Thank You !

42

You might also like