0% found this document useful (0 votes)
25 views15 pages

Chapter 4 - Arrays and Strings (Part 1)

The document discusses arrays in C++ including how to declare, initialize, access elements of arrays and multidimensional arrays. It provides examples of declaring one-dimensional and multi-dimensional arrays, initializing array elements, taking user input to populate arrays, and retrieving elements from arrays.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
25 views15 pages

Chapter 4 - Arrays and Strings (Part 1)

The document discusses arrays in C++ including how to declare, initialize, access elements of arrays and multidimensional arrays. It provides examples of declaring one-dimensional and multi-dimensional arrays, initializing array elements, taking user input to populate arrays, and retrieving elements from arrays.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

CHAPTER FOUR

ARRAYS, STRINGS, AND POINTERS

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.

C++ Array Declaration


Syntax: dataType arrayName[arraySize];

Example: int x[6];


 int - type of element to be stored
 x - name of the array
 6 - size of the array

Access Elements in C++ Array


In C++, each element in an array is associated with a number. The number is known as an array
index. We can access elements of an array by using those indices.
arrayName[index];
Consider the array x we have seen above.

Figure 2.1: Accessing of array elements using their index value.

Elements of an array in C++

Remember:
 The array indices start with 0. Meaning x[0] is the first element stored at index 0.

Fundamentals of Programming [By: Sinodos G.] Chapter Four 1|Page


 If the size of an array is n, the last element is stored at index (n-1). In this example, x[5]
is the last element.
 Elements of an array have consecutive addresses.

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.

C++ Array Initialization


In C++, it's possible to initialize an array during declaration.

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.

C++ ARRAY WITH EMPTY MEMBERS


If an array has a size n, we can store up to n number of elements in the array. However, what will
happen if we store less than n number of elements.

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.

Empty array members are automatically assigned the value 0

Example: How to insert and print array elements?

Fundamentals of Programming [By: Sinodos G.] Chapter Four 2|Page


Example 1: Displaying Array Elements

Output: The numbers are: 7, 5, 6 , 12 , 35


Note: In our range-based loop, we have used the code const int &n instead of int n as the range
declaration.
Example 2: Take Inputs from User and Store Them in an Array

Fundamentals of Programming [By: Sinodos G.] Chapter Four 3|Page


Example 3: Display Sum and Average of Array Elements Using for Loop

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.

Example 2: C++ Program to Calculate Average of Numbers Using Arrays

Fundamentals of Programming [By: Sinodos G.] Chapter Four 4|Page


Output 5. Enter number: 33
Enter the numbers of data: 6 6. Enter number: 45.6
1. Enter number: 45.3 Average = 27.69
2. Enter number: 67.5
3. Enter number: -45.6 This program calculates the average of all the
4. Enter number: 20.34 numbers entered by the user.

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

Output Enter Number 7 : 5.7


Enter total number of elements(1 to 100): 8 Enter Number 8 : -66.5
Enter Number 1 : 23.4 -----------------------------------
Enter Number 2 : -34.5 Largest element = 55.5
Enter Number 3 : 50
Enter Number 4 : 33.5 This program takes n number of elements
Enter Number 5 : 55.5 from user and stores it in array arr[].
Enter Number 6 : 43.7

C++ Array Out of Bounds


 If we declare an array of size 10, then the array will contain elements from index 0 to 9.
However, if we try to access the element at index 10 or more than 10, it will result in
Undefined Behavior.
Fundamentals of Programming [By: Sinodos G.] Chapter Four 5|Page
C++ MULTIDIMENSIONAL ARRAYS
In C++, we can create an array of an array, known as a multidimensional array. For example:
int x[3][4];
 Here, x is a two-dimensional array. It can hold a maximum of 12 elements. We can think of
this array as a table with 3 rows and each row has 4 columns as shown below.

Elements in two-dimensional array in C++ Programming


Three-dimensional arrays also work in a similar way.

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

Multidimensional Array Initialization


 Like a normal array, we can initialize a multidimensional array in more than one way.

Initialization of two-dimensional array


int test[2][3] = {2, 4, 5, 9, 0, 19};

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.

Initializing a two-dimensional array in C++

Fundamentals of Programming [By: Sinodos G.] Chapter Four 6|Page


Initialization of three-dimensional array
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};

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

Example 1: Two-Dimensional Array


// C++ Program to display all elements of an initialized two-dimensional array

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

Fundamentals of Programming [By: Sinodos G.] Chapter Four 7|Page


Example 2: Taking Input for Two-Dimensional Array

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.

Fundamentals of Programming [By: Sinodos G.] Chapter Four 8|Page


