0% found this document useful (0 votes)
73 views46 pages

Chapter 5 C++ Array

Uploaded by

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

Chapter 5 C++ Array

Uploaded by

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

CHAPTER 5

ARRAYS, POINT-
ERS AND STRINGS
ARRAYS
ARRAYS
 An array allows you to store and work with mul-
tiple values of the same data type.
 An array works like a variable that can store a
group of values, all of the same type.
 An array must be declared before it is used.
 A typical declaration for an array in C++ is:
type name [Size];
 where type is a valid object type (int, float...),
 name is a valid variable identifier and the
 Size field, that is enclosed within brackets [ ], speci-
fies how many of these elements the array contains.
… ARRAYS
 Here is an example of an array of integers:
int hours[6];
 The name of this array is hours.
 The number inside the brackets is the array’s size
declarator.
 It indicates the number of elements, or values, the array can
hold.
 The hours array can store six integer elements.
 This is depicted in the following figure.
… ARRAYS
 An array’s size declarator must be a constant in-
teger expression with a value greater than zero.
const int SIZE = 6;
int hours[SIZE];
 Arrays of any data type can be defined.
 The following are all valid array definitions:
float temperature[100]; // Array of 100 floats
char letter[26]; // Array of 26 characters
long unit[50]; // Array of 50 long integers
double size[1200]; // Array of 1200 doubles
Accessing Array Elements
 The format is the following:
name[index]
 The individual elements of an array are assigned unique
subscripts.
 Subscript numbering in C++ always starts at zero.
 The subscript of the last element in an array is array size
minus one.
 This means that in the array int hours[6];
 the element hours[6] does not exist.
 The last element in the array is hours[5].
… Accessing Array Elements
 Assume the following two arrays have been defined.
int doctorA[5]; // Holds the number of patients seen by Dr. A on each of 5
days.
int doctorB[5]; // Holds the number of patients seen by Dr. B on each of 5
days.
 The following are all legal assignment statements.
doctorA[0] = 31; // doctorA[0] now holds 31.
doctorA[1] = 40; // doctorA[1] now holds 40.
doctorA[2] = doctorA[0]; // doctorA[2] now also holds
31.
doctorB[0] = doctorA[1]; // doctorB[0] now holds 40.
 However, the following statements are not legal.
doctorA = 152; // Illegal!
doctorB = doctorA; // Illegal!
… Accessing Array Elements
 For example, consider the following array:
int billy [] = { 16, 2, 1, 40, 12 };
 To store the value 5 in the third element of billy:
billy[2] = 5;
 To pass the value of the third element of billy to the variable a, we
could write:
a = billy[2];
 The following are valid operations with arrays:
// declaration of a new Array (begins with a type name)
int billy[5];
// access to an element of the Array.
billy[2] = 5;
billy[0] = a;
billy[a] = 75;
b = billy [a+2];
billy[billy[a]] = billy[2] + 5;
… Accessing Array Elements
 The following program demonstrates how we can access array ele-
ments and perform operations using those elements.
#include <iostream.h>
int billy [ ] = {10, 20, 30, 400, 12000};
int n, result = 0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
result += billy[n];
cout << result;
return 0;
}
 Output:
12460
Array Initialization
 Arrays may be initialized when they are defined or with separate as-
signment statements.
 By writing separate assignment statements for the individual ele-
ments of an array:
const int NUM_MON = 12;
int days[NUM_MON];
days[0] = 31; // January
days[1] = 28; // February
……………..
days[9] = 31; // October
days[10] = 30; // November
days[11] = 31; // December
 By using an initialization list, all the elements of the array can be
easily initialized when the array is created.
 For example: the following statement defines the days array and ini-
tializes it with the values:
int days[NUM_MON] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
… Array Initialization
 For example, consider the following pro-
gram segment.
const int NUM_MON = 12;
int days[NUM_MON] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for (int month = 0; month < NUM_MON; month++)
{
cout << "Month " << (month + 1) << " has ";
cout << days[month] << " days.\n";
}
Partial Array Initialization
 An initialization list cannot have more values than the ar-
ray has elements, but it may have fewer values than
there are elements.
 i.e. C++ does not require a value for every element.
 It’s possible to only initialize some part of an array, such
as
int numbers[7] = {1, 2, 4, 8};
 This definition only initializes the first four elements of a seven
element array:
… Partial Array Initialization
 If an array is partially initialized, the uninitialized elements will be set
to zero for numeric arrays or to the null character for character ar-
rays.
 The following program segment shows the contents of the numbers
