0% found this document useful (0 votes)
45 views

Lecture 11

The document discusses initializing and using arrays in C++. It covers initializing arrays with values, initializing all elements to 0, determining the size of an array, and finding the number of elements. The document also discusses character arrays, C-strings, and using getline() to accept input. It provides examples of one-dimensional and two-dimensional arrays, initializing and accessing two-dimensional arrays, and passing arrays to functions.

Uploaded by

Naveed Iqbal
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Lecture 11

The document discusses initializing and using arrays in C++. It covers initializing arrays with values, initializing all elements to 0, determining the size of an array, and finding the number of elements. The document also discusses character arrays, C-strings, and using getline() to accept input. It provides examples of one-dimensional and two-dimensional arrays, initializing and accessing two-dimensional arrays, and passing arrays to functions.

Uploaded by

Naveed Iqbal
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 79

Lecture 11

Arrays, Vectors and Strings


Initializing Arrays
 One way we have seen to initialize array values is by
taking them from user.

 Another way is, we ourselves initialize array, as shown


below:
int ages[4] = {18, 19, 22, 21};
int numbers[7] = {1, 2, 4, 8}; They are initialized
// What about rest of the elements to 0
Initializing Arrays
 Initializing all elements to 0.
 One way:
 int ages[5] = {0, 0, 0, 0, 0};

 // How about an array of 100 elements?

 Appropriate way:
 int ages[5] = {0};

 // This will put the value of all the elements as 0.

 Can be specified with constant variable (const)


 const int size = 20;

 Constants cannot be changed


 Constants must be initialized when declared
Array Size
 An array may also be declared without specifying the
array size, but instead using the initializer list to set the
array size.

 int ages [ ] = {12, 17, 11, 8, 5};


 // will declare an array ages of size 5.

 Total memory occupied by the array, and memory


occupied by one element of the array can be determined
by sizeof().
sizeof() & sizeof [] Operators
 int ages[ ] = {12, 17, 11, 8, 5};

 sizeof(ages) will give us 20 bytes.

 sizeof(ages[0]) will give us 4 bytes.

 double myArray[] = {2.0, 9.0, 2.2};

 sizeof(myArray) will give us 24 bytes.

 sizeof(myArray[2]) will give us 8 bytes.


Usage
#include <iostream>
using namespace std;

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

 If we have total array size in bytes, and size of one individual


element in bytes, can we find out the number of elements in the
array?

 How ?

 No. of elements = size of array in bytes / size of one element

 24 / 8 = 3 (in previous example).


Example
#include <iostream>
using namespace std;

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;

for(int i = 0 ; i < sizeof (values) / sizeof(values[0]) ;


sum += values[i++]) ;

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:

 C++ does not allow aggregate operations on an array:

 Solution:
Some Restrictions on Array Processing
(continued)

 The following is illegal too:

 Solution:
Character Arrays
 Just like we store integers in an integer array, we can
store characters in a character array.

 E.g. char values[5] = {‘m’, ‘a’, ‘s’, ‘u’, ‘d’};


 stores ‘m’ at values[0]
 stores ‘a’ at values[1]
 and so on.
C-Strings (Character Arrays)
 Character array: an array whose components are of type
char
 C-strings are null-terminated ('\0') character arrays
 Example:
 'A' is the character A
 "A" is the C-string A
 "A" represents two characters, 'A' and '\0‘

 Difference between storing characters in an array and


storing a string in an array.
 char values[5] = {‘m’, ‘a’, ‘s’, ‘u’, ‘d’};
 char values[] = “masud”;
Output of this program ?
#include <iostream>
using namespace std;

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

Reasons: (2nd output)


 The last character is called “Null Character”
and is denoted as “\0”.

 It signifies the end of the string.


Another Program
#include <iostream>
using namespace std;

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

~ missing part of string ~


What is the problem?
cin.getline(string_name, length)
 The cin.getline() function lets us accept a line of text
from the keyboard, containing number of characters
equal to length.
 The default end of input character is ‘\n’. But we can
