What Is An Array?: Introduction To Computing
What Is An Array?: Introduction To Computing
Chapter six
6. What is 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.
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: int num [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.
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: int day[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;
Eg: Arrays example, display the sum of the numbers in the array
#include <iostream.h>
int n, result=0;
void main () {
{ result += day[n]; }
As you can see, the first argument (int arg[] ) admits any array of type int , whatever its
length is, for that reason we have included a second parameter that informs the function
the length of each array that we pass to it as the first parameter so that the for loop that
prints out the array can have the information about the size we are interested about. The
function mult doubles the value of each element and the firstarray is passed to it. After
that the display function is called. The output is modified showing that arrays are passed
by reference.
To pass an array by value, pass each element to the function
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.
This is allowed only during initialization. Therefore, since the lvalue of an assignation
can only be an element of an array and not the entire array, what would be valid is to
assign a string of characters to an array of char using a method like this:
mystring[0] = 'H'; mystring[1] = 'e'; mystring[2] = 'l'; mystring[3] = 'l'; mystring[4]
= 'o'; mystring[5] = '\0';
But as you may think, this does not seem to be a very practical method. Generally for
assigning values to an array, and more specifically to a string of characters, a series of
functions like strcpy are used. strcpy ( str ing c o py ) is defined in the ( string.h ) library
and can be called the following way:
strcpy ( string1 , string2 );
This does copy the content of string2 into string1. string2 can be either an array, a
pointer, or a constant string , so the following line would be a valid way to assign the
constant string "Hello" to mystring :
strcpy (mystring, "Hello");
Look how we have needed to include <string.h> header in order to be able to use
function strcpy.
Although we can always write a simple function like the following setstring with the
same operating than cstring's strcpy :
Another frequently used method to assign values to an array is by using directly the input stream
( cin ). In this case the value of the string is assigned by the user during program execution.
When cin is used with strings of characters it is usually used with its getline method, that
can be called following this prototype:
cin.getline ( char buffer [], int length , char delimiter = ' \n');
where buffer is the address where to store the input (like an array, for example), length is
the maximum length of the buffer (the size of the array) and delimiter is the character
used to determine the end of the user input, which by default - if we do not include that
parameter - will be the newline character ( '\n' ).
The following example repeats whatever you type on your keyboard. It is quite simple
but serves as example on how you can use cin.getline with strings:
Notice how in both calls to cin.getline we used the same string identifier ( mybuffer ).
What the program does in the second call is simply step on the previous content of buffer
by the new one that is introduced.
If you remember the section about communication through console, you will
remember that we used the extraction operator ( >> ) to receive data directly from
the standard input. This method can also be used instead of cin.getline with
strings of characters. For example, in our program, when we requested an input
from the user we could have written: cin >> mybuffer;
This would work, but this method has the following limitations that cin.getline has not:
• It can only receive single words (no complete sentences) since this method uses as
delimiter any occurrence of a blank character, including spaces, tabulators, newlines
and carriage returns.
• It is not allowed to specify a size for the buffer. What makes your program unstable
in case that the user input is longer than the array that will host it.
For these reasons it is recommendable that whenever you require strings of characters
coming from cin you use cin.getline instead of cin >>
may contain "1977" , but this is a sequence of 5 chars not so easily convertible to a
single integer data type. The cstdlib ( stdlib.h ) library provides three useful functions
for this purpose:
•atoi: converts string to int type.
atol: converts string to long type.
atof: converts string to float type.
All of these functions admit one parameter and return a value of the requested type ( int ,
long or float ). These functions combined with getline method of cin are a more reliable
way to get.
The string concatenation can have two forms, where the first one is to append the
whole content of the source to the destination the other will append only part of
the source to the destination.
Appending the whole content of the source
strcat (char* dest , const char* src );
Appending part of the source
strncat (char* dest , const char* src, int size );
Where size is the number characters to be appended
c) String Copy:
Overwrites the content of the dest string by the src string. Returns dest.
The string copy can have two forms, where the first one is to copying the whole
content of the source to the destination and the other will copy only part of the
source to the destination.
Copy the whole content of the source
strcpy (char* dest , const char* src );
Appending part of the source
strncpy (char* dest , const char* src, int size );
Where size is the number characters to be copied
d) String Compare:
Compares the two string string1 and string2.
The string compare can have two forms, where the first one is to compare the
whole content of the two strings and the other will compare only part of the two
strings.
Copy the whole content of the source
strcmp (const char* string1 , const char* string2 );
Appending part of the source
strncmp (const char* string1 , const char* string2, int size );
Where size is the number characters to be compaired
Both string compare functions returns three different values:
Returns 0 is the strings are equal
Returns negative value if the first is less than the second string
Returns positive value if the first is greater than the second string
6.8Multidimensional 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 per 5 values of type int . The way to declare
this array would be:
int matrix[3][5];
For example, the way to reference the second element vertically and fourth horizontally
in an expression would be: matrix[1][3]
With the only difference that the compiler remembers for us the depth of each
imaginary dimension. Serve as example these two pieces of code, with exactly the
same result, one using bi-dimensional arrays and the other using only simple arrays
None of the programs above produce any output on the screen, but both assign values to
the memory block called matrix in the following way:
6. Write a C++ program that accepts 10 integers from the user and finally displays the smallest
value and the largest value.
7. Write a program that accepts ten different integers from the user and display these numbers
after sorting them in increasing order.
Structures
A structure is a collection of one or more variable types grouped together that can be
referred using a single name (group name) and a member name.
You can refer to a structure as a single variable, and you also can initialize, read and change
the parts of a structure (the individual variables that make it up).
Each element (called a member) in a structure can be of different data type.
The General Syntax of structures is:
Struct [structure tag]
{
Member definition;
Member definition;
…
Member definition;
}[one or more structure variables];
Let us see an example
E.g.: Structure tag
struct Inventory
{
char description[15];
char part_no[6];
int quantity; members of the structure
float cost;
}; // all structures end with semicolon
Another example might be:
struct Student
{
char ID[8];
char FName[15];
char LName[15];
char Sex;
int age;
float CGPA;
};
The above “Student” structure is aimed to store student record with all the relevant details.
After the definition of the structure, one can declare a structure variable using the structure
tag. If we need two variables to have the above structure property then the declaration
would be:
struct Inventory inv1,inv2; //or
struct Student Stud1,stud2,Stud3;
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.
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.
.
..
struct cd_collection
{
char title[25];
char artist[20];
int num_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;
ut<<cd1.date_purchased<<endl;
co
.
..
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();
struct cd_collection{
char title[25];
char artist[20];
int num_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
…}
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], int num_items)
{
int ctr;
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;
}
20. Write a program which reads a 3 x 2 matrix and then calculates the sum of each row and store
that in a one dimension array.