Chapter - 2 (Arrays and Structures)
Chapter - 2 (Arrays and Structures)
An Array
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.
Array elements are also variables.
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
A block of memory representing a collection of many simple data variables stored in a
separate array element, and the computer stores all the elements of an array consecutively in
memory.
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 (homogenous data type)
Array declaration
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:
The type of the array (i.e. integer, floating point, char etc.)
Name of the array,
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.
the general syntax for the declaration is: DataTypenamearrayname [array size];
Note: array size cannot be a variable whose value is set while the program is running.
Thus to declare an integer with size of 10 having a name of num is: intnum [10];
This means: Ten consecutive two byte memory locations will be reserved with the name
num.
That means, we can store 10 values of type int without having to declare 10 different
variables each one with a different identifier. Instead of that, using an array we can store 10
different values of the same type, int for example, with a unique identifier.
Initializing Arrays
When declaring an array of local scope (within a function), if we do not specify the array
variable will not be initialized, so its content is undetermined until we store some values in it.
If we declare a global array (outside any function) its content will be initialized with all its
elements filled with zeros. Thus, if in the global scope we declare:
But additionally, when we declare an Array, we have the possibility to assign initial values
to each one of its elements using curly brackets { } . For example: int day [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.
For example, in the example of the day 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.
Because this can be considered as useless repetition, 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 day [] = { 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.: day[6])
You can use the initialization form only when defining the array. You cannot use it later, and
cannot assign one array to another once. I.e.
intarr [] = {16, 2, 77, 40, 12071};
intar [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.
Accessing and processing array elements
In any point of the program in which the array is visible we can access individually anyone
of its elements for reading or modifying it as if it was a normal variable. To access individual
elements, index or subscript is used. The format is the following:
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). Thus, from the above declaration, day[0] is the first
element and day[4] is the last element.
Following the previous examples where day 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 day a suitable
sentence would be: day[2] = 75; //as the third element is found at index 2
And, for example, to pass the value of the third element of the array variable day to the
variable a , we could write:
a = day[2];
Therefore, for all the effects, the expression day[2] is like any variable of type int with the
same properties. Thus an array declaration enables us to create a lot of variables of the same
type with a single declaration and we can use an index to identify individual elements.
Notice that the third element of day is specified day[2] , since first is day[0] , second day[1]
, and therefore, third is day[2] . By this same reason, its last element is day [4]. Since if we
wrote day [5], we would be acceding to the sixth element of day and therefore exceeding the
size of the array. This might give you either error or unexpected value depending on the
compiler.
In C++ it is perfectly valid to exceed the valid range of indices for an Array, which can cause
certain detectable problems, since they do not cause compilation errors but they can cause
unexpected results or serious errors during execution. The reason why this is allowed will be
seen ahead when we begin to use pointers.
At this point 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:
Eg: intday[5]; // declaration of a new Array (begins with a type name) day[2] = 75; // access to
an element of the Array.
Other valid operations with arrays in accessing and assigning:
int a=1;
day [0] = a; day[a] = 5; b = day [a+2]; day [day[a]] = day [2] + 5;
day [day[a]] = day[2] + 5;
Multidimensional Arrays
Multidimensional arrays can be described as arrays of arrays. For example, a bi-dimensional
array can be imagined as a bi-dimensional table of a uniform concrete data type.
Matrix represents a bi-dimensional array of 3 by 5 values of type int. The way to declare this
array would be:
intmatrix[3][5];
For example, the way to reference the second element vertically and fourth element
horizontally in an expression would be:
Strings of Characters:
Strings
In all programs and concepts we have seen so far, we have used only numerical variables,
used to express numbers exclusively. But in addition to numerical variables there also exist
strings of characters that allow us to represent successive characters, like words, sentences,
names, texts, etc. Until now we have only used them as constants, but we have never
considered variables able to contain them.
In C++ there is no specific elementary variable type to store string of characters. In order to
fulfill this feature we can use arrays of type char, which are successions of char elements.
Remember that this data type (char) is the one used to store a single character, for that reason
arrays of them are generally used to make strings of single characters.
For example, the following array (or string of characters) can store a string up to 20
characters long. You may imagine it thus:
char name [20];
This maximum size of 20 characters is not required to be always fully used. For example,
name could store at some moment in a program either the string of characters "Hello" or the
string "studying C++”. Therefore, since the array of characters can store shorter strings than
its total length, there has been reached a convention to end the valid content of a string with a
null character, whose constant can be written as '\0’.
We could represent name (an array of 20 elements of type char) storing the strings of
characters "Hello" and "Studying C++" in the following way:
Notice how after the valid content it is included a null character ('\0') in order to indicate the
end of string. The empty cells (elements) represent indeterminate values.
Initialization of Strings
Because strings of characters are ordinary arrays they fulfill same rules as any array.
For example, if we want to initialize a string of characters with predetermined values
we can do it in a similar way to any other array: char mystring[] = { 'H', 'e', 'l', 'l', 'o',
'\0' };
In this case we would have declared a string of characters (array) of 6 elements of
type char initialized with the characters that compose Hello plus a null character '\0' .
Nevertheless, string of characters have an additional way to initialize its values: using
constant strings.
In the expressions we have used in examples of previous chapters there have already
appeared several times constants that represented entire strings of characters. These
are specified enclosed between double quotes ( “ “ ), for example:
Eg: "the result is: "
is a constant string that we have probably used in some occasion.
Unlike single quotes ( ' ) which allow to specify single character constants, double
quotes ( " ) are constants that specify a succession of characters. These strings
enclosed between double quotes have always a null character ( '\0' ) automatically
appended at the end.
Therefore we could initialize the string mystringwith 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 mystringis declared with a size of 6
characters (elements of type char ): the 5 characters that compose Hello plus a final
null character ( '\0' ) which specifies the end of the string and that, in the second case,
when using double quotes ( " ) it is automatically appended.
Before going further, you should 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.
Structure tag is not a variable name. Unlike array names, which reference the array as
variables, a structure tag is simply a label for the structure’s format.
The structure tag Inventory informs C++ that the tag called Inventory looks like two
character arrays followed by one integer and one float variables.
A structure tag is actually a newly defined data type that you, the programmer, defined.
Referencing members of a structure
To refer to the members of a structure we need to use the dot operator (.)
The General syntax to access members of a structure variable would be:
VarName.Member
Where VarNameis the varaibale name of the structure variable AndMember is varaibale
name of the members of the structure
Eg:
For the above student structure:
struct Student Stud; //declaring Stud to have the property of the Student structure
strcpy(Stud.FName,”Abebe”); //assigned Abebe as First Name
Stud.CGPA=3.21; //assignes 3.21 as CGPA value of Abebe
sout<<Stud.FName; //display the name
sout<<Stud.CGPA; // display the CGPA of Abebe
Initializing Structure Data
You can initialize members when you declare a structure, or you can initialize a structure in
the body of the program. Here is a complete program.
.
.
structcd_collection
{
char title[25];
char artist[20];
intnum_songs;
float price;
char date_purchased[9];
} cd1 = {"Red Moon Men","Sams and the Sneeds", 12, 11.95,"08/13/93"};
cout<<"\nhere is the info about cd1"<<endl;
cout<<cd1.title<<endl;
cout<<cd1.artist<<endl;
cout<<cd1.num_songs<<endl;
cout<<cd1.price<<endl;
cout<<cd1.date_purchased<<endl;
.
.
A better approach to initialize structures is to use the dot operator(.). the dot operator is one
way to initialize individual members of a structure variable in the body of your program. The
syntax of the dot operator is :structureVariableName.memberName
here is an example:
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
structcd_collection{
char title[25];
char artist[20];
intnum_songs;
float price;
char date_purchased[9];
}cd1;
//initialize members here
strcpy(cd1.title,"Red Moon Men");
strcpy(cd1.artist,"Sams");
cd1.num_songs= 12;
cd1.price = 11.95f;
strcpy(cd1.date_purchased,"22/12/02");
//print the data
cout<<"\nHere is the info"<<endl;
cout<<"Title : "<<cd1.title<<endl;
cout<<"Artist : "<<cd1.artist<<endl;
cout<<"Songs : "<<cd1.num_songs<<endl;
cout<<"Price : "<<cd1.price<<endl;
cout<<"Date purchased : "<<cd1.date_purchased;
getch();
}
Arrays of Structures
Arrays of structures are good for storing a complete employee file, inventory file, or any
other set of data that fits in the structure format.
Consider the following structure declaration:
struct Company
{
int employees;
int registers;
double sales;
}store[1000];
In one quick declaration, this code creates 1,000 store structures with the definition of the
Company structure, each one containing three members.
NB. Be sure that your computer does not run out of memory when you create a large number
of structures. Arrays of structures quickly consume valuable information.
You can also define the array of structures after the declaration of the structure. struct
Company
{
int employees;
int registers;
double sales;
}; // no structure variables defined yet
#include<iostream.h>
…
void main()
{
struct Company store[1000]; //the variable store is array of the structure Company
…}
Here is a complete C++ code that shows you how to use array of structures, and how to pass
and return structures to functions. #include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<iomanip.h>
struct inventory
{
long storage;
intaccesstime;
char vendorcode;
float cost;
float price;
};
void disp_menu(void);
struct inventory enter_data();
void see_data(inventory disk[125],intnum_items);
void main()
{
clrscr();
inventory disk[125];
intans;
intnum_items = 0; //total number of items in the inventory
do{
do{
disp_menu();
cin>>ans;
}while(ans<1 || ans>3);
switch(ans)
{ case 1:
disk[num_items] = enter_data();
num_items++;
break;
case 2:
see_data(disk,num_items);
break;
default :
break;
}
}while(ans != 3);
return;
}//end main
void disp_menu()
{
cout<<"\n\n*** Disk Drive Inventory System ***\n\n";
cout<<"Do you want to : \n\n";
cout<<"\t1. Enter new item in inventory\n\n";
cout<<"\t2. See inventory data\n\n";
cout<<"\t3. Exit the program\n\n";
cout<<"What is your choice ? ";
return;
}
inventory enter_data()
{
inventory disk_item;//local variable to fill with input
cout<<"\n\nWhat is the next drive's storage in bytes? ";
cin>>disk_item.storage;
cout<<"\nWhat is the drive's access time in ms ? ";
cin>>disk_item.accesstime;
cout<<"What is the drive's vendor code (A, B, C, or D)? ";
disk_item.vendorcode = getchar();
cout<<"\nWhat is the drive's cost? ";
cin>>disk_item.cost;
cout<<"\nWhat is the drive's price? ";
cin>>disk_item.price;
return (disk_item);
}
void see_data(inventory disk[125], intnum_items)
{
intctr;
cout<<"\n\nHere is the inventory listing:\n\n";
for(ctr=0;ctr<num_items;ctr++)
{
cout<<"Storage: "<<disk[ctr].storage<<"\n";
cout<<"Access time: "<<disk[ctr].accesstime<<endl;
cout<<"Vendor code: "<<disk[ctr].vendorcode<<"\n";
cout<<"Cost : $ "<<disk[ctr].cost<<"\n";
cout<<"Price: $ "<<disk[ctr].price<<endl;
}
return;
}
Array within Structure
As we know, structure is collection of different data type. Like normal data type, it can also store
an array as well. For example, it as define a structure contain student id, name and, mark of two
assignment and three exam result.
struct studentmark
{
char id [20];
char name [30];
char coursename[40]
int assignment [2];
int exam [3];
}
It is also possible to declare a variable so as to refer only one student full information or arrays of
structure to refer more than one student recorded as follows:
{
cout<<"enter assignment mark: ";
Nested structure
When a structure contains another structure, it is called nested structure. Nested structure is a structure
being a member of another structure. For example, we have two structures named Address and Employee.
To make Address nested to Employee, we have to define Address structure before and outside Employee
structure and create an object of Address structure inside Employee structure.
Syntax for structure within structure or nested structure
struct structure1
{
----------
----------
};
struct structure2
{
----------
----------
structure1 obj;
};
Note: - the obj can be a variable or an array.
18
Example2 for structure within structure or nested structure full program
#include<iostream.h>
struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};
struct Employee
{
int Id;
char Name[25];
float Salary;
struct Address Add;
};
void main()
{
int i;
Employee E;
19
Output :
Details of Employees
Employee Id : 101
Employee Name : Suresh
Employee Salary : 45000
Employee House No : 4598/D
Employee City : Delhi
Employee Pin Code : 110056
Exercise 1
Write a C++ program to accept and display records of 5 students. The information of each student
contains ID, Name, and Sex, age and information about three course(course title, credit, code)
Solution:
#include <iostream.h>
#include <iomanip.h>
struct course
{
char code[20];
char title[100];
int credit;
};
struct student
{
int stnumber;
char stname[20];
char sex;
int age;
course course[3];
};
void main()
{
student stud[5];
//input
for(int i=0;i<5;i++)
{
cout<<"enter "<<(i+1)<<"th student information\n";
20
cout<<"enter student number: ";
cin>>stud[i].stnumber;
cout<<"enter student name: ";
cin>>stud[i].stname;
cout<<"enter student sex: ";
cin>>stud[i].sex;
cout<<"enter student age: ";
cin>>stud[i].age;
for(int j=0;j<3;j++)
{
cout<<"enter course code: ";
cin>>stud[i].couse[j].code;
cout<<"enter course title: ";
cin>>stud[i].couse[j].title;
cout<<"enter course credit: ";
cin>>stud[i].couse[j].credit;
}
//display
cout<<setw(10)<<"id"<<setw(20)<<"name"<<setw(10)<<"sex\n";
for( i=0;i<5;i++)
{
cout<<setw(10)<<stud[i].stnumber<<setw(20)
<<stud[i].stname<<setw(10)<<stud[i].sex<<endl;
cout<<setw(10)<<“course code"<<setw(20)
<<“course title"<<setw(10)<<“credit";
for(int j=0;j<3;j++)
{
cout <<setw(10)<<" stud[i].couse[j].code <<setw(20)
<<" stud[i].couse[j].title<<setw(10)<<" stud[i].couse[j].credit<<endl;
}
}
}//main method
Exercise 2
Write a C++ program to accept records of 5 students. The information of each student contains ID, Name,
GPA and information about three courses that each student is registered for. Information of each course
contains course title, credit, mid-term score, final score, and total score, and letter Grade. Your program
should convert total score of each course to letter grade based on given grade scale and compute semester
GPA of each student.(Assume the curriculum is conventional)
21