Вы находитесь на странице: 1из 56

Mechanical Engineering

Department

Computer Programming
(MEng 1052)

Lecture 5

Arrays and Strings


1

Prepared by: Addisu D. & Beza T.

April, 2015

Part I: Arrays

Introduction
An array is used to process a collection of data all of which is

of the same type, such as a list of temperatures or a list of


names.
Suppose we wish to write a program that reads in 5 test scores
and performs some manipulations on these scores.
To retain the 5 scores, we will need something equivalent to 5
variables of type int. But 5 variables are hard to keep track of,
and we may later want to change our program to handle 100
scores; certainly, 100 variables are impractical.
An array is the perfect solution for such kind of situations.
An array behaves like a list of variables with a uniform
naming mechanism that can be declared in a single line of
simple code.

Declaring and Referencing Arrays


In C++, an array consisting of five variables of type int can be

declared as follows:
int score[5];
This declaration is like declaring the following five variables
to all be of type int:
score[0], score[1], score[2], score[3], score[4]
The individual variables that together make up the array are
called indexed variables. They are also sometimes called
subscripted variables or elements of the array.
The number in square brackets is called an index or a
subscript.
In C++, indexes are numbered starting with 0, not starting
with 1 or any other number except 0.

Declaring and Referencing Arrays


The number of indexed variables in an array is called the

declared size of the array, or sometimes simply the size of the


array.
When an array is declared, the size of the array is given in
square brackets after the array name.
The indexed variables are then numbered (also using square
brackets), starting with 0 and ending with the integer that is one
less than the size of the array.
An array can have indexed variables of any type. For example,
to declare an array with indexed variables of type double, simply
use the type name double instead of int in the declaration of the
array.
All the indexed variables for one array are, however, of the same
type. This type is called the base type of the array. Thus, in our
example of the array score, the base type is int.

Declaring and Referencing Arrays


You can declare arrays and regular variables together. For

example, the following declares the two int variables next


and max in addition to the array score:
int next, score[5], max;
Do not confuse the two ways to use the square brackets [ ]
with an array name.
When used in a declaration, such as int score[5]; the number
enclosed in the square brackets specifies how many indexed
variables the array has.
When used anywhere else, the number enclosed in the square
brackets tells which indexed variable is meant. For example,
score[0] through score[4] are indexed variables.

Declaring and Referencing Arrays


The index inside the square brackets need not be given as an

integer constant. You can use any expression in the square


brackets as long as the expression evaluates to one of the
integers 0 through the integer that is one less than the size of
the array.
For example, the following will set the value of score[3]
equal to 99:
int n = 2;
score[n + 1] = 99;
Although they may look different, score[n + 1] and score[3]
are the same indexed variable in the above code. That is
because n + 1 evaluates to 3.
Lets look at the following example
7

Initializing Arrays
An array can be initialized when it is declared. When initializing

the array, the values for the various indexed variables are
enclosed in braces and separated with commas. For example,
int children[3] = {2, 12, 1};
This declaration is equivalent to the following code:
int children[3];
children[0] = 2;
children[1] = 12;
children[2] = 1;
If you list fewer values than there are indexed variables, those
values will be used to initialize the first few indexed variables,
and the remaining indexed variables will be initialized to a zero
of the array base type.
9

Initializing Arrays
The number of elements in the array that we initialized within

curly brackets { } must be equal or less than the length in elements


that we declared for the array enclosed within square brackets [ ].
If we have less number of items for the initialization, the rest will
be filled with zero.
If you initialize an array when it is declared, you can omit the size
of the array, and the array will automatically be declared to have
the minimum size needed for the initialization values.
For example, the following declaration
int b[ ] = {5, 12, 11};
is equivalent to
int b[3] = {5, 12, 11};
When initializing an array, we can provide fewer values than the
array elements. E.g. int a [10] = {10, 2, 3}; in this case the
10
compiler sets the remaining elements to zero.

Partial Array Initialization


When an array is being initialized, C++ does not require a

value for every element

11

Partial Array Initialization


Program Output
Here are the contents of the array:
1
2
4
8
0
0
0

12

Accessing and processing array elements


In any point of the program in which the array is visible we can

13

access individually anyone of its elements for reading or


modifying it as if it was a normal variable.
To access individual elements, index or subscript is used. The
format is the following:
name [ index ]
In c++ the first element has an index of 0 and the last element has
an index, which is one less the size of the array (i.e. arraysize-1).
Thus, from the following declaration,
int day [5];
day[0] is the first element and day[4] is the last element.
For example, to store the value 75 in the third element of the
array variable day a suitable sentence would be:
day[2] = 75; //as the third element is found at index 2

Accessing and processing array elements


To pass the value of the third element of the array variable

day to the variable a , we could write:


a = day[2];
Other valid operations with arrays in accessing and
assigning:
int a=1;
day [0] = a;
day[a] = 5;
b = day [a+2];
day [day[a]] = day [2] + 5;

14

Array Examples

15

16

Program Output
Month
Month
Month
Month
Month
Month
Month
Month
Month
Month
Month
Month

17

1 has 31 days.
2 has 28 days.
3 has 31 days.
4 has 30 days.
5 has 31 days.
6 has 30 days.
7 has 31 days.
8 has 31 days.
9 has 30 days.
10 has 31 days.
11 has 30 days.
12 has 31 days.

18

19

20

21

22

23

24

Two Dimensional Array


The simplest form of multidimensional array is the two

25