array after it is partially initialized.
const int SIZE = 7;
int numbers[SIZE] = {1, 2, 4, 8}; // Initialize the first 4 elements.
for (int index = 0; index < SIZE; index++)
cout << numbers[index] << " “ << endl;
 This fragment displays the contents of the array as follows:
1248000
 If you leave an element uninitialized, you must leave all the ele-
ments that follow it uninitialized as well.
 For example, the following is not legal:
int array[6] = {2, 4, , 8, , 12}; // NOT Legal!
Implicit Array Sizing
 It’s possible to define an array without specifying its size,
providing an initialization list that includes a value for ev-
ery element.
 C++ automatically makes the array large enough to hold
all the initialization values.
 For example, the following definition creates an array
with five elements:
double ratings[] = {1.0, 1.5, 2.0, 2.5, 3.0};
 Because the size declarator is omitted, C++ counts the
number of items in the initialization list and gives the ar-
ray that many elements.
 Note: You must specify an initialization list if you leave
out the size declarator. Otherwise, C++ doesn’t know
how large to make the array.
Processing Array Contents
 For example, the following statement multiplies hours[3] by the vari-
able rate:
pay = hours[3] * rate;
 The following are examples of pre-increment and post-increment
operations on array elements:
int score[5] = {7, 8, 9, 10, 11};
++score[2]; // Pre-increment operation on the value in score[2]
score[4]++; // Post-increment operation on the value in score[4]
 Array elements can also be used in relational expressions.
 For example, the following if statement tests cost[20] to deter-
mine if it is less than cost[0]:
if (cost[20] < cost[0])
 And the following statement sets up a while loop to iterate as
long as value[place] does not equal 0:
while (value[place] != 0)
Processing Strings
 Strings are internally stored as arrays of characters.
 They are different from other arrays in that the elements can either be
 treated as a set of individual characters or
 can be used as a single entity.
 The following sample code defines a character object and treats it as a sin-
gle entity, inputting it and displaying it as a single unit.
char name[10];
cout << "Enter your name: ";
cin >> name;
cout << "Hello, " << name << endl;
 We can process the string character by character.
 If "Warren" were entered, for example, the statement
cout << name[0]; would print the letter W,
cout << name[1]; would print the letter a, and so forth.
Multidimensional
Arrays
Two-Dimensional Arrays
 An array is useful for storing and working with a set of
data.
 A 2D-array is useful for storing multiple sets of data.
 It’s best to think of a two-dimensional array as a table
having rows and columns of elements.
 To define a 2D-array, two size declarators are required:
 the first one is for the number of rows and
 the second one is for the number of columns.
 For processing the information in a two-dimensional ar-
ray, each element has two subscripts:
 one for its row and
 another for its column.
… Two-Dimensional Arrays
 In the score array, the elements in row 0 are referenced as:
score[0][0]
score[0][1]
score[0][2]
score[0][3]
 The elements in row 1 are
score[1][0]
score[1][1]
score[1][2]
score[1][3]
 And the elements in row 2 are
score[2][0]
score[2][1]
score[2][2]
score[2][3]
… Two-Dimensional Arrays
 For example, the following statement assigns the value 92.25 to the element at row 2,
column 1 of the score array:
score[2][1] = 92.25;
 And the following statement displays the element at row 0, column 2:
cout << score[0][2];
 When initializing a two-dimensional array, it helps to enclose each row’s initialization list in a set
of braces. Here is an example:
int hours[3][2] = {{8, 5}, {7, 9}, {6, 3}};
 The same statement could also be written as
int hours[3][2] = {{8, 5},
{7, 9},
{6, 3}};
 In either case, the values are assigned to hours in the following manner:
hours[0][0] is set to 8
hours[0][1] is set to 5
hours[1][0] is set to 7
hours[1][1] is set to 9
hours[2][0] is set to 6
hours[2][1] is set to 3
… Two-Dimensional Arrays
 The extra braces that enclose each row’s initialization list
are optional.
 Both of the following statements perform the same initial-
ization:
int hours[3][2] = {{8, 5}, {7, 9}, {6, 3}};
int hours[3][2] = {8, 5, 7, 9, 6, 3};
 The braces give you the ability to leave out initializers:
int table[3][2] = {{1}, {3, 4}, {5}};
 In the above array definition:
table[0][0] is initialized to 1,
table[1][0] is initialized to 3,
table[1][1] is initialized to 4, and
table[2][0] is initialized to 5.
 The uninitialized elements, table[0][1] and table[2][1], are
automatically set to zero.
POINTERS
Address (dereference) operator (&)
 The address operator (&) returns the memory address of
a variable.
 Suppose the following variable declaration:
float amount;
 When the address operator (&) is placed in front of a
