0% found this document useful (0 votes)
23 views

Array and String

Chapter Two covers arrays and strings in programming, focusing on the definition, declaration, and initialization of arrays in C++. It explains the use of arrays for managing collections of data, including one-dimensional and multi-dimensional arrays, and introduces sorting algorithms such as selection sort. The chapter emphasizes best practices for array usage, including the importance of constants for array sizes and the potential pitfalls of out-of-range indexing.

Uploaded by

Yigezu Agonafir
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Array and String

Chapter Two covers arrays and strings in programming, focusing on the definition, declaration, and initialization of arrays in C++. It explains the use of arrays for managing collections of data, including one-dimensional and multi-dimensional arrays, and introduces sorting algorithms such as selection sort. The chapter emphasizes best practices for array usage, including the importance of constants for array sizes and the potential pitfalls of out-of-range indexing.

Uploaded by

Yigezu Agonafir
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 66

CHAPTER TWO

ARRAY AND STRING

Fundamental programming II 1
Overview

• Introduction to Arrays
• Initializing Arrays
• Programming with Arrays
• Sorting an array using selection
sort
• Array and loop
• Multidimensional Arrays
• C-style strings

Fundamental programming II 2
Introduction to Arrays
• An array is an aggregate data type that
lets you access multiple variables
through a single name by use of an index.
In C++, all of these variables must have
the same type.
• An array is used to process a collection
of data of the same type
Examples: A list of names
A list of temperatures

Fundamental programming II 3
Introduction to Arrays
(continued)
Why do we need arrays?
Imagine keeping track of 30 test scores,
or 100, or 1000 in memory
How would you name all the variables?
How would you process each of the
variables?

Fundamental programming II 4
Declaring an Array
• Consider the case where you want to record the
test scores for 30 students in a class. To do
so, you would have to allocate 30 variables!
int nTestScoreStudent1;
int nTestScoreStudent2;
int nTestScoreStudent3;
// ...
int nTestScoreStudent30;
• Arrays give us a much easier way to do this:
– int anTestScores[30]; // allocate 30 integers

Fundamental programming II 5
Declaring an Array

• An array, named score, containing 30


variables of type int can be declared
as
int score[ 30 ];
• This is like declaring 30 variables
of type int:
score[0], score[1], … , score[4]
• The value in brackets is called
– A subscript
– An index
The Array Variables

• The variables making up the array are


referred to as
– Indexed variables
– Subscripted variables
– Elements of the array
• The number of indexed variables in an
array is the declared size, or size, of
the array
– The largest index is one less than the
size
– The first index value is zero
Array Variable Types

• An array can have indexed variables


of any type
• All indexed variables in an array
are of the
same type
– This is the base type of the array
• An indexed variable can be used
anywhere an ordinary variable of the
base type is used
Using [ ] With Arrays
• In an array declaration, [ ]'s enclose the
size of the array such as this array of 30
integers:
int score [30];
• When referring to one of the indexed
variables,
the [ ]'s enclose a number identifying one of
the indexed variables
– score[3] is one of the indexed variables
– The value in the [ ]'s can be any
expression that evaluates to one of the
integers 0 to (size -1)
Using [ ] With Arrays
(continued)
• Note that the subscript operator actually
has two uses here: in the variable
declaration, the subscript tells how many
elements to allocate. When using the
array, the subscript tells which array
element to access.
• int anArray[5]; // allocate 5 integers
• anArray[0] = 7; // put the value 7 in
element 0

Fundamental programming II 10
Indexed Variable
Assignment
• To assign a value to an indexed
variable, use
the assignment operator:

int n = 2;
score[n + 1] = 99;
– In this example, variable score[3] is
assigned 99
Example of Array

• Let’s take a look at a simple


program that uses arrays:
int anArray[3]; // allocate 3 integers
anArray[0] = 2;
anArray[1] = 3;
anArray[2] = 4;
int nSum = anArray[0] + anArray[1] +
anArray[2];
cout << "The sum is " << nSum << endl;

