0% found this document useful (0 votes)
10 views37 pages

Lecture 4 - Arrays, Numbers and Strings

This document is a lecture on programming in C++, focusing on arrays, strings, and numbers. It covers the definition, declaration, and access methods for both single and multi-dimensional arrays, as well as string manipulation techniques using character arrays and string objects. The lecture also includes examples and methods for string concatenation, appending, and calculating string length.

Uploaded by

lezileonesmo
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)
10 views37 pages

Lecture 4 - Arrays, Numbers and Strings

This document is a lecture on programming in C++, focusing on arrays, strings, and numbers. It covers the definition, declaration, and access methods for both single and multi-dimensional arrays, as well as string manipulation techniques using character arrays and string objects. The lecture also includes examples and methods for string concatenation, appending, and calculating string length.

Uploaded by

lezileonesmo
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/ 37

Programming in C++

Lecture 4: Arrays, Strings and Numbers


Mr. Msangi
Arrays
● An array is a variable that can store multiple values of the same type.
● It is a collection of similar items stored in contiguous memory locations.
Arrays

● In programming, sometimes a simple variable is not enough to


hold all the data.
● For example, let's say we want to store the marks of 500
students, having 500 different variables for this task is not
feasible, we can define an array with size 500 that can hold the
marks of all students.
Arrays

● Indices are used to hold single values in the array. Indexing


uses the numeric values starting from 0 for the first element, 1
for the second element, etc.
● C++ supports both indexed arrays and associative arrays
● Associative arrays, also called maps or dictionaries will be
discussed in future chapters
Arrays
Declaring Arrays
● General syntax: dataType arrayName[arraySize] = {element 1, element 2, ...};
● Method 1:
○ int arr[5];
○ arr[0] = 10;
○ arr[1] = 20;
○ arr[2] = 30;
○ arr[3] = 40;
○ arr[4] = 50;
● Method 2:
○ int arr[] = {10, 20, 30, 40, 50};
● Method 3:
○ int arr[5] = {10, 20, 30, 40, 50};
Accessing Array Elements

● Array elements are accessed using their index positions.


● The index position starts from 0.
● The first element is at index 0, the second element at index 1
etc.
● If the array is of size n, then the last element of the array is
stored at index n-1.
Accessing Array Elements
1. #include <iostream>
2. using namespace std;
3.
4. int main(){
5. int arr[] = {11, 22, 33, 44, 55};
6. cout<<arr[0]<<endl;
7. cout<<arr[1]<<endl;
8. cout<<arr[2]<<endl;
9. cout<<arr[3]<<endl;
10. cout<<arr[4]<<endl;
11. return 0;
12. }
Accessing Array Elements
● The above code outputs the following results.
○ 11
○ 22
○ 33
○ 44
○ 55
● The above code worked fine, it cannot be practical in situations where the
array size is big.
● Instead of accessing array elements by hardcoding index values, loops are
used to store and retrieve array elements by defining a variable as index.
Accessing Array Elements
● Let us rewrite the above code using a while loop:
1. #include <iostream>
2. using namespace std;
3.
4. int main(){
5. int arr[] = {11, 22, 33, 44, 55};
6. int n=0;
7. while(n<=4){
8. cout<<arr[n]<<endl;
9. n++;
10. }
11. return 0;
12. }
Arrays Example

● Write a C++ program that stores marks for 20 students in a single


variable and using an if-else-if statement display the remarks for
each student as follows:
○ Student 1 Remarks: Excellent
○ Student 2 Remarks: Good
○ Student 3 Remarks: Very good; and so on
● Use the following criteria to define your remarks
○ 70-100: Excellent, 60-70: Very good, 50-60: Good, 40-50:
Average, 35-40: Poor, 0-35: Fail
● NB: Except for the 70-100 range, upper boundary are exclusive.
Arrays Dimensions

● Single dimensional arrays


○ Single dimensional arrays stores values in a single dimension
○ int x[5] = {1,2,3,4,5};
● Multi-dimensional arrays
○ Multi-dimensional arrays are also called array of arrays.
○ The data in multidimensional array is stored in a tabular form as shown in
the diagram below
Arrays Dimensions

● Multi-dimensional array
Multidimensional arrays
● A multidimensional array can be two dimensional array, three
dimensional array etc.
● Two dimensional array
○ int arr[2][3];
○ This array has total 2*3 = 6 elements.
● Three dimensional array
○ int arr[2][2][2];
○ This array has total 2*2*2 = 8 elements.
Two dimensional arrays

● Declaring a two dimensional array is done as follows:


○ int arr[2][3] ;
● Different methods can be used to initialize two dimensional arrays
● Method I:
○ int arr[2][3] = {10, 11 ,12 ,20 ,21 , 22};
● Method II:
○ int arr[2][3] = {{10, 11 ,12} , {20 ,21 , 22}};
● The second method is preferred because it allows you to visualize the
arrangement of your data in terms of rows and columns
Accessing array elements in a two dimensional array

● Accessing array elements:


○ arr[0][0] – first element (first row, first column)
○ arr[0][1] – second element (first row, second column)
○ arr[0][2] – third element (first row, third column)
○ arr[1][0] – fourth element (second row, first column)
○ arr[1][1] – fifth element (second row, second column)
○ arr[1][2] – sixth element (second row, third column)
Accessing array elements in a two dimensional array
1. #include <iostream>
2.using namespace std; 3.
4. int main(){
5. int arr[2][3] = {{11, 22, 33}, {44, 55, 66}};
6. for(int i=0; i<2;i++){
7. for(int j=0; j<3; j++){
8. cout<<"arr["<<i<<"]["<<j<<"]: "<<arr[i][j]<<endl;
9. }
10. }
11. return 0;
12. }
Accessing array elements in a two dimensional array

