[go: up one dir, main page]

0% found this document useful (0 votes)
18 views20 pages

C++ #2 CH1

This document discusses arrays and string manipulation in C++. It defines arrays as a series of elements of the same type placed consecutively in memory that can be referenced using an index. Arrays must be declared with a type, name, and size. Elements are accessed using subscripts from 0 to size-1. Arrays can be initialized with values at declaration. Loops can be used to iterate through arrays to input or output element values.

Uploaded by

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

C++ #2 CH1

This document discusses arrays and string manipulation in C++. It defines arrays as a series of elements of the same type placed consecutively in memory that can be referenced using an index. Arrays must be declared with a type, name, and size. Elements are accessed using subscripts from 0 to size-1. Arrays can be initialized with values at declaration. Loops can be used to iterate through arrays to input or output element values.

Uploaded by

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

CHAPTER-1

ARRAYS AND STRING MANIPULATION

ARRAYS

 An array allows you to store and work with multiple values of the same data type.
 Arrays are a series of elements of the same type placed consecutively in memory that can be
individually referenced by adding an index to a unique name.
 That means that, for example, we can store 5 values of type int without having to declare 5
different variables each with a different identifier. Instead, using an array we can store 5
different values of the same type, int for example, with a unique identifier.
 An array works like a variable that can store a group of values, all of the same type. The
values are stored together in consecutive memory locations.
 Like any other variable, an array must be declared before it is used. A typical declaration for
an array in C++ is:
type name [elements];
where type is a valid object type (int, float...), name is a valid variable identifier and the elements
field, that is enclosed within brackets [], specifies how many of these elements the array contains.
 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 elements, each one an integer. This is depicted in the
following figure.

 An array’s size declarator must be a constant integer expression with a value greater than
zero. It can be either a literal, as in the previous example, or a named constant, as shown here:
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

Memory Requirements of Arrays

 The amount of memory used by an array depends on the array’s data type and the number of
elements.
 The age array, defined below, is an array of six shorts.
short age[6];
 On a typical PC, a short uses 2 bytes of memory, so the age array would occupy 12 bytes.
This is shown in the following figure.

1
 The size of an array can be calculated by multiplying the number of bytes needed to store an
individual element by the number of elements in the array.

ACCE
SSING ARRAY ELEMENTS

 The individual elements of an array are assigned unique subscripts. These subscripts are used
to access the elements.
 Even though an entire array has only one name, the elements may be accessed and used as
individual variables. This is possible because each element is assigned a number known as a
subscript.
 A subscript is used as an index to pinpoint a specific element within an array.
 The first element is assigned the subscript 0, the second element is assigned 1, and so
forth.
 The six elements in the hours array would have the subscripts 0 through 5.
 This is shown in the following figure.

 Note: Subscript numbering in C++ always starts at zero. The subscript of the last element in
an array is one less than the total number of elements in the array.
 This means that in the array int hours[6];
o the element hours[6] does not exist.
o The last element in the array is hours[5].
 Each element in the hours array, when accessed by its subscript, can be used as an int
variable.
 Here is an example of a statement that stores the number 20 in the first element of the array:
hours[0] = 20;

 Note: The expression hours[0] is pronounced “hours sub zero.” You would read this
assignment statement as “hours sub zero is assigned twenty.”
 The following figure shows the contents of the hours array after the statement assigns 20 to
hours[0]

2
 Because values have not been assigned to the other elements of the array, the contents of
those elements are unknown. All of the elements are initialized to zero by default.
 The following statement stores the integer 30 in hours[3]. Note that this is the fourth array
element..
hours[3] = 30;
 The following figure shows the contents of the array after this statement executes.

 Note: It is important to understand the difference between the array size declarator and a
subscript. The number inside the brackets in an array definition is the size declarator. It
specifies how many elements the array holds. The number inside the brackets in an
assignment statement or any statement that works with the contents of an array is a subscript.
It specifies which element is being accessed.
 Array elements may receive values with assignment statements just like other variables.
 However, entire arrays may not receive values for all their elements at once. 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!
 An array as a whole may not be assigned a value. This must be done one element at a time,
