12 Computer Science Notes ch4D Arrays and Structures PDF
12 Computer Science Notes ch4D Arrays and Structures PDF
12 Computer Science Notes ch4D Arrays and Structures PDF
93
4.1 Arrays
An array is a series of elements of the same type placed in contiguous memory locations that can be
individually referenced by adding an index to a unique identifier.
That means that, for example, we can store 5 values of type int in an array without having to declare 5
different variables, each one with a different identifier. Instead of that, using an array we can store 5 different
values of the same type, int for example, with a unique identifier.
For example, an array to contain 5 integer values of type int called myArr could be represented like this:
myArr
|---------------|
int
where each blank panel represents an element of the array, that in this case are integer values of type int.
These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its
length.
Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++
is:
Syntax :
where datatype is a valid type (like int, float...), name is a valid identifier and the elements field (which is
always enclosed in square brackets [ ]), specifies how many of these elements the array has to contain.
Therefore, in order to declare an array called myArr as the one shown in the above diagram it is as simple
as:
int myArr [5];
NOTE: The elements field within brackets [ ] which represents the number of elements the array is going to
hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be
determined before execution. In order to create arrays with a variable length dynamic memory is needed,
which is explained later in these tutorials.
Initializing arrays.
When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise,
its elements will not be initialized to any value by default, so their content will be undetermined until we store
some value in them. The elements of global and static arrays, on the other hand, are automatically initialized
with their default values, which for all fundamental types this means they are filled with zeros.
In both cases, local and global, when we declare an array, we have the possibility to assign initial values to
each one of its elements by enclosing the values in braces { }. For example:
int myArr [5] = { 16, 2, 77, 40, 12071 };
This declaration would have created an array like this:
94
The amount of values between braces { } must not be larger than the number of elements that we declare for
the array between square brackets [ ]. For example, in the example of array myArr we have declared that it
has 5 elements and in the list of initial values within braces { } we have specified 5 values, one for each
element.
When an initialization of values is provided for an array, C++ allows the possibility of leaving the square
brackets empty [ ]. In this case, the compiler will assume a size for the array that matches the number of
values included between braces { }:
int myArr [ ] = { 16, 2, 77, 40, 12071 };
After this declaration, array myArr would be 5 ints long, since we have provided 5 initialization values.
Accessing the values of an array.
In any point of a program in which an array is visible, we can access the value of any of its elements
individually as if it was a normal variable, thus being able to both read and modify its value. The format is as
simple as:
Syntax:
array_name[index]
Following the previous examples in which myArr had 5 elements and each of those elements was of type int,
the name which we can use to refer to each element is the following:
For example, to store the value 75 in the third element of myArr, we could write the following statement:
myArr[2] = 75;
and, for example, to pass the value of the third element of myArr to a variable called a, we could write:
a = myArr[2];
Therefore, the expression myArr[2] is for all purposes like a variable of type int.
Notice that the third element of myArr is specified myArr[2], since the first one is myArr[0], the second one is
myArr[1], and therefore, the third one is myArr[2]. By this same reason, its last element is myArr[4].
Therefore, if we write myArr[5], we would be accessing the sixth element of myArr and therefore exceeding
the size of the array.
In C++ it is syntactically correct to exceed the valid range of indices for an array. This can create problems,
since accessing out-of-range elements do not cause compilation errors but can cause runtime errors. The
reason why this is allowed will be seen further ahead when we begin to use pointers.
At this point it is important to be able to clearly distinguish between the two uses that brackets [ ] have related
to arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and
the second one is to specify indices for concrete array elements. Do not confuse these two possible uses of
brackets [ ] with arrays.
int myArr[5];
myArr[2] = 75;
If you read carefully, you will see that a type specifier always precedes a variable or array declaration, while it
never precedes an access.
95
program 4.1
Output :
12206
Dynamic Initialization:
Arrays can also be initialized during runtime. The following program shows how to input values into arrays
during rum time :
program 4.2
// Inputting value in an array during run-time
#include<iostream.h>
main()
{
int my_arr[5];
// name of array.
cout<<\nEnter values at: ;
for(int i = 0 ; i < 5; i++)
{
cout<<\n<<i+1<< :;
cin>>my_arr[ i ];
}
}
//program 4.3
main()
{
int my_arr[5];
// name of array.
96
#include<iostream.h>
#include<stdio.h>
#include<process.h>
main( )
{
int a[10] , val = 0;
cout<<Input ten integers : ;
// inputting array value
for(int i = 0 ; i<=9 ; i++)
{
cin>> a[i];
}
// searching element
for(int i = 0 ; i<=9 ; i++)
{
if(a[i] == val)
{
cout<<Element found at index location : << i;
getch();
exit(); // if element is found no need to further search, terminate program
}
// if control flow reaches here that means if( ) in the loop was never satisfied
cout<<Element not found;
}
// program 4.5
// program to find the maximum and minimum of an array :
#include<iostream.h>
main( )
{
int arr[ ] = {10, 6 , -9 , 17 , 34 , 20 , 34 ,-2 ,92 ,22 };
int max = min = arr[0];
for(int i = 0 ; i<= 9 ; i++)
{
if(arr[i] < min)
min= arr[i];
if(arr[i] > max)
max = arr[i];
}
97
Write a program to store 10 elements and increase its value by 5 and show the array.
Write the program to divide each of the array element by 3 and show the array.
Write a program to find the average of all elements of an array of size 20.
Write a program to find second minimum value out of an array containing 10 elements.
'H' 'e'
'l'
'l'
'o'
'\0'
19
Therefore, in this array, in theory, we can store sequences of characters up to 20 characters long. But we
can also store shorter sequences. For example, myStr could store at some point in a program either the
sequence "Hello" or the sequence "Merry christmas", since both are shorter than 20 characters.
Therefore, since the array of characters can store shorter sequences than its total length, a special character
is used to signal the end of the valid sequence: the null character, whose literal constant can be written as '\0'
(backslash, zero).
Our array of 20 elements of type char, called myStr, can be represented storing the characters sequence
"Merry Christmas" as:
myStr
'M' 'e'
'r'
'r'
'y'
'C'
'h'
'r'
'i'
's'
't'
'm' 'a'
's'
'\0'
19
Notice how after the valid content a null character ('\0') has been included in order to indicate the end of the
sequence. The panels in gray color represent char elements with undetermined values.
Initialization of null-terminated character sequences
Because arrays of characters are ordinary arrays they follow all their same rules. For example, if we want to
initialize an array of characters with some predetermined sequence of characters we can do it just like any
other array:
char myword[ ] = { 'H', 'e', 'l', 'l', 'o', '\0' };
In this case we would have declared an array of 6 elements of type char initialized with the characters that
form the word "Hello" plus a null character '\0' at the end.
98
But arrays of char elements have an additional method to initialize their values: using string literals.
In the expressions we have used in some examples in previous chapters, constants that represent entire
strings of characters have already showed up several times. These are specified enclosing the text to
become a string literal between double quotes ("). For example:
"the result is: " is a constant string literal that we have probably used already.
Double quoted strings (") are literal constants whose type is in fact a null-terminated array of characters. So
string literals enclosed between double quotes always have a null character ('\0') automatically appended at
the end.
Therefore we can initialize the array of char elements called myword with a null-terminated sequence of
characters by either one of these two methods:
char myword [ ] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char myword [ ] = "Hello";
In both cases the array of characters myword is declared with a size of 6 elements of type char: the 5
characters that compose the word "Hello" plus a final null character ('\0') which specifies the end of the
sequence and that, in the second case, when using double quotes (") it is appended automatically.
Please notice that we are talking about initializing an array of characters in the moment it is being declared,
and not about assigning values to them once they have already been declared. In fact because this type of
null-terminated arrays of characters are regular arrays we have the same restrictions that we have with any
other array, so we are not able to copy blocks of data with an assignment operation.
Assuming mystext is a char[] variable, expressions within a source code like:
mystext = "Hello";
mystext[] = "Hello";
would not be valid, like neither would be:
mystext = { 'H', 'e', 'l', 'l', 'o', '\0' };
The reason for this may become more comprehensible once you know a bit more about pointers, since then
it will be clarified that an array is in fact a constant pointer pointing to a block of memory.
Using null-terminated sequences of characters
Null-terminated sequences of characters are the natural way of treating strings in C++, so they can be used
as such in many procedures. In fact, regular string literals have this type (char[]) and can also be used in
most cases.
For example, cin and cout support null-terminated sequences as valid containers for sequences of
characters, so they can be used directly to extract strings of characters from cin or to insert them into cout.
For example:
//program 4.6
//null-terminated sequences of characters
#include <iostream.h>
int main ()
{
char question[ ] = "Please, enter your first name: ";
char greeting[ ] = "Hello, ";
char yourname [80];
cout << question;
99
100
iv) strcmp(char[ ] , char[ ]) : it accepts two parameters and then compares their content
alphabetically, the one which comes first in the acsii chart has considered to be lower.
This function returns the value as integer. The integer can be :
0
: if the two strings are equal
+val : if the first string is bigger than the second
-ve
: if the second string is bigger than the first.
The above comparison is case sensitive , if we want to perform case insensitive comparison
then we have to take another version of the function called as strcmpi( )
Example :
if( strcmpi(Kamal , kamal) != 0);
cout<<Not equal;
else
cout<<equal;
twoDArr
twoDArr
#define WIDTH 5
#define HEIGHT 3
101
Structures???
To understand the basic need let us proceed with a sample programming scenario.
Problem Definition :
Mr. Chamanlal is Human resource manager in a construction company. He has different responsibilities
related to manpower and its utilities. One of his main duties is to keep the record of data related to the
Workers who are working in the construction company.
102
Data members
Chamanlal wants to write a C++ program which can keep track of the information related to all Workers
working in the construction company.
Solution : The above problem could be solved in C++ using 3 ways. They are :
> Using Simple variables to store all information of each employees
> Using Arrays to store related information of each employees
> Using C++ Structures
Let us explore all these three techniques to store information of each Worker of the company. Assuming that
there are total 20 Workers.
Using Variables :
As we have learned in class XI that any type of data could be stored in a C++ variable having a suitable data
type. For example in the given problem the following data types must be used to store information related to
a Worker :
Data
Data Type
C++ Declaration
Name
char
char name[45] ;
45 x 1 = 45 bytes
Sex
char
char sex = M
1 x 1 = 1 byte
Age
int
int age = 15 ;
1 x 2 = 2 bytes
float
1 x 4 = 4 bytes.
103
Using Arrays
The drawbacks of the previous method of information storage could be managed up to some extent , if
instead of taking separate variables for storing related information of Workers (say Age) , we could have
used an array of Age , which would store the age of all 20 employees.
Though this method does not provides a economic solution in terms of memory , it provides a better
management of Memory locations , where the information about the employees would be stored.
So, four different arrays would be required to keep the related information of Workers i,e :
1. An array to keep the Names of the Workers
2. An array to keep the Gender of the Workers
3. An array to keep the Age of the Workers
4.An array to keep the Rate of the Workers.
1.Array to keep Names :
Ramu
Name[0]
Hari
name[1]
kajri
name[2]
Bajrangi
name[19]
'M'
Gender[0]
'M'
gender[1]
'F'
gender[2]
..
'M'
gender[19]
18
22
age[0]
age[1]
age[2]
24
120
140
rate[0]
rate[1]
Declaration : float rate[20];
rate[2]
19
age[19]
100
100
rate[19]
104
Ramu
Hari
kajri
Bajrangi
'M'
'M'
'F'
'M'
18
22
24
19
100
120
140
100
Structure name
data-member
} W1 , W2 , W3 ;
structure variable representing 3 workers.
Points to remember :
1. A structure can declared locally (inside main( ) ) or globally (Outside main( ) ).
//local declaration
main( )
{
105
struct WORKER
{
char name[45];char gender;
} W1 , W2 , W3;
...
}
In this case we can create structure variable only within main( )
//Global declaration
struct WORKER
{
char name[45];char gender;
};
main( )
{
WORKER W1 , W2 , W3 ;
}
In this case we can create structure variable anywhere in the program
If declared globally , the structure variables could be declared both from inside main( ) and any other
place outside main( ) function including any other user defined functions.
If declared locally , the structure variables could be declared only within the scope in which the
structure has been defined.
2. No data member should be initialized with any value within the structure declaration. i,e the
following type of structure declaration is incorrect and cause error :
struct WORKER
{
char name[45];
gender = M;
age = 16;
rate = 100.00;
};
Static Initialization :
WORKER w1 ; // structure variable declaration
w1.name = Ramu;
w1.gender = M; // static initializations
w1.age = 17;
w1.rate = 100.00;
The ( . ) operator here is known as component operator, used to access the data
composing the structure variable.
106
members
Dynamic Initialization :
main( )
{
WORKER w1 ;
cout<< Input Workers Name;cin.getline(w1.name , 45);
cout<< Input Workers Gender;cin >> w1.gender ;
107
{
char name[45];
char gender;
int age ;
float height;
};
Compared to Worker Structure , we find that , the data types and sequence of all the data members of
structure student is same as that of structure Worker, but still we can never write :
Worker w = {Ramu , M , 20 , 5.5};
So the following assignments are invalid assignments :
Student s = w ;
Student s ;
s = w;
//Invalid
or
Name
Age
Gender
wage
Name
Age
Gender
wage
Name
Age
Gender
wage
Name
Age
Gender
wage
..
Name
Age
Gender
wage
19
Name
Age
Gender
wage
W[0]
W[1]
W[2]
W[2]
W[3]
...
W[19]
Each of the elements of the array is itself a structure hence each of them have all the four components.
W[ ] = {
{ Ramu, 'M' , 17 , 100.00 },
{ Hari , 'M' , 22 , 120.00 },
{ kajri , 'F' , 18 , 100.00 },
109
110
Q3.
Summary :
1. Structured data types are used in special programming situations like arrays are used when there is
bulk of similar type of variables to deal with, whereas structures models a real life entity having
some attribute.
2. Arrays can have both primitive as well user defined data types. There are basically two types of
arrays , one dimensional and multidimensional ( 2 dimensional )
3. Functions can be passed structured datatypes as its parameter as well as they can return them.
4. typedef is a special keyword to define a another name for a variable definition.
111