Output:
test[0][0][0] = 1 test[0][2][0] = 5 test[1][1][0] = 9
test[0][0][1] = 2 test[0][2][1] = 6 test[1][1][1] = 10
test[0][1][0] = 3 test[1][0][0] = 7 test[1][2][0] = 11
test[0][1][1] = 4 test[1][0][1] = 8 test[1][2][1] = 12

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];
}

// Adding Two matrices


for(i = 0; i < r; ++i)

Fundamentals of Programming [By: Sinodos G.] Chapter Four 9|Page


for(j = 0; j < c; ++j)
sum[i][j] = a[i][j] + b[i][j];

// Displaying the resultant sum matrix.


cout << endl << "Sum of two matrix is: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << sum[i][j] << " ";
if(j == c - 1)
cout << endl;
}
return 0;
}

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

C++ Program to Find Transpose of a Matrix


This program takes a matrix of order r*c from the user and computes the transpose of the matrix.
Solution
#include <iostream>
using namespace std;
int main() {
int a[10][10], transpose[10][10], row, column, i, j;
cout << "Enter rows and columns of matrix: ";
cin >> row >> column;
cout << "\nEnter elements of matrix: " << endl;
// Storing matrix elements
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
cout << "Enter element a" << i + 1 << j + 1 << ": ";
cin >> a[i][j];
}
}

// Printing the a matrix


Fundamentals of Programming [By: Sinodos G.] Chapter Four 10 | P a g e
cout << "\nEntered Matrix: " << endl;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
cout << " " << a[i][j];
if (j == column - 1)
cout << endl << endl;
}
}
// Computing transpose of the matrix
for (int i = 0; i < row; ++i)
for (int j = 0; j < column; ++j) {
transpose[j][i] = a[i][j];
}
// Printing the transpose
cout << "\nTranspose of Matrix: " << endl;
for (int i = 0; i < column; ++i)
for (int j = 0; j < row; ++j) {
cout << " " << transpose[i][j];
if (j == row - 1)
cout << endl << endl;
}
return 0;
}
Output
Enter rows and columns of matrix: 23 Entered Matrix:
Enter elements of matrix: 1 2 9
Enter element a11: 1 0 4 7
Enter element a12: 2 Transpose of Matrix:
Enter element a13: 9 1 0
Enter element a21: 0 2 4
Enter element a22: 4 9 7
Enter element a23: 7

Fundamentals of Programming [By: Sinodos G.] Chapter Four 11 | P a g e


C++ STRINGS
String is a collection of characters. Strings are used for storing text. A string variable contains a
collection of characters surrounded by double quotes (“”).
Example: Create a variable of type string and assign it a value:
string greeting = "Hello";
To use strings, you must include the <string> library
#include <string> // Include the string library
string greeting = "Hello"; // Create a string variable
C++ String Concatenation
The + operator can be used between strings to add them together to make a new string. This is
called concatenation:

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.

Fundamentals of Programming [By: Sinodos G.] Chapter Four 12 | P a g e


C++ NUMBERS AND STRINGS
C++ uses the + operator for both addition and concatenation. Numbers are added. Strings are
concatenated. If you add two numbers, the result will be a number:
Example:

int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)

If you add two strings, the result will be a string concatenation:

Example
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)

If you try to add a number to a string, an error occurs:

Example:
string x = "10";
int y = 20;
string z = x + y; //Error

C++ String Length


To get the length of a string, use the length() function: Example

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


cout << "The length of the txt string is: " << txt.length();

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();

C++ ACCESS STRINGS


Access Strings: You can access the characters in a string by referring to its index number inside
square brackets []. Example prints the first character in myString:
string myString = "Hello";
cout << myString[0]; // Outputs H

Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.

Fundamentals of Programming [By: Sinodos G.] Chapter Four 13 | P a g e


Example2: prints the second character in myString:
string myString = "Hello";
cout << myString[1];
// Outputs e

Change String Characters


 To change the value of a specific character in a string, refer to the index number, and use
single quotes:
Example:
string myString = "Hello";
myString[0] = 'J';
cout << myString; // Outputs Jello instead of Hello

User Input Strings


It is possible to use the extraction operator >> on cin to display a string entered by a user:
Example:
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
// Type your first name: John
// Your name is: John

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;

// Type your full name: John Doe


// Your name is: John

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;

Fundamentals of Programming [By: Sinodos G.] Chapter Four 14 | P a g e


Output:
// Type your full name: John Doe
// Your name is: John Doe

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.

Fundamentals of Programming [By: Sinodos G.] Chapter Four 15 | P a g e

You might also like