CH 5
CH 5
Chapter outline:
Introducing Arrays
One Dimensional Array
1
PART ONE
ARRAY
2
INTRODUCING ARRAYS
4
ONE DIMENSIONAL ARRAY
Structured collection of components
All of the same type
Structure given a single name
Individual elements accessed by index indicating relative
position in collection
Type of elements stored in an array can be “just about”
anything
Index of an array must be an integer
5
USE OF ARRAY FOR OUR PROBLEM
Store elements in array as read in
Go back and access for deviations
Note
Notedeclaration
declaration
6
EXAMPLE APPLICATIONS
Given a list of test scores, determine the maximum and
minimum scores.
Read in a list of student names and rearrange them in
alphabetical order (sorting).
Given the height measurements of students in a class,
output the names of those students who are taller than
average.
7
DECLARING ARRAYS
To declare an array in C++, the programmer specifies the type of the
elements and the number of elements required by an array as follows
−
type arrayName [ arraySize ];
This is called a single dimension array.
The arraySize must be an integer constant greater than zero and type
can be any valid C++ data type. For example, to declare a 10
element array called balance of type double, use this statement −
double balance[10];
8
ALTERNATIVELY CAN BE DECLARED AS
datatype[] arrayname;
Example:
double[] myList;
datatype arrayname[];
Example:
double myList[];
Declaring multiple arrays of same type
Formatsimilar to regular variables
Example:
int b[ 100 ], x[ 27 ];
9
ARRAY DECLARATION …
E.g:
Data_type Array_name [constant];
Note declaration from our example
Tells
Tellshow
howmany
manyelements
elementsset
setaside
aside
10
INITIALIZING ARRAYS
You can initialize C++ array elements either one by one or using a
single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the
number of elements that we declare for the array between square
brackets [ ]. Following is an example to assign a single element of
the array −
If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write-
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous
example.
balance[4] = 50.0;
11
The above statement assigns element number 5th in the array a
value of 50.0. Array with 4th index will be 5th , i.e, last element
because all arrays have 0 as the index of their first element which
is also called base index.
Following is the pictorial representation of the same array we
discussed above
12
INITIALIZING ARRAYS
Using a loop:
for (int i = 0; i < size; i++)
myList[i] = i;
13
INITIALIZING ARRAYS…
int A[5] = {2, 4, 8, 16, 32};
Static or automatic
int B[20] = {2, 4, 8, 16, 32};
Unspecified elements are guaranteed to be zero
int C[4] = {2, 4, 8, 16, 32};
Error — compiler detects too many initial values
int D[5] = {2*n, 4*n, 8*n, 16*n,
32*n};
Automatically only; array initialized to expressions
int E[n] = {1};
Dynamically allocated array (automatic only). Zeroth element
initialized to 1; all other elements initialized to 0 14
ACCESSING ARRAY ELEMENTS
An element is accessed by indexing the array name. This is done by
placing the index of the element within square brackets after the
name of the array. For example −
double salary = balance[9];
The above statement will take 10th element from the array and
assign the value to salary variable.
15
SUBSCRIPTING (INDEX)
Declare an array of 10 integers:
int Ar[10]; // array of 10 ints
To access an individual element we must apply a subscript to
array named Ar.
A subscript is a bracketed expression.
The expression in the brackets is known as the index.
First element of array has index 0.
Ar[0]
Second element of array has index 1, and so on.
Ar[1], Ar[2], Ar[3],…
Last element has an index one less than the size of the array.
Ar[9]
Incorrect indexing is a common error.
16
SUBSCRIPTING
// array of 10 uninitialized ints
int Ar[10];
--
Ar[3] = 1;
int x = Ar[3]; 1 --
-- -- --
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- 1 -- -- -- -- -- --
Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8] Ar[9]
17
SUBSCRIPTING EXAMPLE
//For loop to fill & print a 10-int array
#include <iostream>
using namespace std;
int main ( ) {
int index, ar[10]; // array for 10 integers
// Read in 10 elements.
cout << "Enter 10 integers: ";
for(index = 0; index < 10; index ++)
cin >> ar[index];
cout << endl;
cout << "The integers are ";
for(index = 0; index < 10; index ++)
cout << ar[index] << " ";
cout << endl;
return 0;
}
18
19
scores
scores: : 85
85 79
79 92
92 57
57 68
68 80
80 . .. .. .
0 1 2 3 4 5 98 99
Index
Indexcan
canbe:
be: max
max == scores[0];
scores[0];
--constant
constant for
for (x
(x == 0;
0; xx << 100;
100; x++)
x++)
--variable
variable if
if (scores[x]
(scores[x] >> max)max)
--expression
expression max
max == scores[x];
scores[x];
MUST
MUSTbe bean
aninteger
integer
EX: 6 MARKS OF A SINGLE STUDENT
20
ARRAY INITIALIZATION EX.1
int Ar[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
Ar[3] = -1;
0 1 2 3 4 5 6 7 8 9
Ar 9 8 7 6 5 4 3 2 1 0
6 -1
0 1 2 3 4 5 6 7 8 9
Ar 9 8 7 -1 5 4 3 2 1 0
21
ARRAY ELEMENT MANIPULATION EX. 2
Consider
int Ar[10], i = 7, j = 2, k = 4;
Ar[0] = 1;
Ar[i] = 5;
Ar[j] = Ar[i] + 3;
Ar[j+1] = Ar[i] + Ar[0];
Ar[Ar[j]] = 12;
cin >> Ar[k]; // where the next input value is 3
0 1 2 3 4 5 6 7 8 9
Ar 1 -- 8 6 3 -- -- 5 12 --
Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8] Ar[9]
22
What will be the out put of the following program.
#include <iostream>
using namespace std;
int main()
{
int odd[10] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
cout << odd[7] << endl;
odd[7]= 67;
cout << odd[7] << endl;
cout << odd[6] << endl;
odd[6] += 5;
cout << odd[6] << endl;
return 0;
}
Output of the above program:
15
67
23
13
18
SORTING WITH ARRAYS: EX. 3
#include <iostream>
using namespace std;
25
EXAMPLE 1: 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;
}
26
EXAMPLE 2: Write a program which accepts 5 integer numbers from user
and display them.
#include <iostream>
using namespace std;
int main()
{
int num[5];
cout << "Enter five integer numbers";
for(int j = 0; j < 5; j++)
cin >> num[j]; //56, 69, 75, 88, 78
for(int i = 0; i < 5; i++)
cout << num[i] << " ";
return 0;
}
Output of the above program:
Enter five integer numbers
56
69
75
88
78
56 69 75 88 78 27
COPYING ARRAYS
Can you copy array using a syntax like this?
list = myList;
28
EXAMPLE
C++ program to store and calculate the sum of 5 numbers entered
by the user using arrays.
29
EXERCISE
1. Write a program that reads 10 integer values and display elements that
are greater than 55.
2. write a program which reads 10 integer values and displays them
using array.
3. write a program which asks the user to type 10 float numbers and
display the smallest one.
4. write a program which accepts 5 integer values and display them in a
reverse order.
5. Write a program which initializes 10 integer numbers and reads one
integer from the keyboard. Your program should search the integer
number accepted from the user and search it in the list initialized.
6. write a program which declares two arrays with size of 10 and reads
the elements to the first array and copy the elements into the second
array.
30
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.
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:
int 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}};
31
CONT…
The array ‘board[4][3]’ has 4 rows and 3 columns.
0 1 2
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
32
INITIALIZING MULTIDIMENSIONAL ARRAYS
int Ar[5][3] ={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 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} };
when we put the array inside the table the table looks like the following:
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
3 10 11 12
4 13 14 15
33
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].
Accessing the whole elements of the two dimensional array
If you want to access all elements of the array, use nested for loops. The
following code is used to display the whole elements of the 5 by 3 array of name
'Ar'.
for(int i=0; i<5; i++) //this loop is used to display the row
for(int j=0; j<3; j++) //this loop is used to display individual elements of the group
cout<<Ar[i][j];
but if you want to display the array 'Ar' as matrix form use the following code:
for(int i=0; i<5; i++) {
for(int j=0; j<3; j++)
cout<<Ar[i][j];
cout<<endl; //this is used to separate each groups
}
34
This is sample program to show you how to Initialize and display:
#include <iostream>
using namespace std;
int main()
{
int Ar[5][3] = { {21, 42, 32}, {14, 25, 61}, {17, 18, 69}, {10, 11, 12}, {13, 14,15} };
for ( int i=0; i<5; i++)
{
for (int j = 0; j<3; j++)
{
cout <<Ar[i][j]<<" ";
}
cout <<endl;
}
return 0;
}
Output of the above program:
21 42 32
14 25 61
17 18 69
10 11 12
13 14 15 35
EXERCISE
1. Write a program which initializes a 3 by 2 array and display
them.
2. Write a program which initializes 2 by 4 array and display in a
reverse order.
3. Write a program which reads a 5 by 3 matrix and display them in
a matrix format.
4. Write a program to sum two 2 by 3 matrixes.
5. Write a program to multiply two 4 by 3 matrixes.
36
C-STRING OR CHARACTER ARRAY
C++ provides following two types of string representations:
1. The C-style character string •
char s1[] = {‘e’, ‘x’, ‘a’, ‘m’, ‘p’, ‘l’, ‘e’, '\0'};
Note that: Accessing each characters of the C-style character string is
similar with one dimensional array as we see before.
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
Look at the following examples.
#include <iostream>
using namespace std;
int main()
{
const int max = 80;
char str[max];
cout <<"\nEnter a string";
cin >> str;
cout << "\n You entered: " << str;
return 0;
}
Output of the above program:
Enter a string
KinduTigabu
You entered: KinduTigabu
Output of the above program when there is a space between words:
Enter a string 40
Kindu Tigabu
You entered: Kindu
To read text containing blanks (spaces) we use another function, cin.get().
Example:
#include <iostream>
using namespace std;
int main()
{
const int max = 80;
char str[max];
cout <<"\nEnter a string";
cin.get(str, max);
cout << "\n You entered: " << str;
return 0;
}
Output of the above program:
Enter a string
Kindu Tigabu
You entered: Kindu Tigabu
41
COPYING STRING THE EASY WAY
Of course you don't need to use a for loop to copy a string. As you
might have guesses, a library function will do it for you.
You can copy strings using strcpy or strncpy function.
The prototype for this function is in string.h. strcpy(destination,
source);
42
Example:
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char me[20] = "David";
cout << me << endl;
strcpy(me, "YouAreNotMe");
cout << me << endl ;
return 0;
}
Output of the above program:
David
YouAreNotMe
43
CONCATENATING STRINGS
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);
44
Example:
#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;
return 0;
}
Output of the above program:
abc
abcdef
abcdefxyz
abcd 45
The function strncat is like strcat except that it copies only a specified number of
characters:
strncat(destination, source, int n);
It may not copy the terminating null character.
Example:
#include<iostream>
#include<string.h>
using namespace std;
int main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strncat(str1, "def", 2);
str1[5] = '\0';
cout << str1 << endl;
char str2[] = "xyz";
strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl;
return 0;
46
}
COMPARING STRINGS
Strings can be compared using strcmp or strncmp functions
The function strcmp compares two strings:
strcmp(str1, str2);
strcmp returns: < 0 if str1 is less than str2 = 0 if str1 is equal to
str2 > 0 if str1 is greater than str2
47
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;
return 0;
}
Output of the above program:
-1
1
0
-1
1 48
The function strncmp is like strcmp except that it compares only a specified
number of characters:
strncmp(str1, str2, int n);
strncmp does not compare characters after a terminating null character has been
found in one of the strings.
Example:
#include<iostream>
#include<string.h>
using namespace std;
int main() {
cout << strncmp("abc", "def", 2) << endl;
cout << strncmp("abc", "abcdef", 3) << endl;
cout << strncmp("abc", "abcdef", 2) << endl;
cout << strncmp("abc", "abcdef", 5) << endl;
cout << strncmp("abc", "abcdef", 20) << endl;
return 0;
}
Output of the above program:
-1
0 49
0
2. THE STRING CLASS
The standard C++ library provides a string class type that supports all the
operations mentioned above, and additionally much more functionality.
Three major features:
Supports operators
E.g.
50
PART TWO
STRUCTURE
51
STRUCTURES
A Structure is a collection of related data items,
possibly of different types.
A structure type in C++ is called struct.
A struct is heterogeneous in that it can be composed
of data of different types.
In contrast, array is homogeneous since it can
contain only data of the same type.
52
CONT…
Structures hold data that belong together.
Examples:
Student record: student id, name, major,
gender, start year, …
Bank account: account number, name,
currency, balance, …
Address book: name, address, telephone
number, …
In database applications, structures are called records.
53
CONT…
Individual components of a struct type are called members
(or fields).
Members can be of different types (simple, array or struct).
A struct is named as a whole while individual members are
named using field identifiers.
Complex data structures can be formed by defining arrays
of structs.
54
DECLARATION OF STRUCTURE
Definition of a structure:
struct <struct-type>{
<type> <identifier_list>; Each identifier
<type> <identifier_list>; defines a member
... of the structure.
} ;
Example:
struct Date {
int day; The “Date” structure
int month; has 3 members,
int year; day, month & year.
} ;
55
STRUCT EXAMPLES
Example:
struct StudentInfo{
int Id; The “StudentInfo”
int age;
char Gender; structure has 4 members
double CGA; of different types.
};
Example:
struct StudentGrade{
char Name[15]; The “StudentGrade”
char Course[9];
int Lab[5]; structure has 5
int Homework[3]; members of
int Exam[2];
different array types.
};
56
EXAMPLE STRUCT DECLARATION
struct Student
{ structure tag
int studentID;
string name; structure members
short year;
double gpa;
};
Notice the
required ;
57
STRUCT DECLARATION NOTES
Multiple fields of same type can be in a comma-separated list
string name,address;
You cannot initialize member variables in a structure definition.
The following is wrong and will not compile:
struct date{ int day = 24, month = 10, year = 2001; };
Now we have two structure variables of the same nameless structure
type. Even more fun we can initialize these structure variables as we
normally would:
struct{
int x, y;
} point1 = { 0, 0}, point2 = {0, 0};
This creates the two structure variables, 'point1'and 'point2', and
initializes both members, 'x'and 'y', on each to zero (0). You don't 58
need to make a name-less definition to do this.
59
CREATING THE OBJECT OF STRUCTURE
Creating object means giving copy of the members created in the
struct body.
Struct StudentRecord {string Name;
Int Id;
Char Gender;};
StudentRecord Student1, Student2;
Name Name
Student1 Id Gender Id Gender Student2
Dept Dept
61
CONT…
struct declaration does not allocate memory or create
variables
To define variables, use structure tag as type name.
Student s1;
s1
studentID
name
year
gpa
62
ACCESSING STRUCTURE MEMBERS
Use the dot (.) operator to refer to members of
struct variables
cin >> s1.studentID;
s1.gpa = 3.75;
Member variables can be used in any manner appropriate
for their data type
63
EX. 1: STRUCT BASICS
The members of a struct type variable are
accessed with the dot (.) operator:
<struct-variable>.<member_name>; Student1
Example:
Name
strcpy(Student1.Name, "Chan Tai
Man"); Id Gender
Student1.Id = 12345;
strcpy(Student1.Dept, "COMP");
Student1.gender = 'M'; Dept
cout << "The student is ";
switch (Student1.gender){ Chan Tai Man
case 'F': cout << "Ms. "; break;
case 'M': cout << "Mr. "; break;12345 M
} COMP
cout << Student1.Name << endl;
64
65
DISPLAYING STRUCT MEMBERS
To display the contents of a struct variable, you must
display each field separately, using the dot operator
Wrong:
cout << s1; // won’t work!
Correct:
cout << s1.studentID << endl;
cout << s1.name << endl;
cout << s1.year << endl;
cout << s1.gpa;
66
INITIALIZING A STRUCTURE
Cannot initialize members in the structure declaration, because no
memory has been allocated yet
struct Student // Illegal
{ // initialization
int studentID = 1145;
string name = "Alex";
short year = 1;
float gpa = 2.95;
};
67
INITIALIZING A STRUCTURE
(CONTINUED)
Structure members are initialized at the time a structure
variable is created
Can initialize a structure variable’s members with either
an initialization list
a constructor
68
USING AN INITIALIZATION LIST
An initialization list is an ordered set of values, separated by
commas and contained in { }, that provides initial values for a
set of data members
{12, 6, 3} // initialization list
// with 3 values
69
MORE ON INITIALIZATION LISTS
Order of list elements matters: First value initializes
first data member, second value initializes second data
member, etc.
Elements of an initialization list can be constants,
variables, or expressions
{12, W, L/W + 1} // initialization list
// with 3 items
70
INITIALIZATION LIST EXAMPLE
Structure Declaration Structure Variable
struct Dimensions
{ int length,
width,
height; box
};
Dimensions box = {12,6,3}; length 12
width 6
height 3
71
PARTIAL INITIALIZATION
Caninitialize just some members, but cannot skip
over members
Dimensions box1 = {12,6}; //OK
Dimensions box2 = {12,,3}; //illegal
72
PROBLEMS WITH INITIALIZATION LIST
Can’t omit a value for a member without omitting values for all
following members
Does not work on most modern compilers if the structure
contains any string objects
Will, however, work with C-string members
73
Example:-a program that creates student struct and uses it to store student information.
#include<iostream>
using namespace std;
struct student {
int id;
char name[15];
};
int main() {
//creating three student variables
student s1,s2, s3;
cout <<"\n Enter Student Id";
cin>>s1.id;
cout <<"\nEnter Name";
cin>>s1.name;
cout <<"\n Enter Student Id";
cin>>s2.id;
cout <<"\nEnter Name";
cin>>s2.name;
cout <<"\nStudents Information";
cout <<"\n Student id\t Student Name";
cout <<endl<<s1.id<<"\t"<<s1.name;
cout <<endl<<s2.id<<"\t"<<s2.name; 74
return 0;
}
Example 2: This program demonstrates using member variables for user input,
output, and mathematical operations.
#include<iostream>
using namespace std;
struct date {
int day, month, year;
};
int main() {
date birth;
cout << "Enter your birth date!" << endl;
cout << "Year: ";
cin >> birth.year;
cout << "Month: ";
cin >> birth.month;
cout << "Day: ";
cin >> birth.day;
cout << "You entered
" << birth.month << "/"<< birth.day << "/" << birth.year << endl;
cout << "You were born in the "<< ((birth.year / 100) + 1) << "th
Century!"<< endl; 75
return 0;}
STRUCTURES AS FUNCTION
ARGUMENTS
May pass members of struct variables to functions
computeGPA(s1.gpa);
May pass entire struct variables to functions
showData(s5);
Can use reference parameter if function needs to modify
contents of structure variable
76
NOTES ON PASSING STRUCTURES
Using a value parameter for structure can slow down a program
and waste space
Using a reference parameter speeds up program, but allows the
function to modify data in the structure
To save space and time, while protecting structure data that
should not be changed, use a const reference parameter
void showData(const Student &s)
// header
77
RETURNING A STRUCTURE FROM A
FUNCTION
Function can return a struct
Student getStuData(); // prototype
s1 = getStuData(); // call
Function must define a local structure
for internal use
to use with return statement
78
MORE EXAMPLES ABOUT STRUCTURE
EX 1:
#include <iostream>
using namespace std;
struct Student{
int roll;
char name[10];
float marks;
}a[10];
int main(){
cout << "Enter all information of students\n";
for(int i=0; i < 2; i++)
{
cout <<"Enter a roll\n";
cin>>a[i].roll;
cout <<"Enter a name\n";
cin>>a[i].name;
cout <<"Enter a marks\n";
cin>>a[i].marks;
}
for(int i = 0; i < 2; i++)
{ 79
cout << a[i].roll << " " << a[i].name << " " << a[i].marks << endl;
}
Output of the above program:
Enter all information of students
Enter a roll
55
Enter a name
Desalegn
Enter a marks
89
Enter a roll
45
Enter a name
Asegahegn
Enter a marks
96
55 Dunga 89
45 Ronaldo 96
80
EX 2:
#include<iostream>
using namespace std;
struct student {
int id;
char name[15];
};
int main() {
83