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

Chapter 5 (Array and Strings)

The document discusses arrays and strings in C++, including how to declare and initialize arrays, access array elements, use multidimensional arrays and pass arrays as function parameters, the relationship between pointers and arrays, and representations of strings as both C-style character arrays and the string class.

Uploaded by

Sølø Ëd
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

Chapter 5 (Array and Strings)

The document discusses arrays and strings in C++, including how to declare and initialize arrays, access array elements, use multidimensional arrays and pass arrays as function parameters, the relationship between pointers and arrays, and representations of strings as both C-style character arrays and the string class.

Uploaded by

Sølø Ëd
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Arrays and Strings

Agenda
 Introduction
 Declaration and Initialization of Arrays
 Accessing Elements of Arrays
 Multidimensional Arrays
 Arrays as parameters
 Pointers and Arrays
 Strings
 The C-Style Character String
 The string class
 The String Class Operators
 The string Class functions
Introduction
• Array
– Group of consecutive memory locations
– Same name and type
• To refer to an element, specify
– Array name
– Position number
• Format:
arrayname[ position number ]
– First element at position 0
– n element array named c:
• c[ 0 ], c[ 1 ]...c[ n – 1 ]
Array Declaration
• Like a regular variable, an array must be declared before it is
used.
• Syntax: type name [elements];
– type is a valid type (like int, float...),
– name is a valid identifier
– the elements field (which is always enclosed in square brackets []),
specifies how many of these elements the array has to contain.
• must be a constant value

– Example
• int myArray [5];
– Declaring multiple arrays of same type
• int b[ 100 ], x[ 27 ];
Initialization of Arrays
• Array declaration doesn’t give value to its elements
– Locally declared arrays (e.g. within a function)
• their content will be undetermined until we store some value in them.
– Global and static arrays are automatically initialized with their default
values,
• for all fundamental types they are filled with zeros.
• Two Options to initialize arrays
– when they are declare
int myArray[ 5 ] = {16, 2, 77, 40, 12071};
• If not enough initializerss, rightmost elements become 0
• All elements 0
int n[ 5 ] = { 0 }
• If too many - a syntax error is produced syntax error
Initialization of Arrays…
 If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
 5 initializers, therefore 5 element array

 After declaration – by referring each element


 E.g.
 int x[3];
…

 X[0] = 12;

 X[1] = 4;

 X[2] = 5;
Accessing the values of an array.
 We can access the value of any of arrays elements individually as
if it was a normal variable using the format: name[index]
 E.g.
 myArray[2]= 2;
 to store the value 75 in the third element of my array
 a = myArray[2];
 to pass the value of the third element of billy to a variable called a
 Some other valid operations with arrays:
 myArray[0] = a; – b = myArray [a+2];
 myArray[a] = 75; – myArray[myArray[a]] = myArray [2] + 5;
Example
 The examples
#include<iostream.h>
show how to
#include<conio.h>
use arrays.
int myArray [] = {16, 2, 77, 40, 12071};
int n, result=0;
It adds contents
void main (){
of myArray
for ( n=0 ; n<5 ; n++ )
result += myArray[n];
cout << "Total = "<<result;
getch();
}
Multidimensional Arrays
 Multidimensional arrays can be described as "arrays of arrays“
 For example, a bidimensional array can be imagined as a
bidimensional table made of elements, all of them of a same
uniform data type.

 myArray2 represents a bidimensional array of 3 per 5 elements of type


int.
 to declare this array
 int jimmy [3][5];

 to reference the second element vertically and fourth horizontally in an


expression would be:
 jimmy[1][3]; // remember that array indices always begin by zero
Multidimensional Arrays…
 Multidimensional arrays are not limited to two indices (i.e., two
dimensions).
 They can contain as many indices as needed.
 But be careful! The amount of memory needed for an array
rapidly increases with each dimension.
 Multidimensional arrays are just an abstraction for programmers
 we can obtain the same results with a simple array just by
putting a factor between its indices
 int jimmy [3][5]; // is equivalent to
 int jimmy [15]; // (3 * 5 = 15)
Multidimensional Arrays…

No output but both assign values to the memory block called


jimmy in the following way:
Multidimensional Arrays…
 The preceding way of initializing arrays can also be done as
int jimmy[3][5] = { {1, 2, 3, 4, 5},
{2, 4, 6, 8, 10},
{3, 6, 9, 12, 15}}; //or
int jimmy[3][5] = { 1, 2, 3, 4, 5, 2, 4, 6, 8, 10,3, 6, 9, 12, 15};
 You can check this by printing the array using the code below

for (int n=0;n<3;n++) {


for (int m=0;m<5;m++)
cout<<jimmy[n][m]<<"\t";
cout<<endl;
}
Arrays as parameters
 At some moment we may need to pass an array to a function as a
parameter.
 C++ does not allow to pass an entire array as an argument to a