using a subscript.
 We can access individually anyone of the array values for reading or modifying as if it was a
normal variable. The format is the following:
name[index]
 For example, consider the following array:
int billy [] = { 16, 2, 77, 40, 12071 };
o billy had 5 elements and each of those elements was of type int, the name which we can
use to refer to each element is the following:

o For example, to store the value 75 in the third element of billy a suitable sentence would
be:
billy[2] = 75;
o and, for example, to pass the value of the third element of billy to the variable a, we could
write:
a = billy[2];
3
o Therefore, for all purposes, the expression billy[2] is like any other variable of type int.
o Notice that the third element of billy is specified billy[2], since first is billy[0], the second
is billy[1], and therefore, third is billy[2]. By this same reason, its last element is billy[4].
Since if we wrote billy[5], we would be acceding to the sixth element of billy and
therefore exceeding the size of the array.
 In C++ it is perfectly valid to exceed the valid range of indices for an Array, which can create
problems since they do not cause compilation errors but they can cause unexpected results or
serious errors during execution.
 At this point it is important to be able to clearly distinguish between the two uses that brackets
[ ] have related to arrays. They perform two different tasks:
o one is to set the size of arrays when declaring them; and
o second is to specify indices for a concrete array element when referring to it.
 We must simply take care not to confuse these two possible uses of brackets [ ] with arrays:
 The following are valid operations with arrays:
int billy[5]; // declaration of a new Array (begins with a type name)
billy[2] = 75; // access to an element of the Array.
billy[0] = a;
billy[a] = 75;
b = billy [a+2];
billy[billy[a]] = billy[2] + 5;

Inputting and Displaying Array Contents

 Array elements may also have information read into them using the cin object and have their
values displayed with the cout object, just like regular variables, as long as it is done one
element at a time.
 The following figure shows the contents of the hours array with the example values entered
by the user for program segment.

 Even though the size declarator of an array definition must be a literal or a constant, subscript
numbers can be stored in variables. This makes it possible to use a loop to “cycle through” an
entire array, performing the same operation on each element.
 The following program segment uses two for loops: one for inputting the values into the array
and another for displaying the contents of the array.
const int NUM_EMPLOYEES = 6;
int hours[NUM_EMPLOYEES]; // Holds each employee’s hours
int count; // Loop counter
// Input hours worked
cout << "Enter the hours worked by " << NUM_EMPLOYEES << " employees: ";
for (count = 0; count < NUM_EMPLOYEES; count++)
4
cin >> hours[count];
// Display the contents of the array
cout << "The hours you entered are:";
for (count = 0; count < NUM_EMPLOYEES; count++)
cout << " " << hours[count];
cout << endl;

 Notice in the above program segment that NUM_EMPLOYEES, the named constant used as
the size declarator for the array, is also used as the upper limit in the test expressions of the for
loops.

ARRAY INITIALIZATION

 Arrays may be initialized when they are defined.


 Sometimes it is more appropriate to set variable values within a program than to input them.
However, writing separate assignment statements for the individual elements of an array can
mean a lot of typing, especially for large arrays. For example, consider the following program
segment.
const int NUM_MONTHS = 12;
int days[NUM_MONTHS];
days[0] = 31; // January
………..
days[10] = 30; // November
days[11] = 31; // December
for (int month = 0; month < NUM_MONTHS; month++)
{
cout << "Month " << (month + 1) << " has ";
cout << days[month] << " days.\n";
}
 Fortunately, there is an alternative. Like other variables, C++ allows you to initialize arrays
when you define them. By using an initialization list, all the elements of the array can be
easily initialized when the array is created.
 The following statement defines the days array and initializes it with the same values
