Rev B Lecture 8
Arrays
Suppose one had to develop
a program that requested data entry of around 100 items. Just the declaration of the variables would
be a major task. If the variables were
of the same type and could basically be of names differing by a number we can
use something called an array. An array
is a structured data type of a fixed number of elements. All the elements are of the same type.
Declare an array
datatype
variable[expression]; //expression evaluates to a constant positive integer. This is the declaration of a one dimension
array.
e.g. int number[4]; //
defines an array of name number of 4 integer elements
Access an array
e.g. for the array defined
above number[2] is the third element in the array.
Therefore the array
contains number[0], number[1], number[2], number[3]
Assignment to an array
Values have to be assigned
to the components of an array
e.g. number [2]=3; // the
value 3 is assigned to the third element in the array number.
e.g. number [4-3]=7; the
value 7 is assigned to the second element in the array number.
Arrays are stored
consecutively in memory.
e.g. int number[4];
number[0]=3;
number[1]=8;
number[2]=4;
integer values usually take 4 memory locations (4bytes or 32
bits)
therefore
assume the value 3(digitally) is placed starting at memory location 2000 then 8
is placed beginning at location 2004, value 4 at 2008 and so forth.
Array initialization
during declaration
e.g. int
number[5]={3,8,4,7,12};
or int number[]={3,8,4,7,12}; //the index 5 is assumed because 5 elements
are provided
e.g. int
number[7]={3,8,4,7,12}; //in this case since 7 array elements are indicated,
number[5] and number[6] are set to values of 0 and 28 memory locations are set
aside for this array.
e.g. int number[6]={0};
//sets all elements to 0
Array processing
Arrays allow for tasks to
be developed with minimal amount of code.
double dailyGasPrice[30];
int index, highestIndex;
double highestPrice,
total, average;
a. initializing an array
for
(index = 0; index < 30; index++
dailyGasPrice[index] = 0;
b. reading the price into the array
for
(index = 0; index < 30; index++
cin >> dailyGasPrice[index];
c. printout of the prices
for
(index = 0; index < 30; index++
cout << dailyGasPrice[index];
d. finding the total and average of the prices
total
= 0;
for
(index = 0; index < 30; index++
total = total + dailyGasPrice[index];
average
= total/30;
e. finding the highest price
highestIndex
= 0;
for
(index = 0; index < 30; index++
if dailyGasPrice[highestIndex] <
dailyGasPrice{index]
index = highestIndex;
highestPrice
= dailyGasPrice[highestIndex];
Array no no
When declaring an array
you must know size at that point. At
time of compilation index value must be known.
Cannot do
Cout<< “array size =
”;
cin >> index;
cout<< endl;
double number[index]
Cannot copy elements of
one array to another as an aggregate
int firstGroup[8];
int secondGroup[8];
secondGroup = firstGroup;
// not acceptable L
If you did the following
Cout << firstGroup;
// The base(initial)memory address will be outputted
Arrays as parameters to
functions
Arrays are passed as
reference parameters
#include <iostream>
using namespace std;
const int elements;
void fill(int x[], int
size);
int main()
{
int numbers[elements];
fill(numbers,elements);
return 0;
}
void fill(int x[], int
size)
{
int index;
for (index = 0; index <
size; index++)
cin >> x[index];
}
Since arrays are passed as
reference parameters changes to them in the function will affect their value in
the main(). This can be prevented by
the use of the term const in the formal parameter.
e.g. for the above
function we add to the formal parameter
fill(const int x[], int
size]
Exercises
1) Write the declaration of an array called temperatures that is of type double and holds 30 values.
a) How many bytes does this array take up in memory?
b)
How
can we initialize this array so that all the temperatures start off at 32
degrees?
2) What is printed by the following program segment?
int num[10];
int i;
for (i = 0; i < 10; i++)
num[i] = i - 1;
for (i = 0; i < 10; i++)
if
(i % 3)
num[i] = num[i + 1];
for (i = 0; i < 10; i++)
cout<<num[i]<<endl;
3)
#include<iostream>
#include<fstream>
using namespace std;
//************************************
//Programmer:
//Date:
//
//program to demonstrate
arrays
//************************************
void main()
{
int j;
int arr1[10];
int arr2[10];
for (j = 0; j < 10; j++)
{
arr1[j] = j * 5;
arr2[j] = arr1[j] + 3;
}
for (j = 0; j < 10; j++)
{
cout<<arr1[j]<<" "<<arr2[j]<<endl;
}
}
4)
#include<iostream>
#include<fstream>
using namespace std;
/****************************************
//Programmer:
//Date:
//Description:
//***************************************
void findpos(int[],int,
int &);
const int NUMSPOTS=30;
void main()
{
int i,num,spot;
int array[NUMSPOTS];
for (i = 0; i < NUMSPOTS; i++)
array[i] = i*2;
cout<<"Enter the number you wish to find";
cin>>num;
findpos(array,num,spot);
cout<<"The number that you wish to find is in
the";
cout<<spot<<"spot\n";
}
void findpos(int x[], int
num, int & s)
//**************************************
//Programmer:
//Date:
//Finding num in the array
x
//***************************************
{
int i;
for (i = 0; i < NUMSPOTS; i++)
{
if (x[i] == num)
{
s = i;
break;
}
cout<<"in the "<<i<<"th
iteration\n";
}
if (i == 30) s = -1;
}
Two Dimensional Arrays
We previously talked about an array of elements which are arranged in a list form in what we call one dimension. Sometimes we need to place or read components stored in a tabular form and require a two dimension array.
Declare a 2 dimension
array
datatype
variable[rows][columns]; // This is the declaration of a two dimension
array. The rows and columns are
positive integers.
e.g. int number[4][3]; //
defines an array of name number of 4 rows by 3 columns, totaling 12 variables
containing integer values.
Access an array
e.g. for the array defined
above number[2][1] is in row 2 (3rd) and column 1 (2nd)
in the array number.
Assignment to an array
Values have to be assigned
to the components of an array
e.g. number [2][1]=6; //
the value 6 is stored in row 2 (3rd) and column 1 (2) in the array
number.
Array initialization
during declaration
e.g. int
number[4][3]={{3,8,4},
{5,6,2},
{12,4,13}.
{9,2,7}};
e.g. number[2][1]= ?
At least one of the values
in a row must be given for initialization of all the components of the
row. All the omitted remaining elements
in the row are then initialized to 0.
Two-dimensional array
processing
For two dimensions
processing can be done in 3 ways
1. Process the entire array.
2. Process all the columns for a specific row.
3. Process all the rows for a specific column.
initializing
a row[1] in array number
int
number[4][3];
int row=1;
for
(col = 0; col < 3; col++)
number[row][col] = 0;
inputting a value into column[0] in array number
int
number[4][3];
int
col=0;
for
(row = 0; row < 4; row++)
cin >> number[row][[col];
printout
of all the elements of the array nember
for
(row = 0; row < 4; row++)
{
for (col = 0; col < 3; col++)
cout << setw(5) << number[row][col];
cout << endl;
}
List (array) search
Many times a problem requires finding an item in a list. This breaks down to an algorithm for searching within an array.
To solve this problem we need the following:
List (Array name)
Length of the list (size of the array)
Search item to find
e.g.
#include<iostream>
using namespace std;
int main()
{
int list[]={1,2,3,4};
int pos,item;
int length=4;
int found = 0;
cout<<"enter an item number ";
cin>>item;
cout<<endl;
for (pos=0; pos<length; pos++)
{
if (list[pos] == item)
{
found=1;
break;
}
}
if (found)
cout<<"search item is at position "<<pos<<endl;
else
cout<<"search item is not in the list";
return 0;
}
Character arrays or C-Strings
When a 1 dimension array is of the character type it is called c-string and is ended by the null character ‘\0’. Therefore
Strings can be worked with either through a string variable or a character array (c-string).
Thus char name[15] can only contain a null character plus 14 others defined as the string.
Initialization:
char name[15] = “Jack”; // allows up to a string of 14 characters plus 1 null character and uses only index 0 to 3
or char name[15] = {‘J’, ‘a’, ‘c’, ‘k’};.
Thus name[0] = ‘J’
Index can be omitted during declaration
char name[] = “Jack” // is equal to char name[5] = “Jack”
cstrings contain some useful functions. In order to use them we must add the header file cstring(what else would you think)J
thus #include<cstring>
assume char name[15];
cannot now do name = “Jack”; // illegal
strcpy(s1,s2)
can use the cstring function strcpy(s1,s2); // copies the string s2 into the string variable s1
char name[15];
strcpy(name,”Jack”); // result name = “Jack”
strcmp(s1,s2)
used to compare strings s1 and s2
If s1 = s2 returns a 0
If s1>s2 returns a 1
If s1<s2 returns a –1
strcpy(firstStudent,”John”);
strcpy(secondStudent,James”);
strcmp(firstStudent,secondStudent); // returns a value of 1 because the string “John is greater than ”James” that is ‘o’ is greater than ‘a’.
strlen(s)
will provide the length of the string excluding the null character
char name[15] = “Jack”;
int length;
length = strlen(name); // length = 4
I/O
Output
char name[15] = “Jack”;
cout << name; // continues to output name until the null character ‘\0’ is reached. Thus Jack is outputted. If the string didn’t terminate with a null character then all the values in continuous memory would be outputted till a null is reached.
Input
cin>>name; // If the input is 4 characters they will be stored in the character array along with a terminating null. If a white space is encountered the reading in of the string ceases.
cin.get(str, n+1); // stores the next n characters or until a newline character ‘\n’ is encountered to the character array str.