function.
 However,You can pass a pointer to an array by specifying the array's
name without an index.
 To pass an array as an argument in a function, you would have to
declare function formal parameter in one of following three
ways
 As a pointer: void myFunction(int *param) { . . . }
 as a sized array: void myFunction(int param[10]) { . . . }
 s an unsized array: void myFunction(int param[]) { . . . }
Arrays as parameters
 all three declaration methods produce similar results because each tells
the compiler that an integer pointer is going to be received.
 Now consider the following function
double getAverage(int arr[], int size) {
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i)
sum += arr[i];
avg = double(sum) / size;
return avg;
}
Arrays as parameters…
 Now let us call the above function as follows
#include <iostream.h>
#include <conio.h>
double getAverage(int arr[], int size);
void main (){
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
avg = getAverage( balance, 5 ) ;
cout << "Average value is: " << avg << endl;
getch();
}
Example: Sort
• Sorting data
– Important computing application
– Virtually every organization must sort some data
• Bubble sort (sinking sort)
– Several passes through the array
– Successive pairs of elements are compared
• If increasing order (or identical ), no change
• If decreasing order, elements exchanged
– Repeat
• Example:
– original: 3 4 2 6 7
– pass 1: 3 2 4 6 7
– pass 2: 2 3 4 6 7
– Small elements "bubble" to the top
Example: Sort…
…

Bubble sort: if
elements out of order,
swap them.
Pointers and Arrays
 The pointers and arrays have a very close relationship.
 The name of an array is actually a pointer to the first element in the array.
For example,
int age[];
int *p;
p=&age;
 p will point to the address of the first element of the array.
 Writing age[3] tells the compiler to return the element that is 3 away
from the starting element of age.
 Pointers are helpful where size of the array is unknown.
 Declaring the array with a size of large value wastes lot of space.
 Pointers improve the execution time.
 Here is a program which illustrates the working of arrays and pointers
Pointers and Arrays, example
#include<iostream>
using namespace std;
void main() {
int age[5];
int *p;
int sum=0,i;
The pointer p points to the
char yes='y';
first element of the array
p=age;
for(i=0;i<5;i++) {
cout << "Enter the age of a student" << endl;
cin >> *p;
sum=sum+*p;
p++;
}
p=age;
cout << "The sum of the ages" << sum << endl;
cout << "The age of the last student is : " << *(p + 4) << endl;
}
Strings
 A string is a series of characters.
 The only strings you've seen until now have been unnamed string
constants used in cout statements, such as
 cout << "hello world.\n";

 C++ provides following two types of string representations:


 The C-style character string.
 The string class type introduced with Standard C++.
The C-Style Character String
 Originated within the C language and continues to be supported
within C++
 is actually a one-dimensional array of characters which is
terminated by a null character '\0‘
 E.g.
 char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
 char greeting[] = "Hello";
 Memory presentation of above defined string in C/C++
The C-Style Character String…
 Actually, you do not place the null character at the end of a string
constant.
 The C++ compiler automatically places the '\0' at the end of the string
when it initializes the array.
 Another frequently used method to assign values to an array is by
directly using the input stream (cin).
 When cin is used with strings of characters it is usually used
with its getline method, that can be called following this
prototype:

cin.getline ( char buffer[], int length, char delimiter = ' \n');


The C-Style Character String…
 where
• buffer is the address of where to store the input
• length is the maximum length of the buffer
• delimiter is the character used to determine the end of the user input,
which by default - if we do not include that parameter - will be the
newline character ('\n').
#include <iostream.h>
void main (){
char mybuffer [100];
cout << "What's your name? ";
cin.getline (mybuffer,100);
cout << "Hello " << mybuffer << "\n";
cout << "Which is your favourite team? ";
cin.getline (mybuffer,100);
cout << "I like " << mybuffer << " too.\n";
}
The C-Style Character String Functions
 C++ supports a wide range of functions that manipulate null-
terminated strings
 strcpy(s1, s2) - Copies string s2 into string s1.
 strcat(s1, s2) - Concatenates string s2 onto the end of string
s1.
 strlen(s1) - Returns the length of string s1.
 strcmp(s1, s2) - Returns 0 if s1 and s2 are the same; less
than 0 if s1<s2; greater than 0 if s1>s2.
 strchr(s1, ch)- Returns a pointer to the first occurrence of
character ch in string s1.
 strstr(s1, s2) - Returns a pointer to the first occurrence of
string s2 in string s1.
Character String functions, example
#include <iostream.h>
void main (){
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
}
The String Class
 The standard C++ library provides a string class type that supports
 all the operations mentioned above,
 additionally much more functionality.

 Three major features:


 Don't have to worry about overflowing array boundaries
 Supports different functions
 Supports operators

 To use this class library file string.h should be included