established by the set of assignment statements:
int days[NUM_MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
 These values are stored in the array elements in the order they appear in the list. (The first
value, 31, is stored in days[0], the second value, 28, is stored in days[1], and so forth).
 The following figure shows the contents of the array after the initialization.

Partia
l Array Initialization

 An initialization list cannot have more values than the array has elements, but it may have
fewer values than there are elements.
5
 That is, C++ does not require a value for every element. It’s possible to only initialize 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, as illustrated in
the following figure.

 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] << " ";
cout << endl;
This fragment displays the contents of the array as follows:
1248000
 If you leave an element uninitialized, you must leave all the elements that follow it
uninitialized as well. C++ does not provide a way to skip elements in the initialization list. 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, as long as you provide 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

 Individual array elements are processed like any other type of variable.
 Processing array elements is no different than processing other variables. For example, the
following statement multiplies hours[3] by the variable rate:
pay = hours[3] * rate;

6
 And 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]
 Note: When using increment and decrement operators, be careful not to confuse the subscript
with the array element. The following example illustrates the difference.
amount[count]--; // This decrements the value stored in amount[count].
amount[count--]; // This decrements the variable count, but does nothing
//to the value stored in amount[count].
 Array elements can be used in all the same ways regular variables can. You have seen how to
read in a value and store it in an array element, how to assign a value to an array element, and
how to display an element’s value.
 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)

Summing the Values in a Numeric Array


 To sum the values in an array, you must use a loop with an accumulator variable. The loop
adds the value in each array element to the accumulator.
 For example, assume that the following statements appear in a program.
const int NUM_UNITS = 6;
int units[NUM_UNITS] = {16, 20, 14, 8, 6, 10};
int total = 0; // Initialize accumulator
 The following loop adds the values of each element in the array to the total variable. When
the code is finished, total will contain the sum of the units array’s elements.
for (int count = 0; count < NUM_UNITS; count++)
total += units[count];
 Note: Notice that total is initialized to 0. An accumulator variable must be set to 0 before it is
used to keep a running total.

Finding the Average of the Values in a Numeric Array


 The first step in calculating the average of all the values in an array is to sum the values.
 The second step is to divide the sum by the number of elements in the array. Assume that the
following statements appear in a program.
const int NUM_SCORES = 5;
double scores[NUM_SCORES] = {90, 88, 91, 82, 95};
 The following code calculates the average of the values in the scores array and stores the
result in the average variable.
double total = 0; // Initialize accumulator
double average; // Will hold the average
for (int count = 0; count < NUM_SCORES; count++)
total += scores[count];
average = total / NUM_SCORES;

7
 Notice that the last statement, which divides total by NUM_SCORES, is not inside the loop.
This statement should only execute once, after the loop has finished all its iterations.
Finding the Highest and Lowest Values in a Numeric Array
 The algorithms for finding the highest and lowest values in an array are very similar. First,
let’s look at code for finding the highest value in an array.
 Assume that the following statements appear in a program.
const int SIZE = 10;
int numbers[SIZE] = {15, 6, 3, 11, 22, 4, 0, 1, 9, 12};
 The code to find the highest value in the array is as follows.
int count;
int highest;
highest = numbers[0];
for (count = 1; count < SIZE; count++)
{
if (numbers[count] > highest)
highest = numbers[count];
}
 First we copy the value in the first array element to the variable named highest. Then the loop
compares all of the remaining array elements, beginning at subscript 1, to the value in highest.
Each time it finds a value in the array that is greater than highest, it copies that value to
highest. When the loop has finished, highest will contain the highest value in the array.
 The following code finds the lowest value in the array. As you can see, it is nearly identical to
the code for finding the highest value.
int count;
int lowest;
lowest = numbers[0];
for (count = 1; count < SIZE; count++)
{
if (numbers[count] < lowest)
lowest = numbers[count];
}

MULTIDIMENSIONAL ARRAYS

Two-Dimensional Arrays
 A two-dimensional array is like several identical arrays put together. It is useful for storing
multiple sets of data. It is array of arrays.
 An array is useful for storing and working with a set of data. Sometimes, though, it’s
