Lecture 11
Lecture 11
Appropriate way:
int ages[5] = {0};
int main()
{
double values[] = {1, 2, 3};
cout << "The size of the array is: " << sizeof(values) << " bytes\n\n";
cout << "The size of one individual element is: " << sizeof(values[0])
<< " bytes\n\n";
system("pause");
return 0;
}
Finding out no. of elements of an array
How ?
int main()
{
int values[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
int sum = 0;
cout << endl
<< "There are "
<< sizeof (values) / sizeof(values[0])
<< "elements in the array."<< endl;
cout << "The sum of the array elements is " << sum << endl;
system("pause");
return 0;
}
Sample Output
Some Restrictions on Array Processing
Consider the following statements:
Solution:
Some Restrictions on Array Processing
(continued)
Solution:
Character Arrays
Just like we store integers in an integer array, we can
store characters in a character array.
int main()
{
char first[] = {'m', 'a', 's', 'u', 'd'};
char second[] = "masud";
cout << "Size of first: " << sizeof(first) << endl;
cout << "Size of second: " << sizeof(second) << endl;
system("pause");
return 0;
}
Output
int main()
{
char inputValues[30];
cout << "Enter a string: ";
cin >> inputValues;
cout << "\nThe string entered is: " << inputValues << endl << endl;
system("pause");
return 0;
}
Sample Output 1
~ seems correct ~
Sample Output 2
int main()
{
const int maxlength = 100;
char text[maxlength] = {0};
cout << endl << "Enter a line of text:" << endl;
cin.getline(text, maxlength);
cout << "You entered:" << endl << text << endl;
int vowels = 0;
int consonants = 0;
for(int i = 0 ; text[i] != '\0' ; i++)
{
if(isalpha(text[i]))
{
switch(tolower(text[i]))
{
Example Program (contd)
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowels++;
break;
default:
consonants++;
break;
}
}
}
cout << "Your input contained "
<< vowels << " vowels and "
<< consonants << " consonants."
<< endl << endl;
system("pause");
return 0;
}
Sample Output
int main()
{
char text[10] = {0};
cout << endl << "Enter a string:" << endl;
cin.getline(text, 10);
cout << "You entered:" << endl << text << endl << endl;
system("pause");
return 0;
}
Sample Output
Arrays as Function Arguments
To pass an array to a function, just use the array name:
showScores(tests);
showScores(tests, ARRAY_SIZE);
7-32
When whole array is being passed, we use [ ]
both in function prototype and function definition
38
Initialization & Printing
To initialize row number 4 (i.e., fifth row) to 0
39
Sum by Row
To find the sum of row number 4 of matrix:
int main()
{
double beans[3][4] = {
{ 1.0, 2.0, 3.0, 4.0},
{ 5.0, 6.0, 7.0, 8.0},
{ 9.0, 10.0, 11.0, 12.0}
};
total = 0;
for ( int row = 0; row < 3; row++ )
for ( int col = 0; col < 4; col++
)
total += a[ row ][ col ];
Class Task
Write a program that takes two 3 by 3 integer matrices
from user, and sum them up. The output matrix is
displayed to the user.
2 3 4 9 2 5
-1 3 0 0 5 4
33 -6 1 2 -3 3
Computing Mean, Median and Mode Using
Arrays
Mean
Average (sum/number of elements)
Median
Number in middle of sorted list
1, 2, 3, 4, 5 (3 is median)
If even number of elements, take average of middle
two
Mode
Number that occurs most often
1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)
48
Vectors
Vector is template class and is C++ only construct whereas arrays are built-in
language construct and present in both C and C++.
Vector are implemented as dynamic arrays with list interface whereas arrays can be
implemented as statically or dynamically with primitive data type interface.
Arrays cannot be copied or assigned directly whereas Vectors can be copied or
assigned directly.
Vectors are the same as dynamic arrays with the ability to resize itself automatically
when an element is inserted or deleted, with their storage being handled automatically
by the container.
Vectors are particularly helpful when you don’t know how large your collection of
elements will become.
To use vectors, you must include #include <vector> in the header of your program.
To create a vector, you need to include the following:
The keyword vector followed by the data type in angle brackets <>.
A variable name that refers to the vector.
The number of elements the vector can hold within parentheses ().
int array[100]; // Static Array Implementation
int* arr = new int[100]; // Dynamic Array Implementation
vector<int> v; // Vector's Implementation
Vectors
Size of arrays are fixed whereas the vectors are resizable, i.e., they can grow and shrink as vectors are
allocated on heap memory.
Arrays have to be deallocated explicitly if defined dynamically whereas vectors are automatically de-
allocated from heap memory.
int* arr = new int[100]; // Dynamic Implementation
delete[] arr; // array Explicitly deallocated
vector<int> v; // Automatic deallocation when variable goes out of
scope
To add elements to the vector, simply use the push_back() function.
To print an element within the vector, use the at() function and specify the index of the position of
the element you wish to print within the parentheses.
Vectors use the function size() to determine the number of elements that exist instead of the
operator sizeof() which is used for arrays.
vector <int> numbers(0); //vector with no elements
numbers.push_back(50); //add 50 as an element to end of vector
cout<< numbers.at(0)<< endl; //50 becomes first and only element.
cout<< numbers.size()<<endl;
To add an element to a specific index in the vector, you can use the insert() along with the begin()
functions like below.
numbers.insert(numbers.begin()+1, 50);//add 50 to index 1
Vectors
To remove an element from the end of a vector, use the pop_back().
numbers.pop_back(); //remove last element vector
To remove an element from a specific index in the vector, use the erase() function
and specify the index you want to erase with begin().
numbers.erase(numbers.begin() +1); //removes element from the index 1
To modify vector elements, use the at() method to specify the index number and
then assign a new element to it.
vector<string> contact(0);
contact.push_back("First name");
contact.push_back("Last name");
contact.push_back("Phone number");
contact.at(2) ="Email"; //change element at index 2 to "Email"
cout<<contact.at(0) <<“ “ <<contact.at(1)<<“ “ <<contact.at(2)<<endl;
It is possible to initialize elements inside a vector without constantly using
push_back().
vector<string>contact{"First name", "Last name", "Phone number"};
Iterating through a vector is very similar to iterating through an array.
vector<int>grades{85, 95, 48, 100, 92};
for(int i = 0; i < grades.size(); i++)
cout << grades.at(i) << endl;
Strings
Also called as C++ Style Strings (in contrary to C style
strings)
string a;
string student_name;
string home_address;
The solution?
string x = "10";
string y = "20"; How
string z = x + y; About
This ?
z will be 1020 (a string)
Example
#include <iostream>
using namespace std; Will generate a compile
time error. The second_string
array is too small to hold
int main() these values. The space
{ for ‘\0’ is not there. size = [6]
string first_string = "hello";
char second_string[5] = "world";
string final = first_string + second_string;
cout << final << endl;
system("pause");
return 0;
}
The Length of a String
The length of a string can be found by calling the length()
or size() function of the string.
For example
For example:
h
he
hel
hell
hello
el
ello
and many others.
Substring
To get a substring out of a string, the function substr of
the string object is called.
string a = “hello”;
a.substr(0, 2);
int main()
{
string my_string = "abcdefghijklmnop";
cout<<"The first ten letters of the alphabet are: " << first_ten;
cout << endl;
system("pause");
return 0;
}
Output
Example
#include <iostream>
using namespace std;
int main()
{
string my_string = "123456789";
system("pause");
return 0;
}
Output
Possible Error 1
int main()
Problem:
{
string my_string = "123456789"; There are not
enough characters
in the string to be
string endstring = my_string.substr(4, 14);
extracted
Outcome:
system("pause");
return 0; Compile Time Error
}
Comparing Strings
The simple equality check
string_one == string_two
int main()
{
string fstring = "12345";
if(fstring == sstring)
{
cout << "The strings are equal";
}
Example Code (contd)
else
{
cout << "The strings are not equal";
}
cout << endl;
cout << "Do you want to continue(yes/no): ";
cin >> choice;
}while(choice == "yes");
system("pause");
return 0;
}
Output
The compare() function
The compare() function is used to determine if a string is
greater than the other string.
int main()
{
string fstring, sstring, choice;
do{
cout << "Enter first string: ";
cin >> fstring;
cout << "\nEnter second string: ";
cin >> sstring;
cout << endl;
if(fstring.compare(sstring) > 0)
{
cout << "The first string is greater than the second string\n";
}
Example Code (contd)
else if(fstring.compare(sstring) < 0)
{
cout << "The first string is smaller than the second string\n";
}
else
{
cout << "The first string is equal to the second string\n";
}
cout << endl;
cout << "Do you want to continue(yes/no): ";
cin >> choice;
cout << endl << endl;
}while(choice == "yes");
system("pause");
return 0;
}
Output
More Output