Chapter 1 Array
Chapter 1 Array
Chapter 1 Array
• 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.
• For example, an array representing 10 height measurements (each being an integer quantity) may
be defined as:
• 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 .
• 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,
• When a complete initialize is used, the array dimension becomes redundant, because the
number of elements is implicit in the initializer.
int myNum[3] = {10, 20, 30};
#include <iostream>
#include <string>
int main() {
cars[0] = "Opel";
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:
• 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:
#include <string>
int main() {
cars[3] = "Mazda";
cars[4] = "Tesla";
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.
Dessie 26 34 22 17
Addis Ababa 24 32 19 13
Hossana 28 38 25 20
• 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] .
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:
• 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.
• 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>
int main() {
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>
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!!