Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 27

Chapter One

Array and String


Array and String
• An array consists of a set of objects (called its elements), all of which are of the same type and
are arranged contiguously in memory.

• Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

• Each element is identified by an index which denotes the position of the element in the array.

• The number of elements in an array is called its dimension.


Cont.…..
• To declare an array, define the variable type, specify the name of the array followed by square
brackets and specify the number of elements (dimension) it should store:

• For example, an array representing 10 height measurements (each being an integer quantity) may
be defined as:

Eg1. int heights[10];

• The individual elements of the array are accessed by indexing the array.

• The first array element always has the index 0. Therefore, heights [0] and heights [9] denote,
respectively, the first and last element of heights .

• Each of heights elements can be treated as an integer variable.

• So, for example, to set the third element to 177, we may write: heights[2] = 177;
Cont.…..
• Attempting to access a nonexistent array element (e.g., heights [- 1] or heights [10]) leads to
a serious runtime error (called ‘index out of bounds’ error).

• Processing of an array usually involves a loop which goes through the array element by
element.

• Like other variables, an array may have an initialize. Braces are used to specify a list of
comma- separated initial values for array elements. For example,

int nums[3] = {5, 10, 15};

• Initializes the three elements of nums to 5, 10, and 15, respectively.


Cont.…..
• When the number of values in the initialize is less than the number of elements, the
remaining elements are initialized to zero:

int nums[3] = {5, 10}; // nums[2] initializes to 0

• When a complete initialize is used, the array dimension becomes redundant, because the
number of elements is implicit in the initializer.

• The first definition of nums can therefore be equivalently written as:

int nums[] = {5, 10, 15}; // no dimension needed


Cont.…..
Eg2 string cars[4];

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

• To create an array of three integers, you could write:

int myNum[3] = {10, 20, 30};

Access the Elements of an Array

• You access an array element by referring to the index number.

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


cout << cars[0]; //to accesses the value of the first element in cars:
// Outputs Volvo
Change an Array Element
• To change the value of a specific element, refer to the index number: cars[0] = "Opel";

#include <iostream>

#include <string>

using namespace std;

int main() {

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

cars[0] = "Opel";

cout << cars[0];

return 0;

}
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:
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << cars[i] << "\n";
}
return 0;
}
Omit Array Size
• If you don't have to specify the size of the array, 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

• 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", "Mazda", "Tesla"};

• If you specify the size however, the array will reserve the extra space:

string cars[5] = {"Volvo", "BMW", "Ford"}; // size is 5, even though it's only three


elements
Change an Array Element
• Now you can add a fourth and fifth element without overwriting the others:
#include <iostream>

#include <string>

using namespace std;

int main() {

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

cars[3] = "Mazda";
cars[4] = "Tesla";

for(int i = 0; i < 5; i++) {

cout << cars[i] << "\n";

return 0;

}
Omit Elements on Declaration
• It is also possible to declare an array without specifying the elements on declaration, and add them later:
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
cars[2] = "Ford";
cars[3] = "Mazda";
cars[4] = "Tesla";
for(int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}
return 0;
}
Multidimensional Arrays
• An array may have more than one dimension (i.e., two, three, or higher).

• The organization of the array in memory is still the same (a contiguous sequence of
elements), but the programmer’s perceived organization of the elements is different.

• Table 1. 1 Average seasonal temperature.


  Spring Summer Autumn Winter
 

Dessie 26 34 22 17
Addis Ababa 24 32 19 13
Hossana 28 38 25 20

• This may be represented by a two- dimensional array of integers: int seasonTemp[3][4];

• The organization of this array in memory is as 12 consecutive integer elements.


Cont.…..

• As before, elements are accessed by indexing the array, a separate index is needed for each
dimension.

• For example, Dessie’s average summer temperature (first row, second column) is given by
seasonTemp[0][1] .

• The array may be initialized using a nested initialization:

int seasonTemp[3][4] = {{26, 34, 22, 17},{24, 32, 19, 13},{28, 38, 25, 20}};

• Because this is mapped to a one- dimensional array of 12 elements in memory, it is equivalent to:

int seasonTemp[ 3][4] = {26, 34, 22, 17, 24, 32, 19, 13, 28, 38, 25, 20};
Cont.…..
• The nested initialization is preferred because as well as being more informative, it is more
versatile.

• For example, it makes it possible to initialize only the first element of each row and have the
rest default to zero:

int seasonTemp[3][4] = {{26}, {24}, {28}};

• Processing a multidimensional array is similar to a one- dimensional array, but uses nested
loops instead of a single loop.
String
• 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:
#include <iostream>
#include <string>
using namespace std;
int main() {
string greeting = "Hello";
cout << greeting;
return 0;
}
String Concatenation
• The + operator can be used between strings to add them together to make a new string. This
is called concatenation:
#include <iostream>
#include <string>
using namespace std;
int main () {
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
return 0;
}
String Length
• A string in C++ is actually an object, which contain functions that can perform certain operations
on strings. For example, the length of a string can be found with the length() function:

#include <iostream>

#include <string>

using namespace std;

int main() {

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

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

return 0;

}
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:
#include <iostream>
#include <string>
using namespace std;
int main() {
string myString = "Hello";
cout << myString[0];
return 0;
}
Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.
Change String Characters
To change the value of a specific character in a string, refer to the index number, and use single
quotes:
#include <iostream>
#include <string>
using namespace std;
int main() {
string myString = "Hello";
myString[0] = 'J';
cout << myString;
return 0;
}
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):
Cont……
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:
Cont…..
#include <iostream>
#include <string>
using namespace std;
int main() {
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
return 0;
}
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:
#include <iostream>
using namespace std;
int main () {
int x = 10;
int y = 20;
int z = x + y;
cout << z;
return 0;
}
Cont…..
• If you add two strings, the result will be a string concatenation:

#include <iostream>
#include <string>

using namespace std;

int main () {

string x = "10";

string y = "20";

string z = x + y;

cout << z;

return 0;

}
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;
}
The String Class in C++
#include <iostream> // concatenates str1 and str2
#include <string> str3 = str1 + str2;
using namespace std; cout << "str1 + str2 : " << str3 << endl;
int main () { // total length of str3 after concatenation
string str1 = "Hello"; len = str3.size();
string str2 = "World"; cout << "str3.size() : " << len << endl;
string str3; return 0;
int len ; }
// copy str1 into str3 When the above code is compiled and executed, it produces
result something as follows −
str3 = str1;
str3 : Hello
cout << "str3 : " << str3 << endl;
str1 + str2 : HelloWorld
str3.size() : 10
Cont.…..

Many
Thanks!!

You might also like