0% found this document useful (0 votes)
8 views27 pages

Chapter Four - Array and String

Chapter Four discusses arrays and strings in C++. It explains the definition, properties, and categorization of arrays, including declaration, initialization, and accessing elements. Additionally, it covers string representation, manipulation, and functions for copying and concatenating strings.

Uploaded by

zenebechmezgebe8
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)
8 views27 pages

Chapter Four - Array and String

Chapter Four discusses arrays and strings in C++. It explains the definition, properties, and categorization of arrays, including declaration, initialization, and accessing elements. Additionally, it covers string representation, manipulation, and functions for copying and concatenating strings.

Uploaded by

zenebechmezgebe8
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

Chapter Four

Array and String


Prepared by : Surafiel H.
Department of Computer Science,
Addis Ababa University
May, 2021
Array
• An array is a data structure which allows a collective name to be given to a
group of elements which all have the same type.
• A collection of identical data objects, which are stored in consecutive memory
locations under a common heading or a variable name.
• In other words, an array is a group or a table of values referred to by the same
name.
• The individual values in array are called elements.
• Set of values of the same type, which have a single name followed by an index.
• In C++, square brackets appear around the index right after the name.
• An individual element of an array is identified by its own unique index (or
subscript).

Fundamentals of Programming: Comp 2012 and Comp 2042 2


Properties of Arrays
• Arrays in C++ are zero-bounded; that is the index of the first element in the
array is 0 and the last element is N-1, where N is the size of the array.
• It is illegal to refer to an element outside of the array bounds, and your program
will crash or have unexpected results, depending on the compiler.
• Array can only hold values of one type.

Fundamentals of Programming: Comp 2012 and Comp 2042 3


Array Categorization
• Array can be categorized into two part:
1. One dimensional Array: collection of a fixed number of elements (of the same
type) arranged in one dimension as a list
2. Multi dimensional : collection of a fixed number of components (of the same
type) arranged in multi dimensions

Fundamentals of Programming: Comp 2012 and Comp 2042 4


Declaration of One-dimensional Array
• Declaring the name and type of an array and setting the number of elements in
an array is called dimensioning the array.
• The array must be declared before one uses in like other variables.
• In the array declaration one must define:
1. The type of the array (i.e. integer, floating point, char etc.)
2. Name of the array,
3. The total number of memory locations to be allocated or the maximum value of
each subscript. i.e. the number of elements in the array.
• So the general syntax for the declaration is:
DataTypename arrayname [array size];
• The array size must be an integer constant or integral constant expression and
must have a value at compilation time.
Fundamentals of Programming: Comp 2012 and Comp 2042 5
Cont’d
• Examples:
float score[20]; //score can store 20 float value
char letterGrade[50]; //letterGrade can store 50 char value
int next, score[5], max; // declare arrays and regular variables together
const unsigned int SIZE=50;
double temp[2*SIZE]; //constant expression for dimension (array size)
int i=15, temp[i]; //invalid declaration
• Note: array size cannot be a variable whose value is set while the program is
running.
Fundamentals of Programming: Comp 2012 and Comp 2042 6
Initializing Arrays
• An array can be initialized with the initial values, which are given as a list enclosed in
curly brackets {}.
• Syntax:
Option 1:
type array_Name[dimension/size] = { value0, value1, ..,valueN};
Option 2:
type array_Name[dimension/size] { value0, value1, ..,valueN};
• Where
• type specify that what kind of array you are declaring.
• array_Name specify the name (identifier) of the array.
• dimension specifies the size of the array.
• value0, value1,…,valueN specify the initial values for array_Name[0],
array_Name[1],…, array_Name[N] respectively.
• Dimension is optional; the compiler can determine the dimension (the size of
the array) from the list of initial values.
Fundamentals of Programming: Comp 2012 and Comp 2042 7
Cont’d
• For example initializing an array to hold the first few prime numbers could be
written as follows:
int primes [] = {1, 2, 3, 5, 7, 11, 13};

Fundamentals of Programming: Comp 2012 and Comp 2042 8


Cont’d
• int nums [5] = {16, 2, 77, 40, 12071}
• The above declaration would have created an array like the following one:

• The number of elements in the array that we initialized within curly brackets { }
must be equal or less than the length in elements that we declared for the array
enclosed within square brackets [ ].
• If we have less number of items for the initialization, the rest will be filled with
zero.
Fundamentals of Programming: Comp 2012 and Comp 2042 9
Cont’d
• For example, in the example of the nums array we have declared that it had 5
elements and in the list of initial values within curly brackets { } we have set 5
different values, one for each element.
• If we ignore the last initial value (12071) in the above initialization, 0 will be
taken automatically for the last array element.
• C++ allows the possibility of leaving empty the brackets [ ], where the number
of items in the initialization bracket will be counted to set the size of the array.
int nums [] = { 1, 2, 7, 4, 12,9 };
• The compiler will count the number of initialization items which is 6 and set the
size of the array day to 6 (i.e.: nums[6]).

Fundamentals of Programming: Comp 2012 and Comp 2042 10


Cont’d
• We can use the initialization form only when defining the array; we cannot use
it later.
• We cannot assign one array to another once.
i.e.
int arr [] = {16, 2, 77, 40, 12071};
int ar [4];
ar[]={1,2,3,4};//not allowed
arr=ar;//not allowed
• Note: when initializing an array, we can provide fewer values than the array
elements.
E.g. int a [10] = {10, 2, 3}; // in this case the compiler sets the remaining
elements to zero.
Fundamentals of Programming: Comp 2012 and Comp 2042 11
Accessing and Processing Array Elements
• To access individual elements of an array, index or subscript is used.
• The format is the following:
• Array_Name [ index ]
• In C++ the first element has an index of 0 and the last element has an index,
which is one less the size of the array (i.e. arraysize-1).
• Example:
int nums [] = {16, 2, 77, 40, 12071}

• Thus, from the above declaration, nums[0] is the first element and nums[4] is
the last element.
Fundamentals of Programming: Comp 2012 and Comp 2042 12
Cont’d
• Following the previous examples where nums had 5 elements and each element
is of type int, the name, which we can use to refer to each element, is the
following one:

• For example, to store the value 75 in the third element of the array variable
nums a suitable sentence would be:
nums[2] = 75; //as the third element is found at index 2
• To pass the value of the third element of the array variable nums to the variable
a , we could write:
int a = nums[2];

Fundamentals of Programming: Comp 2012 and Comp 2042 13


Cont’d
• An element of an array can be used any where a variable can be used.
• Assuming the following declaration
int arr[20]={1}, i=1, y=3;
• An element of array can be assigned:
arr[4] = 55; //The fifth element of the array arr assigned 55
• It can be used in an expression(as lvalue and rvalue):
arr[2*i +1] = 3*y + arr[2*i]; //the 4th element is assigned 10
• It can be used in an input-output statement:
cin >> arr[18]; //the 19th element will be an integer read from keyboard
cout << arr[15]; //The 16th will be displayed on the screen

Fundamentals of Programming: Comp 2012 and Comp 2042 14


