Unit 4 Arrays
Unit 4 Arrays
1
Objective
2
What is an array?
• An array is a data structure that represents a collective name to be given to a group of
elements which all have the same type (int, char or float).
• As you can see in the figure below, all are similar values which are integer values.
• An individual element of an array is identified by its own unique index (or subscript).
• You can consider index as the position of the value.
• For example, the index (position) of the value 56 is 0, the index of the value 34 is 3 and so
on.
Index 0 1 2 3 4 5 6 7 8 9
Value 56 89 90 34 37 55 0 23 -56 67
3
Index 0 1 2 3 4 5 6 7 8 9
An array(cont’d)
Value 56 89 90 34 37 55 0 23 -56 67
•An array can be thought of as a collection of numbered boxes (0 through 9) based on figure
where each containing one data item.
E.g. index 5 contains 55, index 7 contains 23 and so on.
•To access a particular item or value in the array, the index associated with the item is used to
access the appropriate value.
E.g. if the name of the array is num, num[6] is refers to 0, num[5] refers to 55 and
so on.
•The index must be an integer and indicates the position of the element in the array.
•Thus, the elements of an array are ordered by the index which starts from 0.
4
Declaration of Arrays
One Dimensional Array
Arrays occupy space in memory when you declare them.
An array declaration is very similar to a variable declaration.
First a type is given for the elements of the array,
then an identifier for the array and,
within square brackets, the number of elements in the array (size of the array is must be
written).
The number of elements (size) must be an integer constant greater than zero.
5
Declaration of Arrays
The programmer specifies the type and the number of elements required by an array as follows:
type variable; // this is a variable declaration like int x;
type arrayName [ arraySize ]; // this is array declaration
Example 1: The marks of 5 students can be stored in an array declared as:
int mark[5];
•This declaration will cause the compiler to allocate 5 spaces consecutive int variables in memory
by the name mark.
6
Declaration of Arrays(cont’d)
Example 2: Data on the average temperature over the year in Ethiopia for each of the last 100 years
could be stored in an array declared as follows:
float annual_temp[100];
This declaration will cause the compiler to allocate space for 100 consecutive float variables in memory by
the name annual_temp.
It is best to make the array size a constant by using const specifier.
E.g. const int max = 5;
int mark[max]; 0 1 2 3 4
In this case, the array mark can store maximum 5 integer values. 7
Declaration of Arrays(cont’d)
If you want to change the size of the array, just change the value of max which is a constant value.
Previously, max were 5, to change the size of array (max) to 10, write the following:
const int max = 10;
int mark[max];
If more records come to light, it is easy to increase the program to cope with more values by
changing the value of max.
This works well because the compiler knows the value of the constant max at compile time and can
allocate an appropriate amount of space for the array.
8
Accessing Individual Array Elements
Index 0 1 2 3 4 5 6 7 8 9
Value 56 89 90 34 37 55 0 23 -56 67
The first element in an array in C++ always has the index 0, and
if the array has n elements the last element will have the index n-1.
The first element in an array is 56. Hence, it has the index 0.
The number of elements in the array above is 10. However, the last element which is 67 has the index 9
(10-1).
An array element is accessed by writing the identifier of the array followed by the subscript in square
brackets.
For example, to access the 89, write as mark[1], to retrieve the value 23, write as mark[7].
Hence, in the above example, the 8th element has index 7. 9
Accessing Individual Array Elements
0 1 2 3 4 5 6 7 8 9
45 66 97 42 78 12 45 87 36 67
10
Accessing Individual Array Elements
13
Example
#include <iostream> cout << odd[7] << endl << endl;
using namespace std; cout << odd[6] << endl << endl;
67
13
14
18
Accessing the whole Elements of the array
15
Example
/*Write a program which stores (initializes) the first 10 odd numbers and display them.*/
#include <iostream>
int main()
return 0;
} 16
Reading elements of the array from the keyboard
Like accessing (retrieving) the whole elements of the array, reading from the keyboard is
performed using for loops.
Example, to read 10 elements and store it in an array whose name is odd, write the
following code:
for(int i=0; i<10;i++) //for loop to read and put elements into the array
cin>>odd[i];
17
Example
#include <iostream> Output of the above program:
using namespace std; Enter five integer numbers
int main() { 56
int num[5]; 69
cout << "Enter five integer numbers"; 75
for(int j = 0; j < 5; j++) 88
cin >> num[j]; //56, 69, 75, 88, 78 78
for(int i = 0; i < 5; i++) 56 69 75 88 78
cout << num[i] << " ";
return 0;
}
18
Copying Arrays
•Copying array elements is possible as long as the size of destination array is greater than or equal to the
size of source array.
•For example,
const int max1=6;
int x[max1];
int y[max2];
19
Copying Arrays
If you want to copy the second element of the array x into the third position of y, we
should write as: y[2] = x[1];.
The second position is at index 1 and the third position is at index 2 because index of
array starts from 0.
To copy all elements of the array, use for loop. . //a for Loop to copy one item at a time.
E.g. for (int i = 0 ; i < max; i++); y[i] = x[i];
20
Example
Write a program which declares two arrays with size of 10 and reads cin>>num1[j];
the elements to the first array and copy the elements into the second
for(int k=0; k<10; k++)
array.
num2[k]=num1[k];
#include<iostream>
for(int i=0; i<10;i++)
using namespace std;
cout <<num2[i]<<" ";
int main() {
return 0;
int num1[10];
}
int num2[10];
Output of the above program:
cout <<"Enter ten integer numbers"; Enter ten integer numbers
21
Multidimensional arrays
22
Declaration of Two Dimensional Array
•This implies that the array has 4 groups and in each group there are 3 individual values.
E.g. board={{2,3,4},{7,8,9},{2,1,5},{8,3,2}};
0 1 2
• In other words, the first number which is 4 implies the number of rows. 0
1
• The second number which is 3 is the number of columns. 2
• This is illustrated the array ‘board[4][3]’ has 4 rows and 3 columns. 3
23
Declaration of Two Dimensional Array
When we fill the data listed above the figure look like this:
0 1 2
0 2 3 4
1 7 8 9
2 2 1 5
3 8 3 5
24
Initializing Multidimensional Arrays
•To initialize a multidimensional array, you must assign the list of values to array elements in order.
•Therefore, if the program has an array of int Ar[5][3], 0 1 2
0 1 2 3
the first three elements go int Ar[0]; the next three into Ar[1]; and so forth.
1 4 5 6
The program initializes this array by writing: 2 7 8 9
3 10 11 12
int Ar[5][3] ={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 4 13 14 15
•However, for the sake of clarity, the program could group the initializations with braces, as shown
below:
int Ar[5][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13, 14,15} };
25
Accessing individual elements of the 2D array
•In order to access individual elements of the array, we should use two indices.
•One for the row/group and the other for the columns/individual.
•E.g. in order to access the element in
Row index 2 and column index 1 which is 8, we should write as: Ar[2][1].
Row 3 and column 2 which is 12, write: Ar[3][2].
Row 1 column 0 which is 4 , write: Ar[1][0].
26
Accessing the whole elements of the two dimensional array
•If you want to access all elements of the array, use cout<<Ar[i][j];
nested for loops. but if you want to display the array 'Ar' as matrix
•The following code is used to display the whole form use the following code:
elements of the 5 by 3 array of name 'Ar'.
for(int i=0; i<5; i++)
for(int i=0; i<5; i++) //this loop is used to display the
{ for(int j=0; j<3; j++)
row or groups
}
27
Example
#include <iostream>
10 11 12
for (int j = 0; j<3; j++) {
13 14 15
cout <<Ar[i][j]<<" ";
cout <<endl; }
return 0; }
28
Reading and Storing Individual elements from or to 2D Array
•Reading and storing for individual elements of the array 'Ar'
If you want to read and put into
the first row and third column, write it as: cin>>Ar[0][2].
Second row and fourth column, cin>>Ar[1][3]; and so on.
#include<iostream>
int main(){
cout<<endl;
}return 0;
31
Example
//Write a program which reads a 5 by 3 matrix and for ( int i=0; i<5; i++) {
display them in a matrix format.
for (int j = 0; j<3;j++)
#include<iostream>
cout <<SomeArray[i][j] << " ";
using namespace std;
cout <<endl;
int main(){
}
int SomeArray[5][3];
return 0;
for(int i=0; i<5; i++)
}
for(int j=0; j<3; j++)
cin>>SomeArray[i][j];
32
String
String in C++ is nothing but a sequence of character.
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++
33
C-Style Character String
•It is originated within the C language and continues to be supported within C++.
•In the case of C-style character string,
•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' (backslash and zero),
is appended to the end of the string to indicate the end of the string.
34
C-Style Character String (cont’d)
Where as the single-character string "a" is stored in two consecutive bytes holding the
character `a' and the null character as : a \0
35
Declaration of a C-style character string
•Strings can be initialized at the time of declaration just as other variables are initialized.
For example: char s1[] = "example";
•s1 also can be initialized like the following: char s1[] = {‘e’, ‘x’, ‘a’, ‘m’, ‘p’, ‘l’, ‘e’, '\0'};
•Inside the memory, s1 is stored like the following : e x a m p l e \0
36
Accessing each characters of the C-style character string
If you want to display individual characters from a string, use the index of the character.
to display the letter ‘p’, write cout<<s1[4],
to display the letter x, write cout<<s1[1].
Accessing all the String
If you want to display the whole elements, write only the name of the array.
to display all the content of the string s1, write:
cout<<s1;
37
Accessing all the characters one by one
•If you want to display the entire characters one after the other, use for
loops.
for(int i=0; i<8; i++)
cout<<s1[i];
38
Reading C-style character string from the keyboard
When the input stream cin is used space characters, newline etc. are used as separators and
terminators.
Thus when inputting numeric data cin skips over any leading spaces and terminates reading a value
when it finds a white-space character (space, tab, newline etc. ).
This same system is used for the input of strings, hence a string to be input cannot start with
leading spaces, also if it has a space character in the middle then input will be terminated on that
space character.
The null character will be appended to the end of the string in the character array by the stream
functions
39
Example
#include <iostream> Output of the above program:
using namespace std; Enter a string
int main() {
EthioProgramming
const int max = 80;
You entered: EthioProgramming
char str[max];
cout <<"\nEnter a string";
cin >> str;
cout << "\n You entered: " << str;
return 0;
}
40
Copying and Concatenation of the String
•In C++ the + operator cannot normally be used to concatenate string, as it can in some languages
such as BASIC; that is you can't say Str3 = str1 + str2; rather you can use strcat() or strncat.
•The function strcat concatenates (appends) one string to the end of another string:
•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.
43
Example:
#include<iostream> strcat(str1, "def");
cout << str1 << endl;
#include<string.h>
char str2[] = "xyz";
using namespace std;
strcat(str1, str2);
int main() {
cout << str1 << endl;
char str1[30];
str1[4] = '\0';
strcpy(str1, "abc");
cout << str1 << endl;
cout << str1 << endl;
return 0;
}
44
Questions ???
Thank you!!!
45