necessary to work with multiple sets of data. For example, in a grade-averaging program a
teacher might record all of one student’s test scores in an array of doubles. If the teacher has
30 students, which means 30 arrays of doubles will be needed to record the scores for the
entire class. Instead of defining 30 individual arrays, however, it would be better to define a
two-dimensional (2D) array.

8
 Two-dimensional arrays can hold multiple sets of values. It’s best to think of a two-
dimensional array as a table having rows and columns of elements, as shown in the following
figure. The figure shows an array of test scores that has three rows and four columns.
 Notice that the three rows are numbered 0 through 2 and the four columns are numbered 0
through 3. There are a total of 12 elements in the array.

 To define a two-dimensional 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.
 Here is an example definition of a two-dimensional array with three rows and four columns:

 Notice that each number is enclosed in its own set of brackets. For processing the information
in a two-dimensional array, each element has two subscripts: one for its row and another for
its column.
 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]
 The subscripted references are used in a program just like the references to elements in a one-
dimensional array.
 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];
 Programs that cycle through each element of a two-dimensional array usually do so with
nested loops.

9
 As with one-dimensional arrays, two-dimensional arrays can be initialized when they are
created.
 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
 The following figure illustrates the initialization.

 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};
 Because the extra braces visually separate each row, however, it’s a good idea to use them. In
addition, the braces give you the ability to leave out initializers within a row without omitting
the initializers for the rows that follow it. For instance, look at the following array definition:
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 (in this case table[0][1] and table[2][1]) are automatically set to
zero.

Summing All the Elements of a Two-Dimensional Array


 To sum all the elements of a two-dimensional array, you can use a pair of nested loops to add
the contents of each element to an accumulator.
 The following code shows an example.
const int NUM_ROWS = 3; // Number of rows
const int NUM_COLS = 5; // Number of columns
int total = 0; // Accumulator
int numbers[NUM_ROWS][NUM_COLS] = {{2, 7, 9, 6, 4}, {6, 1, 8, 9, 4}, {4, 3, 7, 2,
9}};
10
// Sum the array elements
for (int row = 0; row < NUM_ROWS; row++)
{
for (int col = 0; col < NUM_COLS; col++)
total += numbers[row][col];
}
// Display the sum
cout << "The total is " << total << endl;

Summing the Rows of a Two-Dimensional Array


 Sometimes you need to calculate the sum of each row in a two-dimensional array.
 For example, suppose a two-dimensional array is used to hold a set of test scores for a group
of students. Each row in the array is a set of scores for one student. To sum the scores for each
student, you again use a pair of nested loops. The inner loop is used to add all the scores in a
row, that is, all the scores for one student. The outer loop is executed once for each student.
The following code shows an example.
const int NUM_STUDENTS = 3; // Number of students
const int NUM_SCORES = 5; // Number of test scores
double total; // Accumulator
double average; // Holds a given student's average
double scores[NUM_STUDENTS][NUM_SCORES] = {{88, 97, 79, 86, 94},
{86, 91, 78, 79, 84},
{82, 73, 77, 82, 89}};
// Sum each student’s test scores so his or her
// average can be calculated and displayed
for (int row = 0; row < NUM_STUDENTS; row ++)
{
// Reset accumulator to 0 for this student
total = 0;
// Sum a row
for (int col = 0; col < NUM_SCORES; col++)
total += scores[row][col];
// Compute and display the average for this student
average = total / NUM_SCORES;
cout << "Score average for student "<< (row + 1) << " is " << average << endl;
}

Summing the Columns of a Two-Dimensional Array


 Sometimes you may need to calculate the sum of each column in a two-dimensional array.
 Using the array of test scores from the previous example, suppose you wish to calculate the
class average for each of the tests. To do this, you must calculate the average of each column
in the array. As in the previous example, this is accomplished with a set of nested loops.
However, now the order of the two loops is reversed. The inner loop is used to add all the
scores in a column, that is, all the scores for one test. The outer loop is executed once for each
test. The following code illustrates this.
const int NUM_STUDENTS = 3; // Number of students
const int NUM_SCORES = 5; // Number of test scores