● The above code gives the following output:


○ arr[0][0]: 11
○ arr[0][1]: 22
○ arr[0][2]: 33
○ arr[1][0]: 44
○ arr[1][1]: 55
○ arr[1][2]: 66
Three dimensional arrays
● Declaring a three dimensional array is done as follows:
○ int arr[2][3][2];
● Different methods can be used to initialize three dimensional arrays
● Method I:
○ int arr[2][3][2] = {1, -1 ,2 ,-2 , 3 , -3, 4, -4, 5, -5, 6, -6};
● Method II:
○ int arr[2][3][2] = {
○ { {1,-1}, {2, -2}, {3, -3}},
○ { {4, -4}, {5, -5}, {6, -6}}
○ };
● The second method is preferred because it allows you to visualize the
arrangement of your data in terms of rows and columns
Three dimensional array example
Three dimensional array example
● The output of the above code is
○ 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6
C++ Strings
● Strings are words that are made up of characters, hence they are
known as sequence of characters.
● In C++ we have two ways to create and use strings:
○ By creating char arrays and treat them as string
○ By creating string object
Creating Strings as array of characters

1. #include <iostream>
2. using namespace std;
3. int main(){
4. char book[50] = "I can, I must, I will";
5. cout<<book;
6.return 0; 7.
}
8.
Creating Strings as array of characters

● Also known as C Strings


● Example I
1. #include <iostream>
2. using namespace std;
3. int main(){
4. char book[50] = "I can, I must, I will";
5. cout<<book;
6. return 0;
7. }
● The above code produces the following output
○ I can, I must, I will
Getting user input as string

● cin object is not a convenient way to capture strings as user input.


● 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)
Getting user input as string

● Output:
1. Enter your favorite book name: Rich dad, poor dad
2. You entered: Rich
● The problem here is that only the word “Rich” got captured in
the variable book and remaining part after space got
ignored.
● In order to solve this problem we can use cin.get function,
which reads the complete line entered by user
Getting user input as string
1. #include <iostream>
2. using namespace std;
3. int main(){
4. char book[50];
5. cout<<"Enter your favorite book name:";
6.
7. //reading user input
8. cin.get(book, 50);
9. cout<<"You entered: "<<book;
10. return 0;
11. }
Getting user input as string

● Output:
○ Enter your favorite book name: My life, my purpose;
the president remembers
○ You entered: My life, my purpose; the president
remembers
Getting user input as string
● Size of the char array is fixed, which means the size of the string created
through it is fixed in size, more memory cannot be allocated to it during
runtime.
○ E.g., if you create an array of characters of size 20 and user enters the string
of size 25, the last five characters would be truncated from the string.
○ Also, if you create a larger array to accommodate user input then the
memory is wasted if the user input is small and array is much larger then
what is needed.
● In this method, you can only use the in-built functions created for array which
is not convenient for string manipulation.
Using the string object in creating strings

● string object is used to create string literals


● When using a string object in declaring variables, you
must include a string header file at the beginning of your
program
● Strings created using a string object are easily
manipulated using a variety of functions.
Using the string object in creating strings

● Advantages of using the string object to create strings


○ you don’t need to declare the size of the string, the size is
determined at run time, so this is better memory management
method.
○ The memory is allocated dynamically at runtime so no memory
is wasted.
Using the string object in creating strings
1. #include <iostream>
2. #include <string>
3. using namespace std;
4. int main(){
5. // This is how we create string object
6. string str;
7. cout<<"Enter a String:";
8. // This is used to get the user input and store it into str
9. getline(cin,str);
10. cout<<"You entered: ";
11. cout<<str<<endl;
12. return 0;
13. }
String concatenation
● Concatenating strings means joining two or more strings to make a
new string.
● Concatenation is aided by the + operator between strings to add them
together to make a new string.
1. #include <iostream>
2. #include <string>
3.using namespace std; 4.
5. int main () {
6. string firstName = "Sasha ";
7. string lastName = "Obama";
8. string fullName = firstName + lastName;
9. cout << fullName;
10. return 0;
11. }
Appending strings
● Appending strings means adding a string at the end of another string
● The append() method is used to append strings
● This means that you can use the append() method to concatenate strings
● However, append() is much faster than the + operator
1. #include <iostream>
2. #include <string>
3.using namespace std; 4.
5. int main () {
6. string firstName = "Sasha ";
7. string lastName = "Obama";
8. string fullName = firstName.append(lastName);
9. cout << fullName;
10. return 0;
11. }
Adding a character at the end of a string
● The push_back() method is used to add a character at the
end of a string.
1. #include <iostream>
2. #include <string>
3.using namespace std;
4.
5. int main () {
6. string college = "EAST";
7. college = college.push_back(‘C’);
8. cout << college;
9. return 0;
10. }
Removing a character from the end of a string
● The pop_back() method is used to remove a character at the
end of a string.
1. #include <iostream>
2. #include <string>
3.using namespace std;
4.
5. int main () {
6. string college = "EASTCK";
7. college = college.pop_back();
8. cout << college;
9. return 0;
10. }
String length
● The length() method is used to calculate the length of a given
string
○ string myName = "Sasha obama";
○ cout << "The length of the txt string is: " << myName.length();
● Its alias is the size() method which also returns the length of the
string
○ string myName = "Sasha obama";
○ Cout << "The length of the txt string is: " << myName.size();

You might also like