Fundamental programming II 12
Arrays - Introduction

0 69
1 61
index
2 70
3 89 values
4 23
5 10

6 9

13
Loops And Arrays
• for-loops are commonly used to step through
arrays
First index is 0 Last index is (size – 1)
– Example:for (i = 0; i < 5; i++)
{
cout << score[i] << " off by "

<< (max – score[i]) << endl;


}
could display the difference between each
score and the maximum score stored in an
array
Fundamental programming II 16
Fundamental programming II 17
Fundamental programming II 18
Constants and Arrays
• Use constants to declare the size of an array
– Using a constant allows your code to be easily
altered for use on a smaller or larger set of data
– Example:
const int NUMBER_OF_STUDENTS = 50;
int score[NUMBER_OF_STUDENTS];

for ( i = 0; i < NUMBER_OF_STUDENTS;
i++)
cout << score[i] << " off by " << (max – score[i])
<< endl;
• Only the value of the constant must be changed
to make this code work for any number of
students
Variables and
Declarations
• Most compilers do not allow the use of a
variable to declare the size of an array

Example: cout << "Enter number of


students: ";
cin >> number;
int score[number];
– This code is illegal on many compilers
Array Declaration Syntax
• To declare an array, use the syntax:
Type_Name Array_Name[Declared_Size];
– Type_Name can be any type
– Declared_Size can be a constant to make
your program more versatile
• Once declared, the array consists of the
indexed
variables:
Array_Name[0] to
Array_Name[Declared_Size -1]
Computer Memory

• Computer memory consists of numbered


locations called bytes
– A byte's number is its address
• A simple variable is stored in consecutive
bytes
– The number of bytes depends on the
variable's type
• A variable's address is the address of its
first byte
Arrays and Memory
• Declaring the array int a[6]
– Reserves memory for six variables of
type int
– The variables are stored one after
another
– The address of a[0] is remembered
• The addresses of the other indexed variables
is not remembered
– To determine the address of a[3]
• Start at a[0]
• Count past enough memory for three integers
to find a[3]
Array Index Out of Range

• A common error is using a nonexistent


index
– Index values for int a[6] are the
values 0 through 5
– An index value not allowed by the array
declaration is out of range
– Using an out of range index value does
not produce an error message!
Out of Range Problems
• If an array is declared as: int a[6]; and
an integer is declared as: int i = 7;
• Executing the statement a[i] = 238;
causes…
• The computer to calculate the address of
the illegal a[7]
• (This address could be where some other
variable is stored)
• The value 238 is stored at the address
calculated for a[7]
• No warning is given!
Initializing Arrays

• To initialize an array when it is declared


– The values for the indexed variables
are enclosed in braces and separated by
commas
• Example: int children[3] = { 2, 12, 1 };
Is equivalent to:
int children[3];
children[0] = 2;
children[1] = 12;
children[2] = 1;
Fundamental programming II 28
Fundamental programming II 29
Fundamental programming II 30
Initializing Arrays

• Omitted Size
– If you are initializing an array of
elements using an initializer list, the
compiler can figure out the size of the
array for you, and you can omit
explicitly declaring the size of the
array:
– int anArray[] = { 0, 1, 2, 3, 4 }; //
declare array of 5 elements

Fundamental programming II 31
Default Values
• If too few values are listed in an
initialization
statement
– The listed values are used to initialize
the first of the indexed variables
– The remaining indexed variables are
initialized to a zero of the base type
– Example: int a[10] = {5, 5};
initializes a[0] and a[1] to 5 and
a[2] through a[9] to
0
Un-initialized Arrays

• If no values are listed in the array


declaration,
some compilers will initialize each
variable to a
zero of the base type
– DO NOT DEPEND ON THIS!
Section 7.1 Conclusion

• Can you
– Describe the difference between a[4]
and int a[5]?

– Show the output of

