SlideShare a Scribd company logo
CHAPTER 5
ARRAYS, POINTERS AND
STRINGS
ARRAYS
ARRAYS
• An array allows you to store and work with multiple 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 [ ], specifies
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 integer
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 elements 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
assignment statements.
• By writing separate assignment statements for the individual elements 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 initializes 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 program 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 array 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 arrays.
• 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:
1 2 4 8 0 0 0
• If you leave an element uninitialized, you must leave all the elements 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 every
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 array
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 variable
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 determine 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 single
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 array, 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
initialization:
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
in C++ pointer are a variables that stores the
memory addresses of other variables.
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 address 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 address 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 following:
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 preceded
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 designed 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: addresses.
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 assigned 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 variable
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 asterisk:
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 asterisk 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 (*) indicates
only that it is a pointer, not the reference operator (*).
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 characters.
• 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 characters
"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 characters
"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
predetermined 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 element 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 series 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 following 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.
THANK YOU

More Related Content

PPT
PF Lecture 9.ppt hakakbshisokwb jaiksnsjomabhj
PPTX
PPTX
Chapter-Five.pptx
PPTX
Yash Bhargava Array In programming in C
PPTX
Arrays & Strings
PPT
Array
PPT
PPTX
6 arrays injava
PF Lecture 9.ppt hakakbshisokwb jaiksnsjomabhj
Chapter-Five.pptx
Yash Bhargava Array In programming in C
Arrays & Strings
Array
6 arrays injava

Similar to CHAPTER-5.ppt (20)

PDF
PPT
C++ Arrays
PPT
C++ Arrays
PPTX
ARRAYS.pptx
PDF
Array-part1
PPTX
C (PPS)Programming for problem solving.pptx
PPTX
Arrays In C Language
PPTX
Arrays
PPTX
Generative Coding Lecture notes using coding
PPT
Mesics lecture 8 arrays in 'c'
PPTX
2. Array in Data Structure
PPT
arrayy.ppt
PDF
PPTX
3 DS-Arrays.pptx 3 DS-Arrays.pptx 3 DS-Arrays.pptx
PPT
L10 array
PPTX
Programming in c arrays
PDF
Array and its types and it's implemented programming Final.pdf
PDF
Lecture 6 - Arrays
PDF
Arrays in C++
C++ Arrays
C++ Arrays
ARRAYS.pptx
Array-part1
C (PPS)Programming for problem solving.pptx
Arrays In C Language
Arrays
Generative Coding Lecture notes using coding
Mesics lecture 8 arrays in 'c'
2. Array in Data Structure
arrayy.ppt
3 DS-Arrays.pptx 3 DS-Arrays.pptx 3 DS-Arrays.pptx
L10 array
Programming in c arrays
Array and its types and it's implemented programming Final.pdf
Lecture 6 - Arrays
Arrays in C++
Ad

More from Tekle12 (20)

