0% found this document useful (0 votes)
31 views35 pages

Programming Language: Arrays and Strings

The document discusses arrays and strings in C++. It covers topics like declaring, initializing and accessing single and multidimensional arrays. It also covers string variables, concatenation, length and accessing characters in strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views35 pages

Programming Language: Arrays and Strings

The document discusses arrays and strings in C++. It covers topics like declaring, initializing and accessing single and multidimensional arrays. It also covers string variables, concatenation, length and accessing characters in strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Programming Language

Arrays and Strings


Content
• Arrays Introduction
• Single and Multidimensional Arrays
• Organizing Array Elements
• Strings Introduction
• String Constant
• String Variable
• String I/O Functions (gets() and puts())
• Array of Strings

2
C++ Arrays
• Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
• To declare an array, define the variable type, specify the name of the array
followed by square brackets and specify the number of elements it should
store:
string cars[4];
• We have now declared a variable that holds an array of four strings. To
insert values to it, we can use an array literal - place the values in a comma-
separated list, inside curly braces:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of three integers, you could write:
int myNum[3] = {10, 20, 30};

3
Access the Elements of an Array
• You access an array element by referring to the index number.
• This statement accesses the value of the first element in cars:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo

• Note: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.

4
Change an Array Element
• To change the value of a specific element, refer to the index number:
cars[0] = "Opel";

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};


cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo

5
Loop Through an Array
• You can loop through the array elements with the for loop.
• The following example outputs all elements in the cars array:

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};


for(int i = 0; i < 4; i++) {
cout << cars[i] << "\n";
}//output
Volvo
BMW
Ford
Mazda

6
Loop Through an Array
• The following example outputs the index of each element together
with its value:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << i << ": " << cars[i] << "\n";
}//output
0: Volvo
1: BMW
2: Ford
3: Mazda

7
Omit Array Size
• You don't have to specify the size of the array.
• But if you don't, it will only be as big as the elements that are inserted
into it:
string cars[] = {"Volvo", "BMW", "Ford"};
// size of array is always 3
This is completely fine.

8
Omit Array Size
However, the problem arise if you want extra space for future
elements.
Then you have to overwrite the existing values:

string cars[] = {"Volvo", "BMW", "Ford"};


string cars[] =
{"Volvo", "BMW", "Ford", "Mazda", "Tesla"};

9
Omit Array Size
• If you specify the size however, the array will reserve the extra space:
string cars[5] = {"Volvo", "BMW", "Ford"};
// size of array is 5, even though it's only three
elements inside it
• Now you can add a fourth and fifth element without overwriting the
others:
cars[3] = {"Mazda"};
cars[4] = {"Tesla"};

10
Omit Elements on Declaration
• It is also possible to declare an array without specifying the elements
on declaration, and add them later:
string cars[5];
cars[0] = {"Volvo"};
cars[1] = {"BMW"};
...

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

12
C++ Multidimensional Arrays
• Three-dimensional arrays also work in a similar way.
• For 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

13
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.
14
Multidimensional Array Initialization
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} }
};

15
Two-Dimensional Array Example

16
Creating References
• A reference variable is a "reference" to an existing variable, and it is
created with the & operator:
string food = "Pizza"; // food variable
string &meal = food; // reference to food
• Now, we can use either the variable name food or the reference name
meal to refer to the food variable:
string food = "Pizza";
string &meal = food;
cout << food << "\n"; // Outputs Pizza
cout << meal << "\n"; // Outputs Pizza
17
C++ Strings
• Strings are used for storing text.
• A string variable contains a collection of characters surrounded by
double quotes:
• Create a variable of type string and assign it a value:
string greeting = "Hello";
• To use strings, you must include an additional header file in the
source code, the <string> library:

18
C++ Strings Example

19
String Concatenation
• The + operator can be used between strings to add them together to
make a new string. This is called concatenation:
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
• In the example above, 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 ' ‘).

20
Append
• A string in C++ is actually an object, which contain functions that can
perform certain operations on strings. For example, you can also
concatenate strings with the append() function:
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;
//output: John Doe
• 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.
• However, for testing and such, it might be easier to just use +.

21
Adding 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:
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:
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)

22
Adding Numbers and Strings
• If you try to add a number to a string, an error occurs:
string x = "10";
int y = 20;
string z = x + y;

23
String Length
• To get the length of a string, use the length() function:
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " <<
txt.length();
//output: The length of the txt string is: 26
• Tip: You might see 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():
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();
//output: The length of the txt string is: 26

24
Access Strings
• You can access the characters in a string by referring to its index number
inside square brackets [].
• This 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.
• This example prints the second character in myString:
string myString = "Hello";
cout << myString[1];
// Outputs e

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

26
User Input Strings
• It is possible to use the extraction operator >> on cin to display a
string entered by a user:
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):

27
User Input Strings
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;
// Type your full name: John Doe
// Your name is: John
• From the example above, you would expect the program to print
"John Doe", but it only prints "John".
• That's why, when working with strings, we often use the getline()
function to read a line of text.
• It takes cin as the first parameter, and the string variable as second.
28
User Input Strings
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;

// Type your full name: John Doe


// Your name is: John Doe

29
Omitting Namespace
• You might see some C++ programs that runs without the standard
namespace library.
• The using namespace std line can be omitted and replaced with the std
keyword, followed by the :: operator for string (and cout) objects:
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
}
• It is up to you if you want to include the standard namespace library or not.

30
How gets() function works?

31
How puts() function works?

32
What is an Array of Strings?
• A string is a 1-D array of characters, so an array of strings is a 2-D array of
characters.
• Just like we can create a 2-D array of int, float etc;
• We can also create a 2-D array of character or array of strings.
• Here is how we can declare a 2-D array of characters.
char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '\0'},
{'t', 'o', 'm','\0'},
{'j', 'e', 'r', 'r', 'y','\0'}
};
33
Array of Strings
• It is important to end each 1-D array by the null character ('\0'), otherwise,
it will be just an array of characters.
• We can't use them as strings.
• Declaring an array of strings this way is rather tedious, that's why C
provides an alternative syntax to achieve the same thing.
• This above initialization is equivalent to:
char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};

34
Array of Strings

35

You might also like