Chapter 5 - Arrays and Strings in C++
This chapter presents more complex used of variables through arrays which are a type of data storage that is often use in C++ programs.
Array
An array is a collection of same data type elements which are sheltered under a common name. A variable when declared as an array can store one or more data of the same data type under the same name but they are distinguished based from their array element numbers or subscript numbers. There are two type of array, single-dimensional array and multi-dimensional array.
1. Single-Dimensional array is useful for simple grouping of data that is relatively small in size. A single-dimensional array has only a single subscript. A subscript is a number in brackets that follows an array's name.
Syntax for declaring a single-dimensional array:
<data-type> <array-name> [<size>];
The <data-type> is the data type of elements that an array stores. It can be any of the available variable data types. If the array stores an integer elements then the type of array is int. The <array-name> is the name that is given to the array. It can be any string but should abide to the rules in naming variables as discussed in chapter 3. The <size> is the size of array, the value in subscripts [ ] enclosed in brackets, indicates the number of elements of how many data the array can store.
Example of declaring array:
int num[5];
The above example declares an array with the data type integer and the array name is num having 5 elements. 5 elements means that the array can hold 5 integer numbers. The array elements or the different data stored in an array is distinguished through the array's subscript number. The subscript number of arrays always start with 0 zero. Therefore, the above array declaration example can be initialized as:
num[0]=7;
num[1]=4;
num[2]=6;
num[3]=1;
num[4]=12;
Since the array is declared with 5 elements, the array can hold 5 integer numbers, and its subscript starts with 0 and ends with 4. Arrays can also be declared and defined (initialized) in a single line like the example below. This example is an array declaration and definition in single line.
int num[5]={7,4,6,1,12};
2. Multi-Dimensional Array (Two-Dimensional). A two-dimensional array can hold 2 subscripts which can be represented as rows and columns.
Example:
int num[2][3];
The example can be represented like a 2 x 3 table as presented in table 5.1
Table 5.1
The numbers in table 5.1 is the subscript numbers of the array. The above two-dimensional array example can hold 6 data. Below is an example of initializing the two-dimensional array.
num[0][0]=5;
num[0][1]=3;
num[0][2]=8;
num[1][0]=7;
num[1][1]=2;
num[1][2]=15;
Multi-dimensional array can have more dimensions, but having more than two dimensions means developing a very complicated program. Even industry practitioners has difficulty dealing with multi-dimensional arrays. The following are sample programs that uses arrays.
Array program1: Figure 5.1 presents a sample program that declares and defines a single and two-dimensional array and prints their values. Figure 5.2 presents the output.
Figure 5.1 (source file name: ch5sample1.cpp)
Line 6 declares and defines (initialize) a single dimensional array with 3 elements named num1, and line 7 prints its values using the cout<<. Line 10 declares a single dimensional array named num2 with 3 elements, and lines 13 to 15 is the array's definition (initialization). Line 16 prints the values of array num2. Finally, line 19 declares a two-dimensional array named num3, and lines 21 to 24 defines its values. Line 25 prints its values. Figure 5.2 presents the output of the program.
Figure 5.2
Code listings of figure 5.1
#include<iostream>
using namespace std;
int main()
{
//Array declaration and definition in 1 line
int num1[3]={5,9,2};
cout<<"Array num1 holds: "<<num1[0]<<","<<num1[1]<<","<<num1[2]<<endl;
//Array declaration
int num2[3];
//Array definition
num2[0]=7;
num2[1]=1;
num2[2]=4;
cout<<"Array num2 holds: "<<num2[0]<<","<<num2[1]<<","<<num2[2]<<endl;
//2-Dim array declaration
int num3[2][2];
//2-Dim array definition
num3[0][0]=5;
num3[0][1]=3;
num3[1][0]=8;
num3[1][1]=10;
cout<<"Array num3 holds: "<<num3[0][0]<<","<<num3[0][1]<<","<<num3[1][0]<<","<<num3[1][1];
fflush(stdin);
getchar();
return 0;
}
Array program2: Figure 5.3 presents a sample program that declares a single-dimensional array, and its values are defined through the scanf() function. The values of the array is then printed through the cout<<.
Figure 5.3 (source file name: ch5sample2.cpp)
Line 5 presents the array declaration with the name of num having 3 elements. Line 5 prints the instruction to the user. Line 7 accepts 3 values and assigns them to the array elements. Line 8 prints the array values. Figure 5.4 presents the output.
Figure 5.4
Code listings of figure 5.3
#include<iostream>
using namespace std;
int main()
{
int num[3];
cout<<"Enter the values of the array: "<<endl;
cin>>num[0]>>num[1]>>num[2];
cout<<"The array holds: "<<num[0]<<","<<num[1]<<","<<num[2];
fflush(stdin);
getchar();
return 0;
}
The C-Style Character String
The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
Declaring and defining a string
In C language, strings are stored in an array of char data type along with the null terminating character "\0" (slash zero) at the end. In other words to create a string in C, it is needed to create an array of chars to set each element in the array to a char value that makes up the string.
When sizing the string array, it is needed to add plus one to the actual size of the string to make space for the null terminating character, "\0". For example is the word "hello" which has 5 characters. Instead of declaring a array of char with an array size of 5, it should be 6 because of the null terminating character.
Example:
char word[6];
word[0]='h';
word[1]='e';
word[2]='l';
word[3]='l';
word[4]='o';
word[5]='\0';
Note that the Null terminating character is considered as a single character. The above example can also be declared and define as:
char word[6]={'h','e','l','l','o','\0'}
To make things simpler, the above examples can be written as:
char word[6]="hello";
Figure 5.5 presents a sample program in C++ that uses character arrays to handle string data and print its value.
Figure 5.5 (source file name: ch5sample3.cpp)
Lines 5 to 7 declares arrays in different format. Lines 9 to 14 initializes char array str1 and lines 15 to 17 prints the values of the three arrays. Figure 5.6 presents the output.
Figure 5.6
Code listings of figure 5.5
#include<iostream>
using namespace std;
int main()
{
char str1[6];
char str2[10]={'C','+','+',' ','P','r','o','g','\0'};
char str3[10]="Language!";
str1[0]='H';
str1[1]='e';
str1[2]='l';
str1[3]='l';
str1[4]='o';
str1[5]='\0';
cout<<"The str1 is: "<<str1<<endl;
cout<<"The str2 is: "<<str2<<endl;
cout<<"The str3 is: "<<str3;
fflush(stdin);
getchar();
return 0;
}
Defining a string using input functions
String in C language can also be initialized using the two input functions which are scanf() and gets().
1. The format in defining a string with scanf() function is:
char <str-name>[<size>];
cin>> <str-name>
The <str-name> in the format is the name of the char array, and the cin>> assign it to char array.
Example:
char strLastName[50];
cin>>&strLastName;
The above example declares a char array with 50 elements which means that the input string should not exceed more than 49 characters because the 50th character is reserved for the Null character. If the string entered is only 5 characters long, then char array subscripts 0 to 5 are the elements with values having the 5th subscript holds the null character, and the rest of the elements are left with no value.
Figure 5.7 presents a sample program that uses a cin>> to define a string.
Figure 5.7 (source file name: ch5sample4.cpp)
Line 5 declares char array of 50 elements, and line 7 defines the string using the cin>>. Figure 5.8 presents the output.
Figure 5.8
Code listings of figure 5.7
#include<iostream>
using namespace std;
int main()
{
char strFName[50];
cout<<"Enter your First Name:";
cin>>strFName;
cout<<"Your name is "<<strFName;
fflush(stdin);
getchar();
return 0;
}
C Strings' pre-defined functions in C++
Character arrays are a special type of array that uses a "\0" NULL character at the end. As such, in C++, it has it its own include file or header library called "cstring" that contains pre-defined functions for performing operations on these specific array types.
The cstring library must be included in the program to utilize strings' pre-defined functions. Below is the code to include the cstring library using the #include directive.
#include<cstring>
Following are the strings' pre-defined functions:
1. Length of a String
Use the strlen() function to get the length of a string minus the null terminating character. This function returns an integer value representing the length of the string.
Syntax of strlen():
int strlen(<string>);
The <string> in the syntax can be a literal string, a variable, or a function that returns a string.
Example:
char name[30]="Sherwyn";
int intLen=strlen(name);
The example would set the value of intLen to 7, because the literal string "Sherwyn" has 7 characters.
2. Concatenation of Strings
The strcat() function appends one string to another.
Syntax strcat():
char strcat(<str1>, <str2>);
The first string <str1> gets the second string <str2> appended to it. In the syntax, the <str1> should be a variable that holds a string and the <str2> can be a literal string, a variable, or a function that returns a string.
Example:
char fname[30] = "Sherwyn";
char lname[30] = "Allibang";
cout<<strcat(fname, lname);
In the example, the output is "SherwynAllibang" as lname is appended to fname.
3. Compare Two Strings (Case Sensitive)
Sometimes it is needed to determine if two strings are the same. For this, the strcmp() function should be used. This function returns an integer number.
Syntax of strcmp():
int strcmp(<str1>, <str2>);
The return value indicates how the 2 strings relate to each other. If they are equal strcmp() returns 0 zero. The value will be negative if string1 <str1> is less than string2 <str2>, or positive in the opposite case. The <str1> and <str2> in the syntax can be a literal string, a variable, or a function that returns a string.
Example:
char strDep1[10]="CSE";
char strDep2[10]="ITE";
char strAdd1[10]="Prontera";
char strAdd2[10]="Prontera";
int intVal1=strcmp(strDep1, strDep2);
int intVal2=strcmp(strAdd1, strAdd2);
In the example, the intVal1 will be assigned to a value -1, because strDep1 and strDep2 is not the same. Moreover, intVal2 will be assigned to a value of 0, because strAdd1 and strAdd2 is the same.
4. Compare Two Strings (Not Case Sensitive)
If one do not care whether the strings are in upper or lower case then use strcmpi() function instead of the strcmp(). Other than that, it's exactly the same.
Syntax of strcmpi():
int strcmpi(<str1>, <str2>);
The <str1> and <str2> in the syntax can be a literal string, a variable, or a function that returns a string.
Example:
char strDep1[10]="CSE";
char strDep2[10]="ITE";
char strAdd1[10]="Prontera";
char strAdd2[10]="PRONTERA";
int intVal1=strcmp(strDep1, strDep2);
int intVal2=strcmp(strAdd1, strAdd2);
The intVal1 will have a value of -1 similar to strmp() function, and at the same time the intVal2 will still have a value of 0, because strAdd1 and strAdd2 is the same regardless of cases.
5. Copy Strings
To copy one string to another string variable, the strcpy() function should be used. This makes up for not being able to use the "=" assignment operator to set the value of a string variable.
Syntax of strcpy():
strcpy(<str-var>,<str2>);
The <str-var> must be a char array variable, and the <str2> can be a literal string, variable, or a function that returns a string.
Example:
char strName[10]="Sherwyn";
char strOfficer[10];
strcpy(strOfficer,strName);
The value of strOfficer upon executive the codes above is "Sherwyn" as it copied the value of strName into strOfficer. Below is another example when copying a literal string to <str-val>.
char strOfficer[10];
strcpy(strOfficer,"Allibang");
The value of strOfficer from the example above is "Allibang" as the literal string "Allibang" has been copied to strOfficer. This is actually another way of defining a char array or string variable.
6. Reversing the Order of a String
The strrev() function is not part of the ANSI standard and therefore strongly recommended against if it is needed for the program to be portable to platforms other than Windows.
Syntax of strrev():
strrev(<string>);
This function will reverse the order of string <string>. The <string> in the syntax can be a literal text, a variable, or a function that returns a string.
Example:
char strName[10]="Sherwyn";
strrev(strName);
The string is "Sherwyn", strrev() reverses the string then the new value of strName would become "nywrehS".
7. Converting Uppercase Strings to Lowercase Strings
The strlwr() function is not part of the ANSI standard and therefore strongly recommended against if it is needed for the program to be portable to platforms other than Windows.
Syntax of strlwr():
strlwr(<string>);
This function will convert uppercase characters in string <string> to lowercase. The <string> in the syntax can be a literal text, a variable, or a function that returns a string.
Example:
char strName[10]="Sherwyn";
strlwr(strName);
The string is "Sherwyn", strlwr() converts the string into lowercase, therefore the new value of strName would become "sherwyn".
8. Converting Lowercase Strings to Uppercase Strings
The strupr() function is not part of the ANSI standard and therefore strongly recommended against if it is needed for the program to be portable to platforms other than Windows.
Syntax of strupr():
strupr(<string>);
Unlike strlwr(), the function strrupr() will convert uppercase characters in string <string> to lowercase. The <string> in the syntax can be a literal text, a variable, or a function that returns a string.
Example:
char strName[10]="Sherwyn";
strupr(strName);
The string is "Sherwyn", strupr() converts the string into UPPERCASE, therefore the new value of strName would become "SHERWYN".
Figure 5.9 presents an example of a program the uses the different string functions.
Figure 5.9 (source file name: ch5sample5.cpp)
Line 2 includes in the program the library cstring which is needed to utilize the different string functions. Line 6 declares char array with 50 elements and line 7 declares and defines a char array with initial value. Line 10 gets a string input and assigns it to variable strName. Lines 12to 18 uses the different string functions. Figure 5.11 presents the output.
Figure 5.10
Code listings of figure 5.10
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char strName[50];
char strComName[50]="Allibang, ";
cout<<"Enter your name: ";
cin>>strName;
cout<<"\nstrlen(strName) it returns: "<<strlen(strName)<<endl;
cout<<"strcat(strComName,strName) it becomes: "<<strcat(strComName,strName)<<endl;
cout<<"strcmp(strName,'Allibang') returns: "<<strcmp(strName,"Allibang")<<endl;
cout<<"strcmpi(strName,'Allibang') returns: "<<strcmpi(strName,"Allibang")<<endl;
cout<<"strcpy(strComName,strName) it becomes: "<<strcpy(strComName,strName)<<endl;
cout<<"strlwr(strName) it returns: "<<strlwr(strName)<<endl;
cout<<"strupr(strName) it returns: "<<strupr(strName);
fflush(stdin);
getchar();
return 0;
}
Self-assessment questions
Answer the following:
1. In a one-dimensional array declared with n elements, what is the subscript of the last element?
2. If an array is declared with 10 elements, what is the subscript value of the first element?
3. Write a declaration for an array named x that will hold 50 type long values.
4. Write a definition statement that assigns the value of 123.456 to the 50th element of an array named x.
5. Can a particular array contain integers, floats, and characters?
6. What is the number of the starting subscript or index of an array?
7. What is the purpose of the null character?
8. What will be the value of length in the following C++'s C style code?
char fname[30]="Jhen";
int length=strlen(fname);
9. What will be printed on-screen in the following C++'s C style code?
char fname[20]="Ric";
char lname[20]="DD";
cout<<strcat(fname, lname);
10. What will be the value of x in the following C++'s C style code?
x = strcmp(Eri, Eri);