variable name, it returns the address of that variable.
 Here is an expression that returns the address of the
variable amount:
&amount
 Here is a statement that displays the variable’s ad-
dress on the screen:
cout << &amount;
… Address (dereference) operator (&)
 For example the statement:
ted = &andy;
would assign to variable ted the address of variable andy,
 When preceding the name of the variable andy with the
ampersand (&) character we are talking about its ad-
dress in memory not its content.
 We are going to suppose that andy has been placed in
the memory address 1776 and that we write the follow-
ing:
andy = 25;
fred = andy;
ted = &andy;
… Address (dereference) operator (&)
andy = 25;
fred = andy;
ted = &andy;
 We have assigned:
 to fred the content of variable andy, but
 to ted the address in memory where the value of andy is stored
 The reason is that in the allocation of ted we have pre-
ceded andy with an ampersand (&) character.
 The variable that stores the address of another variable
(like ted in the previous example) is what we call a
pointer.
Pointer Variables
 Pointer variables are often called pointers
 They are designed to hold memory addresses.
 Pointers are special variables that C++ provides
for working with memory addresses.
 Just like int variables are designed to hold and
work with integers, pointer variables are de-
signed to hold and work with addresses.
… Pointer Variables
 The definition of a pointer variable looks like the
following:
int *ptr;
 The asterisk indicates that ptr is a pointer variable.
 The int data type indicates that ptr can be used to
hold the address of an integer variable.
 The declaration statement above would read “ptr
is a pointer to an int.”
 Note: In this definition, the word int does not
mean that ptr is an integer variable.
 Remember, pointers only hold one thing: ad-
dresses.
Declaring Pointer Variables
 It is necessary to specify which data type a pointer points
to when declaring it.
 Therefore, the declaration of pointers follows this form:
type * pointer_name;
 where type is the type of data pointed, not the type of the pointer
itself.
 For example:
int * number;
char * character;
float * greatnumber;
 they are three declarations of pointers.
 The following statement declares the two pointers of the
previous example putting an asterisk (*) for each pointer.
int *p1, *p2;
… Declaring Pointer Variables
 In the following statements:
int x = 25;
int *ptr;
ptr = &x;
 The variable x is an int, while ptr is a pointer to an int.
 The variable x is initialized with 25, while ptr is as-
signed the address of x.
 the variable x is located at memory address 0x7e00
and contains the number 25,
 the pointer ptr contains the address 0x7e00.
 In essence,” ptr “points to the variable x.
Reference (Indirection ) operator (*)
 With pointer variables you can indirectly manipulate data stored in
other variables.
 Using a pointer we can directly access the value stored in the vari-
able pointed by it.
 This is done by preceding the pointer identifier with the reference
operator asterisk (*)
 Therefore, if we write:
andy = 25;
fred = andy;
ted = &andy;
beth = *ted;
 beth would take
the value 25,
since ted is 1776,
and the value pointed
by 1776 is 25.
… Reference (Indirection ) operator (*)
andy = 25;
ted = &andy;
beth = *ted;
 You must clearly differentiate that:
 ted stores 1776,
 *ted refers to the value stored in the address 1776, that is 25.
 Notice the difference of including or not including the reference as-
terisk:
beth = ted; // beth equal to ted ( 1776 )
beth = *ted; // beth equal to value pointed by ted ( 25 )
 Consider the following statements:
andy = 25;
ted = &andy;
all the following expressions are true:
andy == 25 &andy == 1776
ted == 1776 *ted == 25
*ted == andy
… Reference (Indirection ) operator (*)

 Using the expression *ptr is indirectly using the


variable x.
int x = 25;
int *ptr;
ptr = &x;
 The following cout statement displays the value
in x twice:
cout << x << " " << *ptr << endl;
 And the following statement stores 100 in x:
*ptr = 100;
… Reference (Indirection ) operator (*)
 The following program segment demonstrates the use of indirection
operator.
int x = 25;
int *ptr;
ptr = &x; // Store the address of x in ptr
cout << "Here is the value in x, printed twice:";
cout << x << " " << *ptr << endl;
*ptr = 100;
cout << “\nOnce again, here is the value in x:";
cout << x << " " << *ptr << endl;
 The above program segment displays the following:
Here is the value in x, printed twice: 25 25
Once again, here is the value in x: 100 100
… Reference (Indirection ) operator (*)
 The following program demonstrates the ability of a pointer to point