Cont’d
• It is important to be able to clearly distinguish between the two uses the square
brackets [ ] have for arrays.
• One is to set the size of arrays during declaration
• The other is to specify indices for a specific array element when accessing the
elements of the array.
• We must take care of not confusing these two possible uses of brackets [ ] with arrays:
• Example:
int nums[5]; // declaration of a new Array (begins with a type name)
nums[2] = 75; // access to an element of the Array.
• Other valid operations with arrays in accessing and assigning:
int a=1;
nums [0] = a;
nums[a] = 5;
b = nums [a+2];
nums [nums[a]] = nums [2] + 5;
nums [nums[a]] = nums[2] + 5;
Fundamentals of Programming: Comp 2012 and Comp 2042 15
Cont’d
• Consider the following array declaration:
int lista[]={5, 7, 9, 6, 4}, listb[5];
• Attempting to access a nonexistent array element leads to a serious runtime
error called “index out of bounds” error.
• The compiler won’t complain if you assign a value to the nonexistent element.
Your code will compile.
listb[5]=lista[0]; // index out of bounds error
cout <<lista[-1] ; // index out of bounds error
cout<<lista[5]; // index out of bounds error
• C++ does not allow aggregate operations on an array:
listb=lista; //illegal! Copy element by element.
cin >> listb; //illegal! Read element by element.
cout << listb; //illegal! Display element by element.
Fundamentals of Programming: Comp 2012 and Comp 2042 16
Cont’d
• Example: display the sum of the numbers in the array.
#include <iostream>
int nums [ ] = {1, 2, 3,4,5};
int n, sum=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
sum += nums[n];
}
cout << sum;
}
Fundamentals of Programming: Comp 2012 and Comp 2042 17
Strings Representation and Manipulation
• String in C++ is nothing but a sequence of character in which the last character
is the null character ‘\0’.
• The null character (‘\0’) indicates the end of the string.
• In C++ strings of characters are held as an array of characters, one character
held in each array element.
• In addition a special null character, represented by `\0', is appended to the end of
the string to indicate the end of the string.
• Hence if a string has n characters then it requires an n+1 element array (at least)
to store it.
• A string variable s1 could be declared as follows:
char s1[10];

Fundamentals of Programming: Comp 2012 and Comp 2042 18


Cont’d
• The string variable s1 could hold strings of length up to nine (9) characters since
space is needed for the final null character.
• Strings can be initialized at the time of declaration just as other variables are
initialized. For example:
char s1[] = "example"; • In the first case the array would be
allocated space for eight characters,
char s2[20] = "another example" that is space for the seven characters
of the string and the null character.
• Would store the two strings as follows: • In the second case the string is set
by the declaration to be twenty
characters long but only sixteen of
these characters are set, i.e. the
fifteen characters of the string and
the null character.
• Note that the length of a string does
not include the terminating null
character.
Fundamentals of Programming: Comp 2012 and Comp 2042 19
Initialization of Strings
• We could initialize the string with values by any of these two ways:
char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char mystring [] = "Hello";
• In both cases the Array or string of characters mystring is declared with a size
of 6 characters (elements of type char ).
• In the first case, the 5 characters that compose Hello plus a final null character
('\0') which specifies the end of the string.
• In the second case, when using double quotes ( " ) it is automatically appended.
• Note that the assignation of multiple constants like double-quoted constants ( " )
to arrays are only valid when initializing the array, that is, at the moment when
declared.

Fundamentals of Programming: Comp 2012 and Comp 2042 20


String Output and Input
• A string is output by sending it to an output stream:
• Example 1:
char s1[] = "example";
cout << "The string s1 is " << s1 << endl; //prints the string example.
• Example 2:
char string1 []= "Please be";
char string2 [] = {' ','a', ' ','k', 'i','n','d','\0'};
cout<<string1<<string2; // prints the string Please be a kind

Fundamentals of Programming: Comp 2012 and Comp 2042 21


Cont’d
#include <iostream>
using namespace std;
int main()
{
char firstName [20];
char middleName [20];
char lastName [20];
cout<<"Please enter your first name\n";
cin>>firstName;
cout<<"Please enter your middle name\n";
cin>>middleName;
cout<<"Please enter your last name\n";
cin>>lastName;
cout<<"Your full name is "<<firstName<<" "<<middleName<<" "<<lastName;
}
Fundamentals of Programming: Comp 2012 and Comp 2042 22
Copying String - The Easy Way
• Strings can be copied using strcpy or strncpy function.
• We assign strings by using the string copy function strcpy.
• The prototype for this function is in string.h.
Syntax:
strcpy(destination, source);
• strcpy copies characters from the location specified by source to the location
specified by destination.
• It stops copying characters after it copies the terminating null character.
• The return value is the value of the destination parameter.
• You must make sure that the destination string is large enough to hold all of the
characters in the source string (including the terminating null character).
Fundamentals of Programming: Comp 2012 and Comp 2042 23
Cont’d
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char me[20] = "Abebe";
cout << me << endl;
strcpy(me, "You are not Abebe");
cout << me << endl ;
}

Fundamentals of Programming: Comp 2012 and Comp 2042 24


Concatenating Strings
• You can use strcat() or strncat().
• The function strcat concatenates (appends) one string to the end of another
string.
Syntax:
strcat(destination, source);
• The first character of the source string is copied to the location of the
terminating null character of the destination string.
• The destination string must have enough space to hold both strings and a
terminating null character.

Fundamentals of Programming: Comp 2012 and Comp 2042 25


Cont’d
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strcat(str1, "def");
cout << str1 << endl;

char str2[] = "xyz";


strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl;
}
Fundamentals of Programming: Comp 2012 and Comp 2042 26
Comparing Strings
• Strings can be compared using strcmp or strncmp functions
• The function strcmp compares two strings by comparing the ASCII value of each character in the string.
strcmp(str1, str2);
strcmp returns:
< 0 (-1) if str1 is less than str2
=0 if str1 is equal to str2
> 0 (1) if str1 is greater than str2
• Example:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
cout << strcmp("abc", "def") << endl;
cout << strcmp("def", "abc") << endl;
cout << strcmp("abc", "abc") << endl;
cout << strcmp("abc", "abcdef") << endl;
cout << strcmp("abc", "ABC") << endl;
}

Fundamentals of Programming: Comp 2012 and Comp 2042 27

You might also like