You are on page 1of 54

Chapter 2: Array’s and

Strings
Module outline

▪ Single Dimensional Arrays


▪ Multi-Dimensional Arrays
▪ C-Strings
▪ C-String variables
– String constants
– Reading Embedded blanks
– Reading multiple lines
– Copying a string

2
Single-Dimensional Arrays

▪ Arrays are used to store multiple values in a single variable, instead of


declaring separate variables for each value.
▪ An array is a sequence of objects all of which have the same type. The
objects are called the elements of the array and are numbered
consecutively 0, 1, 2, 3, . . . . These numbers are called index values or
subscripts of the array.
▪ To declare an array, define the variable type, specify the name of the
array followed by square brackets and specify the number of
elements it should store:

3
Array Literals

▪ An array literal is created when we assign values to an array upon its


declaration. This is called initializing an array.
▪ Example:

▪ The array cars has four elements and since we assigned these
elements to it upon declaration it is an array literal.
▪ To create an array of three integers, you could write:

4
Access the Elements of an Array

▪ You access an array element by referring to the index number inside


square brackets [].

▪ Note: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.

5
Change an Array Element

6
Arrays and Loops

▪ You can loop through the array elements with the for loop.
▪ The following example outputs all elements in the cars array:

▪ This example outputs the index of each element together with its
value:

7
Activity 1 (10 mins)

▪ Step 1: create an array named myNumbers that has 5 elements


▪ Step 2: initialize the array with the following numbers 10,20,30,40,50
▪ Step 3: Use a for loop to loop through the array and display the
numbers on the screen
▪ Output:

8
The foreach Loop