char symbol[3] = {'a', 'b', 'c'};


for (int index = 0; index < 3; index+
+)
cout << symbol[index];
One-Dimensional Arrays

• referred to as a single-dimensional array


• is a list of related values, all having
the same data type, that’s stored with a
single group name.
• In C++, as in other computer languages,
the group name is referred to as the array
name. For example, consider this list of
temperatures:
– 95.75
– 83.0
– 97.625

Fundamental programming II 35
One-Dimensional Arrays
(continued)
• All the temperatures in the list are
double-precision numbers and must be
declared as such. However, each item in
the list doesn’t have to be declared
separately.
• The items in the list can be declared as a
single unit and stored under a common
variable name called the array name. For
example, temp is used as the name for this
list, and the declaration statement double
temp[5];

Fundamental programming II 36
One-Dimensional Arrays
(continued)
• Good programming practice requires
defining number-of-items in the array as a
constant before declaring the array. So in
practice, the previous array declaration
for temp would be declared with two
statements, as in these examples:
– const int NUMELS = 5; // define a
constant for the number of items
– double temp[NUMELS]; // declare the
array

Fundamental programming II 37
One-Dimensional Arrays
(continued)
• The following are other examples of array
declarations using this two-line syntax:
const int NUMELS = 6;
int volts[NUMELS];
const int ARRAYSIZE = 4;
char code[ARRAYSIZE];
const int SIZE = 100;
double amount[SIZE];
• In these declaration statements, each array is
allocated enough memory to hold the number of
data items specified in the declaration
statement.
Fundamental programming II 38
Arrays and Enums

• One of the big documentation


problems with arrays is that that
integer indices do not provide any
information to the programmer about
the meaning of the variable.
Consider a class of 5 students:
– const int nNumberOfStudents = 5;
– int anTestScores[nNumberOfStudents];
– anTestScores[2] = 76;

Fundamental programming II 39
One-Dimensional Arrays
(continued) Example
enum StudentNames
{
KENNY, // 0
KYLE, // 1
STAN, // 2
BUTTERS, // 3
CARTMAN, // 4
WENDY, // 5
MAX_STUDENTS // 6
};
int anTestScores[MAX_STUDENTS]; // allocate 6
anTestScores[STAN] = 76;

Fundamental programming II 40
Exercise

• Declare an array to hold the high


temperature (to the nearest tenth of a
degree) for each day of a year. Assign a
value of 0 to each day.
• Set up an enum with the names of the
following animals: chicken, dog, cat,
elephant, duck, and snake. Allocate an
array with an element for each of these
animals, and use an initializer list to
initialize each element to hold the number
of legs that animal has.

Fundamental programming II 41
Multi-Dimensional Arrays

• C++ allows arrays with multiple index


values
– char page [30] [100];
declares an array of characters named
page
• page has two index values:
The first ranges from 0 to 29
The second ranges from 0 to 99
– Each index in enclosed in its own
brackets
– Page can be visualized as an array of
30 rows and 100 columns
Index Values of page

• The indexed variables for array page are


page[0][0], page[0][1], …, page[0][99]
page[1][0], page[1][1], …, page[1][99]
• …
page[29][0], page[29][1], … , page[29][99]
• page is actually an array of size 30
– page's base type is an array of 100
characters
Multi-Dimensional Arrays
• A two-dimensional array, sometimes
referred to as a table, consists of both
rows and columns of elements. For example,
the following array of numbers is called a
two-dimensional array of integers:
8 16 9 52
3 15 27 6
14 25 2 10
This array consists of three rows and four
columns.
int val[3][4];
Fundamental programming II 44
Fundamental programming II 45
Fundamental programming II 46
Fundamental programming II 47
Sorting an array using
selection sort
• Sorting is generally performed by
repeatedly comparing pairs of array
elements, and swapping them if they meet
some criteria.
• The order in which these elements are
compared differs depending on which
sorting algorithm is used, and the
criteria depends on how the list will be
sorted (ascending or descending order).