11
double total; // Accumulator
double average; // Holds average score on a given test
double scores[NUM_STUDENTS][NUM_SCORES] = {{88, 97, 79, 86, 94},
{86, 91, 78, 79, 84},
{82, 73, 77, 82, 89}};
// Calculate and display the class average for each test
for (int col = 0; col < NUM_SCORES; col++)
{
// Reset accumulator to 0 for this test
total = 0;
// Sum a column
for (int row = 0; row < NUM_STUDENTS; row++)
total += scores[row][col];
// Compute and display the class average for this test
average = total / NUM_STUDENTS;
cout << "Class average for test " << (col + 1)<< " is " << average << endl;
}

Arrays with Three or More Dimensions

 C++ permits arrays to have multiple dimensions.


 C++ allows you to create arrays with virtually any number of dimensions. Here is an example
of a three-dimensional (3D) array definition:
double seat[3][5][8];
 This array can be thought of as three sets of five rows, with each row containing eight
elements. The array might be used, for example, to store the price of seats in an auditorium
that has three sections of seats, with five rows of eight seats in each section.
 Arrays with more than three dimensions are difficult to visualize but can be useful in some
programming problems. For example, in a factory warehouse where cases of widgets are
stacked on pallets, an array with four dimensions could be used to store a part number for
each widget. The four subscripts of each element could represent the pallet number, case
number, row number, and column number of each widget. Similarly, an array with five
dimensions could be used if there were multiple warehouses.

C++ Program to Store value entered by user in three dimensional array and display
it.
#include <iostream>
using namespace std ;

int main () {
int test [ 2 ][ 3 ][ 2 ]; // this array can store 12 elements
cout << "Enter 12 values: \n" ;
for ( int i = 0 ; i < 2 ; ++ i ) {
for ( int j = 0 ; j < 3 ; ++ j ) {
for ( int k = 0 ; k < 2 ; ++ k ) {
cin >> test [ i ][ j ][ k ];
}
}
}
12
cout << "\nDisplaying Value stored:" << endl ;
/* Displaying the values with proper index. */
for ( int i = 0 ; i < 2 ; ++ i ) {
for ( int j = 0 ; j < 3 ; ++ j ) {
for ( int k = 0 ; k < 2 ; ++ k ) {
cout << "test[" << i << "][" << j << "][" << k << "] = " << test [ i ][ j ][ k ]<< endl ;
}
}
}

return 0 ;
}

STRINGS
 Strings of characters allow us to represent successions of characters, like words, sentences,
names, texts, et cetera.
 In C++ there is no specific elemental variable type to store strings of characters. In order to
fulfill this feature we can use arrays of type char, which are successions of char elements.
Remember that this data type (char) is the one used to store a single character, for that reason
arrays of them are generally used to make 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. You may imagine it thus:

 This maximum size of 20 characters is not required to always be fully used. For example,
jenny could store at some moment in a program either the string of characters "Hello" or the
string "Merry Christmas".
 Therefore, since the array of characters can store shorter strings than its total length, a
convention has been reached to end the valid content of a string with a null character, whose
constant can be written 0 or '\0'.
 We could represent jenny (an array of 20 elements of type char) storing the strings of
characters "Hello" and "Merry Christmas" in the following way:

 Notice how after the valid content a null character ('\0') it is included in order to indicate the
end of the string. The panels in gray color represent indeterminate values.

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.
13
 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;
 This is, in fact, how strings are normally treated and processed—as single entities. However,
C++ provides the ability to index them with a subscript, like any other array, so they can be
processed character by character.
 If "Warren" were entered for the name in the previous code segment, it would be stored in the
name character object as shown in the following figure.

 If we wanted to process the string character by character, like a regular array, we could do so.
For example the statement
cout << name[0]; would print the letter W,
cout << name[1]; would print the letter a, and so forth.