pass another argument to specify a character instead of
‘\n’.
 For example:
 cin.getline(string_name, length, ‘#’) means that # will
be used to indicate end of string_name.
Example Program
#include <iostream>
using namespace std;

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

Notice that capital A is also counted due to “tolower()” function


Also note that spaces are not ignored
Sample Output

cin.getline(text, maxlength, ‘#’);


cout << "You entered:" << endl << text << endl;
C-Strings (Character Arrays) (continued)
Class Task
 Write a program that takes a string of characters from
the user (assuming there are no white spaces entered)
and then tells the user if the string entered is a
palindrome or not. The string can be of any size from 2
to 9.
Code
#include <iostream>
using namespace std;

int main()
{
char text[10] = {0};
cout << endl << "Enter a string:" << endl;

cin.getline(text, 10);
cout << "You entered:" << endl << text << endl << endl;

int iSize, flag = 0;

for(iSize = 0; text[iSize] != '\0'; iSize++);

for(int i=0, j=(iSize-1); i<iSize/2, j>iSize/2; i++, j--)


{
if(text[i] != text[j])
{
flag = 1;
}
}
Code (contd)
if(flag == 0)
{
cout << "String is a palindrome\n";
}
else
{
cout << "String is not a palindrome\n";
}

system("pause");
return 0;
}
Sample Output
Arrays as Function Arguments
 To pass an array to a function, just use the array name:

showScores(tests);

 To define a function that takes an array parameter, use


empty [] for array argument:

void showScores(int []);


// function prototype

void showScores(int tests[])


// function definition
When a single element of an array is passed to a
function, it is handled like any other variable.
Arrays as Function Arguments
 When passing an array to a function, it is common to pass
array size so that function knows how many elements to
process:

showScores(tests, ARRAY_SIZE);

 Array size must also be reflected in prototype, header:

void showScores(int [], int);


// function prototype

void showScores(int tests[], int size)


// function header

7-32
When whole array is being passed, we use [ ]
both in function prototype and function definition

When entire array is being


passed to a function, it is passed
by reference. While single element
of array is always passed by value.
Two-Dimensional Arrays
 A two-dimentional array is like several identical arrays put
together. It is useful for storing multiple sets of data.
 Two-dimensional array: collection of a fixed number of
components (of the same type) arranged in two dimensions.
 Sometimes called matrices or tables.
 Declaration syntax uses two size declarators:

where intexp1 and intexp2 are expressions yielding


positive integer values, and specify the number of rows and
the number of columns, respectively, in the array
Two-Dimensional Arrays (continued)
Accessing Array Components (continued)
Syntax:

where indexexp1 and indexexp2 are expressions yielding


nonnegative integer values, and specify the row and column position.
Two-Dimensional Array Initialization During
Declaration
 Two-dimensional arrays can be initialized when they are
declared:

 Elements of each row are enclosed within braces and


separated by commas
 All rows are enclosed within braces
 For number arrays, if all components of a row aren’t
specified, unspecified ones are set to 0
Processing Two-Dimensional Arrays
 Each row and each column of a two-dimensional array is
a one-dimensional array
 Ways to process a two-dimensional array:
 Process the entire array
 Process a particular row of the array, called row
processing
 Process a particular column of the array, called
column processing

38
Initialization & Printing
 To initialize row number 4 (i.e., fifth row) to 0

 To initialize the entire matrix to 0:

 To print the components of matrix:

39
Sum by Row
 To find the sum of row number 4 of matrix:

 To find the sum of each individual row:


Sum by Column
 To find the sum of each individual column:
Passing Multidimensional Arrays to
Functions
 Multidimensional array parameters
 Size of first dimension is not required
 As with a one-dimensional array
 Size of subsequent dimensions are required
 Compiler must know how many elements to skip to
move to the second element in the first dimension
 Example
 void printArray(const int a[][3]);
Passing Two-Dimensional Arrays as Parameters
to Functions
 Two-dimensional arrays can be passed as parameters to
a function
 Pass by reference
 Base address (address of first component of the

actual parameter) is passed to formal parameter


 Two-dimensional arrays are stored in row order
 When declaring a two-dimensional array as a formal
parameter, can omit size of first dimension, but not the
second
// Passing a two-dimensional array to a function
#include <iostream>
using namespace std;

double yield(double values[][4], int n);

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}
};