▪ There is also a "for-each loop" (introduced in C++ version 11 (2011),


which is used exclusively to loop through elements in an array:

▪ Note: The foreach loop can only be used with Arrays.

9
Activity 2

▪ Use a for each loop to display the numbers in the previous Activity.
▪ Solution:

10
Omit Array size

▪ In C++, you don't have to specify the size of the array. The compiler is smart
enough to determine the size of the array based on the number of inserted
values:

▪ However, the last approach is considered as "good practice", because it will


reduce the chance of errors in your program.

11
Omit Elements on Declaration

▪ It is also possible to declare an array without specifying the elements


on the declaration, and add them later:

12
C++ Array Size

▪ To get the size of an array, you can use the sizeof() operator:

▪ Why did the result show 20 instead of 5, when the array contains 5
elements?
▪ It is because the sizeof() operator returns the size of a type in bytes.
▪ You learned from our Recap lessons that an int type is usually 4 bytes,
so from the example above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.

13
C++ Array size

▪ To find out how many elements an array has, you have to divide
the size of the array by the size of the data type it contains:

14
Activity 3

▪ This is an activity you must complete before you come to the next
class.
▪ Loop through the myNumbers array using the sizeof() function,

15
Passing An Array To A Function

▪ The code that is used to pass an array to a function includes the array’s
element type and its name. This is illustrated in the next example. It
includes two functions that process arrays. In both parameter lists, the
array a[] is declared in the parameter list as double a[].
▪ The actual number of elements has to be passed by means of a
separate integer variable. When a function is passed an array this way,
it is actually passed only the address of the memory cell where the
array starts. This value is represented by the array’s name a. The
function can then change the contents of the array by directly
accessing the memory cells where the array’s elements are stored. So,
although the name of the array is passed by value, its elements can be
changed just as if they had been passed by reference.

16
Example

17
Activity 4

▪ The sum function is a very useful function to work with Arrays.

▪ Your task is to create a program that uses this function to add the first n
elements of an array based on input from the user.

18
Some common errors

▪ Index Out of Range : when working with an array be careful not to


enter an index that is greater than or equal to the size of the array
because the index variable may run far beyond its defined range
without any error being detected by the computer resulting in a
garbage / incorrect output.
▪ Segmentation fault: displayed when the index is so far out of range
that it goes beyond that part of memory allocated to the running
program, This run-time error message means that the system has
tried to access part of memory that lies outside the “segment”
allocated to the process that is currently running.

19
Multi-Dimensional Arrays

▪ A multi-dimensional array is an array of arrays.


▪ To declare a multidimensional array, define the variable type, specify
the name of the array followed by square brackets which specify how
many elements the main array has followed by another set of square
brackets that indicates how many elements the sub-arrays have:
▪ Example:

20
Continued...

▪ As with ordinary arrays, you can insert values with an array literal - a
comma-separated list inside curly braces. In a multi-dimensional
array, each element in an array literal is another array literal.

▪ Each set of square brackets in an array declaration adds


another dimension to an array. An array like the one above is said to
have two dimensions.

21
Continued...

▪ Arrays can have any number of dimensions. The more dimensions an


array has, the more complex the code becomes. The following array
has three dimensions:

22
Access the Elements of a Multi-
Dimensional Array

▪ To access an element of a multi-dimensional array, specify an index


number in each of the array's dimensions.
▪ This statement accesses the value of the element in the first row
(0) and third column (2) of the letters array

Remember that: Array indexes


start with 0: [0] is the first
element. [1] is the second
element, etc.

23
Loop Through a Multi-Dimensional Array

▪ To loop through a multi-dimensional array, you need one loop for


each of the array's dimensions.
▪ The following example outputs all elements in the letters array:

24
Example

This example shows how to


loop through a three-
dimensional array:

25
Why Multi-Dimensional Arrays?

▪ Multi-dimensional arrays are great at representing grids and are


frequently used to store data for mathematic computations, image
processing, and record management.
▪ Example: The following multidimensional array stores student
information from a given table.

26
Activity 5

▪ Loop through the array with student records in the previous example
and display the student’s information.

27
C++ Strings

▪ A string is a sequence of zero or more characters, and


strings are enclosed in double quotation marks.
▪ C++ provides following two types of string
representations −
– The C-style character string.
– The string class type introduced with Standard C++.

▪ Reminder:
– Strings are used for storing text.

▪ To use strings, you must include an additional header file


in the source code, the <string> library:

28
C-String

▪ This string is actually a one-dimensional array of characters which is terminated


by a null character ‘\0’.
▪ It is also known as a null terminated string.
▪ The following declaration and initialization create a string consisting of the
word "Hello". To hold the null character at the end of the array, the size of the
character array containing the string is one more than the number of characters
in the word "Hello.

▪ If you follow the rule of array initialization, then you can write the above
statement as follows −

29
Memory Representation

▪ Actually, you do not place the null character at the end of a string literal.
The C++ compiler automatically places the ‘\0' at the end of the string
when it initializes the array.
30
Example:

▪ The following program contains the different ways of creating a


string.

31
The null character (\0)

▪ The null character indicates the end of the string. Such strings are
called null-terminated strings. 
▪ If you don’t have the null character at the end of a C-string you will
get a garbage output added when you display your output .
▪ Example:
– Remove the \0 element found at the end of the greeting string found on line 8

32
Accepting C-Strings from the user

▪ The entire string may be input as a single object, like


the code below but when doing so we can not accept
white spaces.
▪ The system will copy characters from cin into word
until a white space character is encountered. You
must ensure that word is defined to be a character
string long enough to hold the input.
▪ The entire string may be output as a single object.
The system will copy characters from word to cout
until the NULL character \ o is encountered.

33
Reading embedded blanks

▪ We can also accept input containing


white spaces from the user using the cin
Example:
member function .get().
▪ cin.get(char &ch): Reads a character
from the input and stores it in ch.
▪ If we give cin.get() a second parameter
which is a number we can specify how
many characters we can accept at a time.
▪ We can only use this to read a single line
of text.

34
Reading Multiple lines

▪  To accept multiple lines, we use the getline() function. Which is a pre-
defined function defined in a <string.h> header file used to accept a
line or a string from the input stream until the delimiting character is
encountered.
▪ The cin.getline() function takes three parameters as follows:
– cin.getline(charArray,length,delimiter)

▪ It is possible to omit the delimiting character when calling the


function:
– Cin.getline(charArray,length)

35
Example

36
The <cstring> library

▪ The cstring library is home to various functions :

37
Example:

38
Activity 6

▪ Step one : Create a C-string called myWords that has a size of 150.
▪ Step two : Accept multi line input from the user and store it in
myWords. Your Delimiter should be the number 5.
▪ Step three: Display what is stored in my words as an output.
▪ Step four: Display what is stored in myWords reversed as an output

39
The String class

▪ A string variable contains a collection of characters surrounded by


double quotes:

▪ To use strings, you must include an additional header file in the


source code, the <string> library:

40
String Constants

▪ To declare a string constant add a const keyword before declaring a


string.
▪ Note: Constants can’t be changed one they have been assigned a
value.
▪ Example:

41
Activity 6

▪ Step 1: Create a C-string variable called myName.


▪ Step 2: Accept the user’s name
▪ Step 3 display the user’s name:
▪ Output:

42
String Concatenation

▪ The + operator can be used between strings to add them together to


make a new string. This is called concatenation:

43
Append a String

▪ A string in C++ contains functions that can perform certain


operations on strings. For example, you can also concatenate strings
with the append() function:

44
C++ Numbers and Strings

▪ WARNING!
▪ C++ uses the + operator for both addition and
concatenation.
▪ Numbers are added. Strings are concatenated.

45
C++ String Length

▪ To get the length of a string, use the length() function:

▪ You might see some C++ programs that use the size() function to get
the length of a string. This is just an alias of length(). It is completely
up to you if you want to use length() or size():

46
Access Strings

▪ You can access the characters in a string by referring to its index


number inside square brackets [].
▪ This example prints the first character in myString:

▪ Note: String indexes start with 0: [0] is the first character. [1] is the
second character, etc.

47
Change String Characters

▪ To change the value of a specific character in a string, refer to the


index number, and use single quotes:

48
C++ Special Characters

▪ Because strings must be written within quotes, C++ will


misunderstand this string, and generate an error:

▪ The solution to avoid this problem, is to use the backslash escape


character.
▪ The backslash (\) escape character turns special characters into string
characters:

49
Example

Note:

50
Reading whitespaces and Multiple lines

▪ It is possible to use the extraction operator >> on cin to display a


string entered by a user.
▪ However, cin considers a space (whitespace, tabs, etc) as a
terminating character, which means that it can only display a single
word (even if you type many words):

51
Using getline()

▪ we often use the getline() function to read a line of text. It takes cin
as the first parameter, and the string variable as second.

▪ The default delimiting character is \n .

52
Reading multiple lines

▪ We can also use getline() to read multiple lines by specifying a


delimiting character.

53
Activities

▪ Write a C++ program to reverse a given string.


– Sample Input: Abebe
– Sample Output: ebebA

▪ Write a C++ program to capitalize the first letter of each word of a


given string. Words must be separated by only one space.
– Sample Input: cpp string exercises
– Sample Output: Cpp String Exercises

54

You might also like