0% found this document useful (0 votes)
28 views45 pages

Unit 4 Arrays

Chapter 4 covers the concept of arrays in C++, including their definition, types, declaration, initialization, and accessing elements. It explains how to work with both one-dimensional and multi-dimensional arrays, providing examples for declaring, initializing, and manipulating array elements. The chapter emphasizes the importance of indices for accessing and modifying array values, as well as techniques for reading from and copying arrays.

Uploaded by

lastmikisahle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views45 pages

Unit 4 Arrays

Chapter 4 covers the concept of arrays in C++, including their definition, types, declaration, initialization, and accessing elements. It explains how to work with both one-dimensional and multi-dimensional arrays, providing examples for declaring, initializing, and manipulating array elements. The chapter emphasizes the importance of indices for accessing and modifying array values, as well as techniques for reading from and copying arrays.

Uploaded by

lastmikisahle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Chapter 4:Arrays

Compiled by Aye new(MPH in HI)

1
Objective

At the end of the lesson, student should be able to:


 Define the concept of array in C++
 Explain the types of array
 Write the program using single and multiple dimension of array

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

 An array element can be used anywhere an identifier may be used.


 Here are some examples assuming the following declarations:
 const int max = 10;
 int mark[max];
Let us assume the values in the table are values of the array mark declared above which has ten elements.
 To display the value 12, we should say: cout<<mark[5];
 To display the value 45, we should say: cout<<mark[6];

10
Accessing Individual Array Elements

 Moreover, we can also change the values of the array.


 For example, to change the element at index 3 which is 42 into 90, write mark[3]=90.
 A value can be read into an array element directly, using cin,
 cin >> mark[4];
 The element at index 4 which is 78 is changed to a value which is going to be accepted from the
keyboard.
 The element at index 8 which is 36 can be increased by 5,
 mark[8] = mark[8] + 5; or
 using the shorthand form of the assignment mark[8] += 5;
11
Initialization of arrays
Initialization is giving the initial value.
 The initialization of simple variables in their declaration has already been covered.
 An array can be initialized in a similar manner.
 In this case the initial values are given as a list enclosed in curly brackets.
 For example, initializing an array to hold the first 7 odd numbers could be written as
follows:
 int odd[] = {1, 3, 5, 7, 9, 11, 13};
Note that if we initialize an array, it is optional to give the size.
12
Initialization of arrays(cont’d)

We can omit the array size.


However, if the array is given a size, then this size must be greater than or equal to the
number of elements in the initialization list.
 For example: int odd[10] = {1, 3, 5, 7,9,11,13};
The array odd would reserve space for a ten elements array
but would only initialize the first seven elements.

13
Example
#include <iostream> cout << odd[7] << endl << endl;

using namespace std; cout << odd[6] << endl << endl;

int main() odd[6] += 5;


cout << odd[6] << endl << endl;
{
return 0;
int odd[10] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
}
cout << odd[7] << endl << endl;
Output of the above program:
odd[7]= 67; 15

67

13
14
18
Accessing the whole Elements of the array

 The whole elements of an array are accessed using for loops.


 E.g. to display all the elements of an array whose name is odd which has
10 elements, write the following code:
for(int i=0; i<10;i++) //for loop to display all elements of the array
cout<<odd[i]<<" ";

15
Example
/*Write a program which stores (initializes) the first 10 odd numbers and display them.*/

#include <iostream>

using namespace std;

int main()

int odd[10] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};

for(int i = 0; i < 10; i++)

cout << odd[i] << " ";

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;

const int max2=7;

int x[max1];

int y[max2];

•The size of x is less than the size of y.


•Hence, we cannot copy all the elements of y into x // Error - Illegal.

19
Copying Arrays

 To copy individual elements of the array, use the index.

 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

for(int j=0; j<10; j++) 57 44 51 64 66 17 34 23 55 33


57 44 51 64 66 17 34 23 55 33

21
Multidimensional arrays

An array may have more than one dimension.


Each dimension is represented as a subscript (index) in the array.
Therefore, a two-dimensional array has two subscripts, a three-dimensional array has three
subscripts, and so on.
Arrays can have any number of dimensions, although most of the arrays that you create will
likely be of one or two dimensions.

22
Declaration of Two Dimensional Array

•Suppose the program contains an array named board.


•The declaration of array named board that represents 4 by 3 array would be:
 Square board[4][3];

•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

for(int j=0; j<3; j++) //this loop is used to display cout<<Ar[i][j];


individual elements of the group cout<<endl; //this is used to separate each groups

}
27
Example
#include <iostream>

using namespace std;


Output of the above program:
int main(){
21 42 32
int Ar[5][3] = { {21, 42, 32}, {14, 25, 61}, {17, 18, 69},
{10, 11, 12}, {13, 14,15} }; 14 25 61

for ( int i=0; i<5; i++) { 17 18 69

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.

•Reading the whole elements of the two-dimensional array


•If you want to read all elements and store it in an array 'Ar', use nested for loops.
•The following code is used to read the whole elements of the 5 by 3 array of name 'Ar':
 for(int i=0; i<5; i++)
 for(int j=0; j<3; j++)
 cin>>Ar[i][j];
29
Reading and Storing Individual elements from or to 2D Array

•Omitting the Array Size


•If a one-dimensional array is initialized, the size can be omitted.
•int x[] = { 1, 2, 3, 4} ;
•This initialization creates an array of four elements.
•Note however:
 int x[][] = { {1,2}, {3,4} } ; is an error and it is not allowed. and must be written as :
 int x[2][2] = { {1,2}, {3,4} } ;
 In short omitting array size is not possible in multidimensional array.
 It is possible only in one dimensional array.
30
Example
//Write a program which initializes a 3 by 2 array and display them.

#include<iostream>

using namespace std;

int main(){

int SomeArray[3][2] = {{0,0},{1,2}, {2,4}};

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

for (int j = 0; j<2; j++)

cout <<SomeArray[i][ j]<<" ";

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)

Hence if a string has n characters, then,

 it requires an n+1 element array (at least) to store it.

 Thus, the character `a' is stored in a single byte as: a

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

•A string variable s1 could be declared as follows: char s1[10];


•The string variable s1 could hold strings of length up to nine characters since space is needed for the
final null character.

Initialization of 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

You can copy strings using strcpy or strncpy function.


We assign strings by using the string copy function strcpy.
The prototype for this function is in string.h. 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).
41
Example
#include<iostream>
#include<string.h>
using namespace std; Output of the above program:
int main(){ David
char me[20] = "David"; YouAreNotMe
cout << me << endl;
strcpy(me, "YouAreNotMe");
cout << me << endl ;
return 0;
} 42
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

You might also like