cout << endl


<< "Yield = " << yield(beans, sizeof beans / sizeof beans[0])
<< endl;
return 0;
}
// Passing a two-dimensional array to a function….. Continued

// Function to compute total yield


double yield(double array[][4], int count)
{
double sum = 0.0;
for(int i = 0 ; i < count ; i++) // Loop through number of rows
for(int j = 0 ; j < 4 ; j++) // Loop through elements in a row
sum += array[i][j];
return sum;
}
Multidimensional-Array Manipulations
 Commonly performed with for statements
 Example
 Modify all elements in a row
for ( int col = 0; col < 4; col++ )
a[ 2 ][ col ] = 0;
 Example
 Total all elements

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)

 The String class

 The C++ String class is part of the std namespace and


allows you to manipulate strings safely.
Declaring and Initializing a String
 string identifier_name;

 string a;
 string student_name;
 string home_address;

 string student_name(“ali nisar”);


 string student_name = “ali nisar”;

 Both ways are valid, but it is recommended to use the


second way since all other variables are initialized that
way.
Input from User
 string student_name;
 cin >> student_name;

 The problem of terminating input at any white space.

 The solution?

 getline(cin, student_name, ‘\n’);

 Modified version of cin.getline() function.


Operations on Strings: Concatenation
 Concatenation means joining two strings together.
 Two strings can be concatenated together, using the +
operator.

 string first_name = “masud”;


 string last_name = “khokhar”;
 string full_name = first_name + last_name;
 cout << full_name; //Will display “masudkhokhar”

 Append() for concatenation

string firstName = "John ";


string lastName = "Doe";
string fullName = firstName.append(lastName);
Operations on Strings: Concatenation
 Two string objects can be concatenated.

 It is important to note that in the concatenation operation,


at least one of the operands has to be a string object.

 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

 string first = “hello”;


 string second = “ world”;
 string final = first + second;
 cout << “The string is: “ + final << endl;
 cout << “The length of the string is: “ << final.length();
 //We can achieve the same by calling final.size();
Output
Individual Elements of a String
 Strings can be treated internally as character arrays, with
each character on an individual index.

 For example:

string fullname = “masud khokhar”;


for (int i=0; i<fullname.length(); i++)
{
cout << “The “ << (i + 1) << “ character is: “ << fullname[i]
<< endl;
}
Output
Substring
 A substring is a part of a string.

 The substring of string “hello” can be

 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);

 The first argument specifies the position in the string a


from where to start calculating the substring.

 The second argument specifies the number of


characters that should be extracted from the string a.
Example
#include <iostream>
using namespace std;

int main()
{
string my_string = "abcdefghijklmnop";

string first_ten = my_string.substr(0, 10);

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";

string endstring = my_string.substr(4, 4);

cout<<"The output is: " << endstring;


cout << endl;

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

cout<<"The output is: " << endstring; Outcome:


cout << endl;
No error: All
characters
system("pause"); till the last character
return 0; are extracted
}
Possible Error 2
int main()
Problem:
{
string my_string = "123456789"; The start of the
string given is
invalid. The
string endstring = my_string.substr(14, 2);
compiler will not
know from which
cout<<"The output is: " << endstring; place to start
cout << endl; extracting characters

Outcome:
system("pause");
return 0; Compile Time Error
}
Comparing Strings
 The simple equality check

 string_one == string_two

 the compare() function


Example Code
#include <iostream>
using namespace std;

int main()
{
string fstring = "12345";

string sstring, choice;


do{
cout << "Enter a string: ";
cin >> sstring;

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.

 We first have to define what a greater string is.

 “B” is greater than “A”


 “c” is greater than “a”
 “ab” is greater than “a”
 “123” is greater than “122”
 Surprisingly “123” is also greater than “1229999”

 Reason is character by character matching.


The compare() function
 firststring.compare(secondstring);

 returns an integer value.

 If the integer value returned is greater than 0, than the


first string is greater than the second string.

 If the integer value returned is equal to 0, than the first


string is the same as the second string.

 If the integer value returned is less than 0, than the first


string is smaller than the second string.
Example Code
#include <iostream>
using namespace std;

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

You might also like