dimensional array.
A twodimensional array is, in essence, a list of onedimensional
arrays.
The general form of a twodimensional array declaration is
type name[size1][size2];
Pay careful attention to the declaration. Unlike some other
computer languages, which use commas to separate the array
dimensions, C++ places each dimension in its own set of
brackets. Similarly, to access an element, specify own set of
brackets
Twodimensional arrays are stored in a rowcolumn matrix,
where the first index indicates the row and the second indicates
the column

26

Two Dimensional Array


In preceding example, nums[0][0] will have the value 1,

nums[0][1] the value 2, nums[0][2] the value 3, and so on.


The value of nums[2][3] will be 12. Conceptually, the array
will look like that shown here

Twodimensional arrays are used to create matrix, where

the first index indicates the row and the second indicates
the column
27

28

Part II: Strings

29

Strings
The most common use for one-dimensional arrays is to store

strings of characters.
In C++, a string is defined as a character array terminated by
a null symbol (\0).

To declare an array str that could hold a 10-character string,

one would write:

char str[11];
Specifying the size as 11 makes room for the null at the end

of the string.

30

Strings

31

Declaration of Strings
Similar to declaration of any array

char name[30];
// no initialization
char title [20] = "Le Grande Fromage";
// initialized at declaration
// with a string
char chList [10] = {'a', 'b', 'c', 'd'};
// initialized with list of char
// values

32

Reading a String from the Keyboard


How to read a string entered from the keyboard?
Make an array, that will receive the string, the target of a cin

stream.
The following program reads (part of) a string entered by the
user:

33

Reading a String from the Keyboard


Problem: Entering the string This is a test, the above

program only returns This, not the entire sentence.


Reason: The C++ input/output system stops reading a string
when the first whitespace character is encountered.
Solution: Use another C++ library function, gets( ).

34

Some C++ Library Functions for Strings


C++ supports a range of string-manipulation functions.
The most common are:
strcpy ( ) : copy characters from one string to another

strcat ( ) : concatenation of strings


strlen ( ) : length of a string
strcmp ( ) : comparison of strings

35

String manipulation
strlen (str) = tells the length of a string; the total number

36

of characters in the string.


strcpy (str1, str2) = copies string str2 to string str1.
strcat (st1, str2) = appends string str2 to string st1.
strncat (str1, str2, n) = appends only n characters of str2
to str1.
strrev (str) = reverses the string str.
strcmp (str1, str2) = compares the two strings.
strncmp (str1, str2, n) = compares only the first n
characters of the two strings.

Some C++ Library Functions for Strings


strcpy (to_string, from_string ) String Copy:

37

Some C++ Library Functions for Strings


strlen(string) String Length

strlen(str) returns the length of the string pointed to by str ,

i.e., the number of characters excluding the null terminator.

38

Some C++ Library Functions for Strings


strcat(string_1, string_2) Concatenation of Strings
The strcat ( ) function appends s2 to the end of s1. String s2

is unchanged.

39

Some C++ Library Functions for Strings


Note: The first string array has to be large enough to hold both

strings:

40

Some C++ Library Functions for Strings


strcmp(string_1, string_2) Comparison of Strings
The strcmp(str_1, str_2) function compares two strings and

returns the following result:


str_1 == str_2 : 0
str_1 > str_2 : positive number
str_1 < str_2 : negative number
The strings are compared lexicographically (i.e., according
to dictionary order):
a < aa < aaa < < b < ba < bb < < bz < baa <
< abca < abd < ...

41

42

Some C++ Library Functions for Strings


You also cannot use the operator == in an expression to test

whether two strings are the same.


To test whether two C strings are the same, you can use the
predefined function strcmp. For example:

Note that the function strcmp works differently than you

43

might guess.
The comparison is true if the strings do not match. The
function strcmp compares the characters in the string
arguments a character at a time

Some C++ Library Functions for Strings


If at any point the numeric encoding of the character from

44

c_string1 is less than the numeric encoding of the


corresponding character from c_string2, the testing stops, and
a negative number is returned.
If the character from c_string1 is greater than the character
from c_string2, then a positive number is returned.
If the C strings are the same, a 0 is returned.
The ordering relationship used for comparing characters is
called lexicographic order.
The important point to note is that if both strings are all in
uppercase or all in lowercase, then lexicographic order is just
alphabetic order.

45

46

Arrays of Strings
An array of strings is a special form of a two-dimensional

array.
The size of the left index determines the number of strings.
The size of the right index specifies the maximum length of
each string.
For example, the following declares an array of 30 strings,
each having a maximum length of 80 characters (with one
extra character for the null terminator):
char string_array[30][81];
For accessing an individual string, one simply specifies only

the left index:


firstString = string_array[0];
sixthString = string_array[5];
47

Arrays of Strings
The following example calls the gets ( ) function with the

third string in the array:


gets(string_array[2]);

48

Programming Example_ Functions containing


arrays and strings
Arrays of strings are commonly used for handling tables of

information.
One such application would be an employee database that
stores
the name
telephone number
hours worked per pay period, and
hourly wage.
These data we could store in arrays:

49

char name[20][80]; // employee names


int phone[20]; // phone numbers
float hours[20]; // hours worked
float wage[20]; // wage

50

The full program is shown below


51

52

53

54

Exercises
1.

2.

3.

4.
5.

55

Write a C++ program that accepts 10 integers from the user


and finally displays the smallest value and the largest value.
Write a program that accepts ten different integers from the
user and display these numbers after sorting them in increasing
order.
Write a C++ program that calculates the letter grades of 20
students. The program should accept the mid result and the
final result from the students. Use the appropriate validity
control mechanism to prevent wrong inputs.
Write a C++ program that accepts a word from the user and
then displays the word after reversing it.
Develop a C++ program that accepts the name of a person and
then counts how many vowels the persons name have.

End of course
Thank You!!!

56

Вам также может понравиться