to different variables.
int x = 25, y = 50, z = 75;
int *ptr;
cout << "Here are the values of x, y, and z:\n";
cout << x << " " << y << " " << z << endl;
ptr = &x; // Store the address of x in ptr
*ptr *= 2; // Multiply value in x by 2
ptr = &y; // Store the address of y in ptr
*ptr *= 2; // Multiply value in y by 2
ptr = &z; // Store the address of z in ptr
*ptr *= 2; // Multiply value in z by 2
cout << "Once again, here are the values of x, y, and z:\n";
cout << x << " " << y << " " << z << endl;
 The above program segment displays the following:
Here are the values of x, y, and z: 25 50 75
Once again, here are the values of x, y, and z: 50 100 150
Summary on the two pointer operators
 Note: So far you’ve seen three different uses of the as-
terisk in C++:
 As the multiplication operator, in statements such as
distance = speed * time;
 In the definition of a pointer variable, such as
int *ptr;
 As the indirection operator, in statements such as
*ptr = 100;
 Address or dereference operator(&)
 It is used as a variable prefix and
 can be translated as "address of",
 thus: &variable1 can be read as "address of variable1"
 Reference operator (*)
 It indicates that what has to be evaluated is the content pointed
by the expression considered as an address.
 It can be translated by "value pointed by".
* mypointer can be read as "value pointed by mypointer".
Pointer Initialization
 We can explicitly specify to which variable we want
pointers to point during their declaration,
int number;
int *tommy = &number;
 this is equivalent to:
int number;
int *tommy;
tommy = &number;
 When a pointer assignment takes place we are always
assigning the address where it points to, never the value
pointed.
 At the moment of declaring a pointer, the asterisk (*) in-
dicates only that it is a pointer, not the reference opera-
tor (*).
STRINGS
STRINGS
 Strings of characters allow us to represent successions
of characters, like words, sentences, names, texts.
 Arrays of type char are used to store strings of charac-
ters.
 The data type (char) is used to store a single character
 So arrays are used to store strings of single characters.
 For example, the following array (or string of characters):
char jenny [20];
 can store a string up to 20 characters long.
… STRINGS
 For example, jenny could store either the string of char-
acters "Hello" or "Merry Christmas".
 Since the array of characters can store shorter strings
than its total length, a null character is used to end the
valid content of a string.
 A constant for the null character can be written '\0'.
 We could represent jenny storing the strings of charac-
ters "Hello" and "Merry Christmas" in the following way:
 Null character ('\0') is included to indicate the end of the
string. The panels in gray color represent indeterminate
values.
Initialization of strings
 To initialize a string of characters with predeter-
mined values:
char mystring[ ] = { 'H', 'e', 'l', 'l', 'o', '\
0' };
 mystring is a string of characters (array) of 6 elements
 its type is char
 initialized with the characters that compose Hello plus
a null character '\0'.
 Another way is using constant strings.
char mystring [ ] = { 'H', 'e', 'l', 'l', 'o', '\
0' };
char mystring [ ] = "Hello";
… Initialization of strings
 The assignment of multiple constants like
double-quoted constants (") to arrays are
only valid at the moment when declared.
 Expressions within the code like:
mystring = "Hello";
mystring[ ] = "Hello";
mystring = { 'H', 'e', 'l', 'l', 'o', '\0' };
are not valid for arrays.
… Initialization of strings
 Since the lvalue of an assignment can only be an ele-
ment of an array, it would be valid to 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';
 Generally for assigning values to a string of characters, a se-
ries of functions like strcpy are used.
 strcpy (string copy) is defined in the string.h library and can be
called the following way:
strcpy (string1, string2);
 This does copy the content of string2 into string1.
 For example, the following line assigns the constant string
"Hello" to mystring:
strcpy (mystring, "Hello");
… Initialization of strings
 The following program sets a value to string
#include <iostream.h>
#include <string.h>
int main ()
{
char msg[10];
char myName [20];
strcpy (msg,"Hello");
strcpy (myName,“Alemu");
cout << msg << " " << myName;
return 0;
}
 The above code will display:
Hello Alemu
… Initialization of strings
 Another method to assign values to an array is by using
the input stream (cin).
 The value is assigned by the user during program execution.
 When cin is used with strings of characters it is usually
used with its getline function, that can be called follow-
ing this prototype:
cin.getline ( char buffer[ ], int length, char delimiter = ' \n');
 where buffer is the address of where to store the input (array),
 length is the maximum length of the buffer (the size of the array)
 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').
… Initialization of strings
 The following code repeats whatever you type on your
keyboard using cin.getline:
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";
 The above code will display:
What's your name? Alemu
Hello Alemu.
Which is your favourite team? Inter Milan
I like Inter Milan too.
END OF CHAPTER FIVE
******** THANK YOU********
***** GOOD LUCK *****

You might also like