Chapter 4 - Arrays and Strings (Part 1)
Chapter 4 - Arrays and Strings (Part 1)
ARRAYS IN C++
In C++, an array is a variable that can store multiple values of the same type.
Example:
Suppose a class has 27 students, and we need to store the grades of all of them. Instead of
creating 27 separate variables, we can simply create an array:
double grade[27];
Here, grade is an array that can hold a maximum of 27 elements of double type. In C++, the size
and type of arrays cannot be changed after its declaration.
Remember:
The array indices start with 0. Meaning x[0] is the first element stored at index 0.
Example: suppose the starting address of x[0] is 2120d. Then, the address of the next element
x[1] will be 2124d, the address of x[2] will be 2128d and so on. Here, the size of each element is
increased by 4. This is because the size of int is 4 bytes.
Example:
int x[6] = {19, 10, 8, 17, 9, 15}; // declare and initialize and array
C++ Array elements and their data. Another method to initialize array during declaration:
int x[] = {19, 10, 8, 17, 9, 15}; // declare and initialize an array
Here, we have not mentioned the size of the array. In such cases, the compiler automatically
computes the size.
Example: int x [6] = {19, 10, 8}; // store only 3 elements in the array
The array x has a size of 6.
However, we have initialized it with only 3 elements. In such cases, the compiler assigns random
values to the remaining places. Oftentimes, this random value is simply 0.
Output
The numbers are: 7 5 6 12 35 27
Their Sum = 92
Their Average = 15.3333
Note: We used a ranged for loop instead of a normal for loop. A normal for loop requires us to
specify the number of iterations, which is given by the size of the array. But a ranged for loop does
not require such specifications.
Example3:
C++ Program to Find Largest Element of an Array (This program takes n number of elements from
user (where, n is specified by user) and stores data in an array. Then, this program displays the
largest element of that array using loops.)
Example:
float x[2][4][3];
This array x can hold a maximum of 24 elements. We can find out the total number of
elements in the array simply by multiplying its dimensions:
2 x 4 x 3 = 24
The above method is not preferred. A better way to initialize this array with the same array
elements is given below:
int test[2][3] = { {2, 4, 5}, {9, 0, 19}};
This array has 2 rows and 3 columns, which is why we have two rows of elements with 3 elements
each.
This is not a good way of initializing a three-dimensional array. A better way to initialize this array
is: int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
};
Notice the dimensions of this three-dimensional array. The first dimension has the value 2. So, the
two elements comprising the first dimension are:
Element 1 = { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} }
Element 2 = { {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
The second dimension has the value 3. Notice that each of the elements of the first dimension has
three elements each:
{3, 4, 2, 3}, {0, -3, 9, 11} and {23, 12, 23, 2} for Element 1.
{13, 4, 56, 3}, {5, 9, 3, 5} and {5, 1, 4, 9} for Element 2.
Finally, there are four int numbers inside each of the elements of the second dimension:
{3, 4, 2, 3}
{0, -3, 9, 11}
... .. ...
Output
test[0][0] = 2 test[1][1] = 0
test[0][1] = -5 test[2][0] = 9
test[1][0] = 4 test[2][1] = 1
Output:
Enter 6 numbers: The numbers are:
1 numbers[0][0]: 1
2 numbers[0][1]: 2
3 numbers[0][2]: 3
4 numbers[1][0]: 4
5 numbers[1][1]: 5
6 numbers[1][2]: 6
Example 3: Three-Dimensional Array: A C++ Program to Store value entered by user in three-
dimensional array and display it.
The basic concept of printing elements of a 3d array is similar to that of a 2d array. However, since
we are manipulating 3 dimensions, we use a nested for loop with 3 total loops instead of just 2:
the outer loop from i == 0 to i == 1 accesses the first dimension of the array
the middle loop from j == 0 to j == 2 accesses the second dimension of the array
the innermost loop from k == 0 to k == 1 accesses the third dimension of the array
As we can see, the complexity of the array increases exponentially with the increase in dimensions.
Examples of Arrays
Example 1: C++ Program to Add Two Matrix Using Multi-Dimensional Arrays
This program takes two matrices of order r*c and stores it in two-dimensional array. Then, the
program adds these two matrices and displays it on the screen.
#include <iostream>
using namespace std;
int main()
{
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
cout << "Enter number of rows (between 1 and 100): ";
cin >> r;
cout << "Enter number of columns (between 1 and 100): ";
cin >> c;
cout << endl << "Enter elements of 1st matrix: " << endl;
// Storing elements of first matrix entered by user.
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << "Enter element a" << i + 1 << j + 1 << " : ";
cin >> a[i][j];
}
// Storing elements of second matrix entered by user.
cout << endl << "Enter elements of 2nd matrix: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << "Enter element b" << i + 1 << j + 1 << " : ";
cin >> b[i][j];
}
Output
Enter number of rows (between 1 and Enter elements of 2nd matrix:
100): 2 Enter element b11: 3
Enter number of columns (between 1 Enter element b12: -9
and 100): 2 Enter element b21: 7
Enter elements of 1st matrix: Enter element b22: 2
Enter element a11: -4
Enter element a12: 5 Sum of two matrix is:
Enter element a21: 6 -1 -4
Enter element a22: 8 13 10
Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
we added a space after firstName to create a space between John and Doe on output. However, you
could also add a space with quotes (" " or ' '):
Example
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;
APPEND IN C++
A string in C++ is actually an object, which contain functions that can perform certain operations
on strings. you can also concatenate strings with the append () function:
Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;
Notes: It is up to you whether you want to use + or append (). The major difference between the
two, is that the append () function is much faster.
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)
Example
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)
Example:
string x = "10";
int y = 20;
string z = x + y; //Error
Note: some C++ programs that use the size() function to get the length of a string. This is just an
alias of length(). It is completely up to you if you want to use length() or size():
Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();
Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.
However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means
that it can only display a single word (even if you type many words):
Example:
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;
we often use the getline() function to read a line of text. It takes cin as the first parameter, and
the string variable as2nd.
Example:
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
Example 1: C++ String to read a word, and to display a string entered by user.
#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
cin >> str;
cout << "You entered: " << str << endl;
cout << "\nEnter another string: ";
cin >> str;
cout << "You entered: "<<str<<endl;
return 0;
}
Output
Enter a string: C++ Enter another string: Programming is
You entered: C++ fun.
-------------------------------------------- You entered: Programming
Example 2: C++ String to read a line of text, a C++ program to read and display an entire
line entered by user.
#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
cin.get(str, 100);
cout << "You entered: " << str << endl;
return 0;
}
Output
Enter a string: Programming is fun.
You entered: Programming is fun.