The String Class…
 Multiple Declaration Formats:
 string str; //an empty string
 E.g. str = “abcdefgh”; //now a value is assigned
 string str (s);
 This creates and initializes str to contain a copy of s
 s may be a string or char array
 E.g.
 string s = “Hello there”;

 string str(s);

 string str (charAr, n);


 This creates and initializes str to contain a copy of the 1st n characters
of charAr
 Strng str(s, 5);//now str contains “Hello”
The String Class, Example
#include <iostream.h>
#include <string>
using namespace std;
void main (){
cout << "s4 is: " << s4 << endl;
char *line = "short line for testing";
// copy word 'line' from s3
string s1;
string s5 (s3,6,4);
s1 = "Anatoliy";
cout << "s5 is: " << s5 << endl;
string s6 (15,'*');
cout << "s1 is: " << s1 << endl;
cout << "s6 is: " << s6 << endl;
string s2 (s1);
string s7 (s3.begin(),s3.end()-5);
cout << "s2 is: " << s2 << endl;
cout << "s7 is: " << s7 << endl;
string s3 (line);
string s8 = "Anatoliy";
cout << "s3 is: " << s3 << endl;
cout << "s8 is: " << s8 << endl;
string s4 (line,10);
}
The String Class functions
 string class counterpart to strcpy
 str.assign(s) //s may be a string or char array
 copies s into str

 str.assign(s, p, n) //s is a string


 copies n characters from s into str, starting at position p

 str.assign(charAr, n) //charAr is a char array


 copies n characters from charAr into str

 string class counterpart to strcat:


 str.append(s) //s may be a string or char array
 Appends a copy of s onto str
The String Class functions…
 string class counterpart to strncat:
 str.append(s, p, n) // s is a string
 appends n characters from s onto str, starting at position p
 str.append(charAr, n)// charAr is a char array str
 appends n characters from charAr onto str

 string class counterpart to strcmp:


 str.compare(s) // s is a string or char array
 compares str to s
 returns: 0 if str is equal to s
negative value if str < s
positive value if str > s
The String Class functions…
 string class counterpart to strchr and strstr:
 str.find(s)
 returns position (subscript) of the first occurrence of s in str

 s is a string, char array, or char

 string class counterpart to strlen:


 str.length() or str.size()
 returns the length of str
 Other methods
 str.c_str() - converts the string object str to a null terminated char array
- returns:
 const char * str.substr(p, n) - returns a copy of a sub-string n characters
long, starting at position p
The String Class, Example
 string str = "Nobody is perfect";
 string s = ""; // empty string
 char *ch = "abcdef";
 s.append(str,0,6); // s is Nobody
 s.append(3,'!'); //s is now Nobody!!!
 s.append(ch,3); //s is now Nobody!!!abc
 s.assign(str); //s is now No body is perfect
 s.assign(str,10,7); // s is now perfect
 s.assign(ch,6); //s is now abcdef
 s.assign(ch); //s is now abcdef
 s.assign(7,'*'); //*******
 s.assign(str.begin(),str.end()); //s is now No body is perfect
 for ( int pos = 0; pos < s.length(); ++pos )cout << s.at(pos) << "/";
 //s is now N/o/ /b/o/d/y/ /i/s/ /p/e/r/f/e/c/t/
Converting strings to other types
 Due to that a string may contain representations of other data
types like numbers
 For example, a string may contain "1977", but this is a sequence of 5
chars not so easily convertable to a single integer data type.
 The cstdlib (stdlib.h) library provides three useful functions
to translate that content to a variable of a numeric type :
 atoi: converts string to int type.
 atol: converts string to long type.
 atof: converts string to float type.

 All of these functions admit one parameter and return a value of the
requested type (int, long or float).
The String Class Operators
 Assignment Operator (=): str = value;
 Assigns a copy of value to str
 value may be a string, char array, char
 String concatenation Operator (+): str + value or value + str
 returns the result of concatenating str and value
 value may be a string, char array, char
 Add to itself Operator (+=) : str += value;
 Appends a copy of value to str
 value may be a string, char array, char
 Subscript Notation: str[p]
 returns a reference to the character stored in str at position p
The String Class Operators…
 Relational Operators – the comparison is alphabetically
 str < s  s may be a string or char array
 str <= s  s may be a string or char array
 str > s  s may be a string or char array
 str >= s s may be a string or char array
 str == s  s may be a string or char array
 str != s  s may be a string or char array
The String Class Operators, Examples
 Examples
 String aa;
 String bb("Bill Clinton");
 aa = "put some value string"; // assignment operator
 aa += "add some more"; // Add to itself and assign operator
 aa = "My name is" + " Alavoor Vasudevan "; // string cat operator
 if (bb == "Bill Clinton") // boolean equal to operator
cout << "bb is equal to 'Bill Clinton' " << endl;
 if (bb != "Al Gore") // boolean 'not equal' to operator
cout << "bb is not equal to 'Al Gore'" << endl;

You might also like