PPTX
MAD-4 (2).pptx mobile application development
PPTX
MAD-3 (2).pptx mobile application development
PPTX
MAD-2.pptx mobile application development
PPTX
MAD-1.pptx mobile application development
PPTX
MAD-4 (2).pptx mobile application development
PPTX
MAD-3 (2).pptx mobile application development
PPTX
MAD-2.pptx mobile application development
PPTX
Chapter 3 - EMTE.pptx artificial intelligence
PPTX
Chapter 2.pptx emerging technology data science
PPTX
Chapter 4 - EMTE.pptx internet of things
PPTX
This is Emerging Technology Power point shared here
PPTX
ch1introduction about android development.pptx
PPTX
Chapter 3 Naming in distributed system.pptx
PPTX
Chapter Introductionn to distributed system .pptx
PPTX
Chapter 6emerging technology - EMTE.pptx
PPTX
Chapter 4about internet of things IoT.pptx
PPTX
Design and analysis of algorithm chapter two.pptx
PPT
Chapter1.1 Introduction to design and analysis of algorithm.ppt
PPT
Chapter 6 WSN.ppt
PPTX
Chapter 2.1.pptx
MAD-4 (2).pptx mobile application development
MAD-3 (2).pptx mobile application development
MAD-2.pptx mobile application development
MAD-1.pptx mobile application development
MAD-4 (2).pptx mobile application development
MAD-3 (2).pptx mobile application development
MAD-2.pptx mobile application development
Chapter 3 - EMTE.pptx artificial intelligence
Chapter 2.pptx emerging technology data science
Chapter 4 - EMTE.pptx internet of things
This is Emerging Technology Power point shared here
ch1introduction about android development.pptx
Chapter 3 Naming in distributed system.pptx
Chapter Introductionn to distributed system .pptx
Chapter 6emerging technology - EMTE.pptx
Chapter 4about internet of things IoT.pptx
Design and analysis of algorithm chapter two.pptx
Chapter1.1 Introduction to design and analysis of algorithm.ppt
Chapter 6 WSN.ppt
Chapter 2.1.pptx
Ad

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Machine Learning_overview_presentation.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
August Patch Tuesday
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
SOPHOS-XG Firewall Administrator PPT.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Accuracy of neural networks in brain wave diagnosis of schizophrenia
MIND Revenue Release Quarter 2 2025 Press Release
Machine Learning_overview_presentation.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Group 1 Presentation -Planning and Decision Making .pptx
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Spectral efficient network and resource selection model in 5G networks
Univ-Connecticut-ChatGPT-Presentaion.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Unlocking AI with Model Context Protocol (MCP)
Diabetes mellitus diagnosis method based random forest with bat algorithm
Programs and apps: productivity, graphics, security and other tools
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Spectroscopy.pptx food analysis technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
August Patch Tuesday

CHAPTER-5.ppt

  • 3. ARRAYS • An array allows you to store and work with multiple 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 [ ], specifies how many of these elements the array contains.
  • 4. … 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.
  • 5. … ARRAYS • An array’s size declarator must be a constant integer 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
  • 6. 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].
  • 7. … 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!
  • 8. … 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;
  • 9. … Accessing Array Elements • The following program demonstrates how we can access array elements 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
  • 10. Array Initialization • Arrays may be initialized when they are defined or with separate assignment statements. • By writing separate assignment statements for the individual elements 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 initializes it with the values: int days[NUM_MON] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  • 11. … Array Initialization • For example, consider the following program 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"; }
  • 12. Partial Array Initialization • An initialization list cannot have more values than the array 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:
  • 13. … 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 arrays. • 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: 1 2 4 8 0 0 0 • If you leave an element uninitialized, you must leave all the elements that follow it uninitialized as well. • For example, the following is not legal: int array[6] = {2, 4, , 8, , 12}; // NOT Legal!
  • 14. Implicit Array Sizing • It’s possible to define an array without specifying its size, providing an initialization list that includes a value for every 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 array 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.
  • 15. Processing Array Contents • For example, the following statement multiplies hours[3] by the variable 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 determine 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)
  • 16. 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 single 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.
  • 18. 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 array, each element has two subscripts: • one for its row and • another for its column.
  • 19. … 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]
  • 20. … 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
  • 21. … Two-Dimensional Arrays • The extra braces that enclose each row’s initialization list are optional. • Both of the following statements perform the same initialization: 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.
  • 22. POINTERS in C++ pointer are a variables that stores the memory addresses of other variables.
  • 23. 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 address on the screen: cout << &amount;
  • 24. … 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 address 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 following: andy = 25; fred = andy; ted = &andy;
  • 25. … 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 preceded 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.
  • 26. 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 designed to hold and work with addresses.
  • 27. … 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: addresses.
  • 28. 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;
  • 29. … 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 assigned 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.
  • 30. 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 variable 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.
  • 31. … 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 asterisk: 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
  • 32. … 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;
  • 33. … 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
  • 34. … 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
  • 35. Summary on the two pointer operators • Note: So far you’ve seen three different uses of the asterisk 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".
  • 36. 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 (*) indicates only that it is a pointer, not the reference operator (*).
  • 38. 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 characters. • 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.
  • 39. … STRINGS • For example, jenny could store either the string of characters "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 characters "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.
  • 40. Initialization of strings •To initialize a string of characters with predetermined 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";
  • 41. … 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.
  • 42. … Initialization of strings • Since the lvalue of an assignment can only be an element 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 series 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");
  • 43. … 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
  • 44. … 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 following 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').
  • 45. … 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.