STRING MANIPULATION

Initialization of strings

 Because strings of characters are ordinary arrays they fulfill all their same rules. For example,
if we want to initialize a string of characters with predetermined values we can do it just like
any other array:
char mystring[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
 In this case we would have declared a string of characters (array) of 6 elements of type char
initialized with the characters that compose Hello plus a null character '\0'.
 Nevertheless, strings of characters have an additional way to initialize their values: using
constant strings.
 Constants represent entire strings of characters enclosed between double quotes ("), for
example:
"the result is: "
is a constant string that we have probably used on some occasion.
 Unlike single quotes (') which specify single character constants, double quotes (") are
constants that specify a succession of characters. Strings enclosed between double quotes
always have a null character ('\0') automatically appended at the end.
 Therefore we could initialize the string mystring with values by either of these two ways:

14
char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char mystring [] = "Hello";
 In both cases the array or string of characters mystring is declared with a size of 6 characters
(elements of type char): the 5 characters that compose Hello plus a final null character ('\0')
which specifies the end of the string and that, in the second case, when using double quotes
(") it is automatically appended.
 Before going further, notice that the assignation of multiple constants like double-quoted
constants (") to arrays are only valid when initializing the array, that is, at the moment when
declared. Expressions within the code like:
mystring = "Hello";
mystring[] = "Hello";
are not valid for arrays, like neither would be:
mystring = { 'H', 'e', 'l', 'l', 'o', '\0' };
 So remember: We can "assign" a multiple constant to an Array only at the moment of
initializing it. The reason will be more comprehensible when you know a bit more about
pointers, since then it will be clarified that an array is simply a constant pointer pointing to an
allocated block of memory. And because of this constantness, the array itself cannot be
assigned any value, but we can assing values to each of the elements of the array.
 The moment of initializing an Array it is a special case, since it is not an assignation, although
the same equal sign (=) is used. Anyway, always have the rule previously underlined present.

Assigning values to strings

 Since the lvalue of an assignation can only be an element of an array and not the entire 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';
 But as you may think, this does not seem to be a very practical method. Generally for
assigning values to an array, and more specifically 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. string2 can be either an array, a pointer, or
a constant string, so the following line would be a valid way to assign the constant string
"Hello" to mystring:
strcpy (mystring, "Hello");
 For example, the following fragment sets value to string
char myName [20];
strcpy (myName,"J. Paul");
cout << myName;
 Notice that we needed to include <string.h> header in order to be able to use function strcpy.

15
 Another frequently used method to assign values to an array is by directly using the input
stream (cin). In this case the value of the string is assigned by the user during program
execution.
 When cin is used with strings of characters it is usually used with its getline method, 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 (like an array, for example), length is
the maximum length of the buffer (the size of the array) and 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').
 The following example repeats whatever you type on your keyboard. It is quite simple but
serves as an example of how you can use cin.getline with strings:
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? Juan
Hello Juan.
Which is your favourite team? Inter Milan
I like Inter Milan too.
 Notice how in both calls to cin.getline we used the same string identifier (mybuffer). What
the program does in the second call is simply step on the previous content of buffer with the
new one that is introduced.
 If you remember the section about communication through the console, you will remember
that we used the extraction operator (>>) to receive data directly from the standard input. This
method can also be used instead of cin.getline with strings of characters. For example, in our
program, when we requested an input from the user we could have written:
cin >> mybuffer;
this would work, but this method has the following limitations that cin.getline has not:
 It can only receive single words (no complete sentences) since this method uses as a
delimiter any occurrence of a blank character, including spaces, tabulators, newlines and
carriage returns.
 It is not allowed to specify a size for the buffer. That makes your program unstable in case
the user input is longer than the array that will host it.
For these reasons it is recommended that whenever you require strings of characters coming
from cin you use cin.getline instead of cin >>.

FORMATTING OUTPUT

 The cout object provides ways to format data as it is being displayed. This affects the way
data appears on the screen. Unfortunately, the numbers do not line up in columns. This is
because some of the numbers, such as 5 and 7, occupy one position on the screen, while
others occupy two or three positions. cout uses just the number of spaces needed to print each
number. To remedy this, cout offers a way of specifying the minimum number of spaces to
16
use for each number. A stream manipulator, setw, can be used to establish print fields of a
specified width. Here is an example of how it is used:
value = 23;
cout << setw(5) << value;
 The number inside the parentheses after the word setw specifies the field width for the value
immediately following it. The field width is the minimum number of character positions, or
spaces, on the screen to print the value in. In our example, the number 23 will be displayed in
a field of five spaces.
 To further clarify how this works, look at the following statements:
value = 23;
cout << "(" << setw(5) << value << ")";
 This will produce the following output: ( 23)
 Floating-point values may be rounded to a number of significant digits, or precision, which is
the total number of digits that appear before and after the decimal point. You can control the
number of significant digits with which floating-point values are displayed by using the
setprecision manipulator.
 The first value in the program is displayed without the setprecision manipulator. (By default,
the system displays floating-point values with six significant digits.) The subsequent cout
statements print the same value, but rounded to five, four, three, two, and one significant
digits. Notice that, unlike setw, setprecision does not count the decimal point. When we used
setprecision(5), for example, the output contained five significant digits, which required six
positions to print 4.9188.
 If the value of a number is expressed in fewer digits of precision than specified by
setprecision, the manipulator will have no effect. In the following statements, the value of
dollars only has four digits of precision, so the number printed by both cout statements is
24.51.
double dollars = 24.51;
cout << dollars << endl; // displays 24.51
cout << setprecision(5) << dollars << endl; // displays 24.51
 The following table shows how setprecision affects the way various values are displayed.
Notice that when fewer digits are to be displayed than the number holds, setprecision rounds,
rather than truncates, the number.

 Unlike field width, the precision setting remains in effect until it is changed to some other
value.
There are a large set of useful string handling library functions
provided by every C++ compiler. But we will only discuss four
main functions. Which are
– strlen() = It is use to finds the length of a string.
– strcpy()= It is use to copies the string into another string .
– strcat() = It is use to Append the string at the end of

17
another string.
– strcmp()= It compares two strings.

18
The String Length function(strlen())
• This function is used to counts the number of characters presents in
a string.
• While calculating length of the string it doesn’t count ‘\0’ (null
character).
void main()
{
char str1[ ]= “hello world”;
char str2[ ]= “India”;
int length1= strlen(str1);
int length2= strlen(str2);
cout<<length1;
cout<<length2;
}

STRING COPY FUNCTION(STRCPY())

• This function is used to copies the contents of one string into


another string.
strcpy(Destination , source)
• strcpy( ) goes on copying the each characters of source string into
the destination string till it doesn’t encounter ‘\0’. It is our
responsibility
void main() to see that the destination string should be big
enough
{ to hold source string.
char str1[ ] = “India”, str2[20];
strcpy(str2,str1);
cout<<str2;
}

THE STRING CONCATENATION FUNCTION


(STRCAT ())

• The function is used to concatenate the source string at the end of


destination string.
strcat(destination, source);
• The destination string should be big enough to hold final string.
void main
{

19
char str1[ ] = “Hello”;
char str2[15 ] = “World”;
strcat(str2, str1);
cout<<str2;
}

13.4 THE STRING COMPARE FUNCTION (STRCMP)

• This function compares two string to find checks whether the two
string are same or different.
• The two strings are compared character by character until there is a
mismatch or end of one of the string is reached.
• If the two strings are equal it will return a value zero. If they are
not than it returns the numeric difference between the ASCII value
of non-matching characters.

Condition result
Str1<Str2 less than zero
Str1==Str2 zero
Str1>Str2 greater than zero

void main( )
{
char str1[ ]= “hello”;
char str2[ ]=“world”;
int i=strcmp(str1, str2);
cout<<i;
}

-------------------

20

You might also like