Fundamental programming II 48
Sorting an array using
selection sort (continued)

• To swap two elements, we can use the


swap() function from the C++ standard
library. Swap is defined in the algorithm
header, and lives in the std namespace.
int main()
{ using namespace std; int x = 2; int y = 4;
cout << "Before swap: x = " << x << ", y = " << y <<
endl;
swap(x, y); // swap also lives in stdnamespace
cout << "After swap: x = " << x << ", y = " << y <<
endl;
}

Fundamental programming II 49
Exercise

1) Selection sort the following array: { 30,


60, 20, 50, 40, 10 }. Show the array after
each swap that takes place.
2) Rewrite the selection sort code above to
sort in descending order (largest numbers
first). Although this may seem complex, it
is actually surprisingly simple.

Fundamental programming II 50
C-Strings

• A C-string (also called a character


string) is a sequence of contiguous
characters in memory terminated by
the NUL character '\0'. C-strings
are accessed by variables of type
char*(pointer to char). For example,
if s has type char*, then
cout << s << endl;

Fundamental programming II 51
C-Strings

• THE NULL CHARACTER,'\0'


– The null character, ’\0’, is used to mark
the end of a C-string that is stored in
an array of characters. When an array of
characters is used in this way, the array
is often called a C-string variable.
– Although the null character ’\0’ is
written using two symbols, it is a single
character that fits in one variable of
type char or one indexed variable of an
array of characters.

Fundamental programming II 52
Strings (continued)

• 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’ ). 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’ ).

Fundamental programming II 53
Strings (continued)

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.
Specifying the size as 11 makes room for the null at the end of the
string.

Fundamental programming II 54
Strings (continued)
Some examples of string constants in C++ are:
"hello there"
"I like C++."
"#$%§@@+*"
"\""
"\"\""
"\\"
""
The null string, ““, only contains the null
terminator and represents
the empty string.
Fundamental programming II 55
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:
#include <stdio.h>
int main() {
char str[80];
cout << “Enter a string: “;
cin >> str; // read string from keyboard
cout << “Here is your string: “;
cout << str;
return(0);}
Fundamental programming II 56
Strings (continued)

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

Fundamental programming II 57
Strings (continued)

• Solution: Use another C++ library function,


gets().
#include <iostream.h>
#include <cstdio.h>
int main()
{
char str[80]; // long enough for user input?
cout << “Enter a string: “;
gets(str); // read a string from the keyboard
cout << “Here is your string: “;
cout << str << endl;
return(0);}

Fundamental programming II 58
Some C++ Library Functions
for Strings (continued)

• 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 string

Fundamental programming II 59
Some C++ Library Functions
for Strings (continued)

• strcpy(to_string, from_string)-String Copy:


#include <iostream.h>
#include <cstring.h>
int main()
{
char a[10];
strcpy(a, “hello”);
cout << a;
return(0);
}
Fundamental programming II 60
Some C++ Library Functions
for Strings (continued)
• 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.
#include <iostream.h>
#include <cstdio.h>
#include <cstring.h>
int main()
{
char str[80];
cout << “Enter a string: “;
gets(str);
cout << “Length is: “ << strlen(str);
return(0);}
Fundamental programming II 61
Some C++ Library Functions
for Strings (continued)
• strcat(string_1, string_2) — Concatenation of Strings
• The strcat() function appends s2 to the end of s1.
String s2 is unchanged.
// includes ...
int main()
{
char s1[21], s2[11];
strcpy(s1, “hello”);
strcpy(s2, “ there”);
strcat(s1, s2);
cout << s1 << endl;
cout << s2 << endl;
return(0); }

Fundamental programming II 62
Fundamental programming II 63
Some C++ Library Functions
for Strings (continued)

• 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

Fundamental programming II 64
Fundamental programming II 65
Using the Null
Terminator

Fundamental programming II 66

You might also like