Chapter 1 Array and Structure
Chapter 1 Array and Structure
int ar [4];
arr=ar;//not allowed
Accessing and processing array elements
● Any elements of array can be access individually for reading
or modifying (like variable).
● But, to access individual elements, index or subscript must be
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, day[0] is the first element and day[4] is the last
element.
● Following the previous examples where day had 5 elements,
we can use the following to refer to each element:
● Ex. To store the value 75 in the third element of
the array variable day???
day[2] = 75; //as the third element is
found at index 2
● Ex. To pass value of the third element of the
array day to the variable a:
a = day[2]; // is like any variable of
type int
● Thus, an array enables us to create a lot of
variables of the same type with a single
declaration .
● If we write day [5], we would be accecing to the
sixth element of day and therefore exceeding the
size of the array. This might give you either error
or unexpected value.
The uses of square brackets [ ] in 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
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;
int b= day [a+2];
day [day [a] ] = day [2] + 5;
● Eg: Arrays example, display the sum of the numbers in
the array
#include <iostream>
…
int day [ ] = {16, 2, 77, 40, 12071};
int n, result=0;
void main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += day[n];
}
cout << result;
}
Arrays as Parameters
● At some moment we may need to pass an array to a
function as a parameter.
● In order to admit arrays as parameters the only thing
that we must do when declaring the function is to
specify in the argument the base type for the array
that it contains, an identifier and a pair of void brackets
[] . For example, the following function:
void procedure (int arg[ ])
● admits a parameter of type "Array of int " called arg .
In order to pass to this function an array declared as:
int myarray [40];
● it would be enough with a call like this:
procedure (myarray);
Here you have a complete example:
// arrays as parameters
#include <iostream>
using namespace std;
void printarray (int arg[], int length)
{
for (int n=0; n<length; n++) void main ()
cout << arg[n] << " "; {
cout << "\n"; int firstarray[] = {5, 10, 15};
}
int secondarray[] = {2, 4, 6, 8, 10};
void mult(int arg[], int length)
{
printarray (firstarray,3);
for (int n=0; n<length; n++) printarray (secondarray,5);
arg[n]=2*arg[n]; mult(firstarray,3);
} cout<<”first array after being doubled is\
n”;
printarray (firstarray,3);
getch()
}
● 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
String of Characters: What is String?
● What type of variables used so far???… numerical variables??
int, float,… char
● What if you need to represent successive characters, like
words, sentences, names, texts, etc.
● Until now we have only used them as constants, but not
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.
● 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.
char name [20];
● The 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:
H e l l 0 \0
S t u d y i n g C + + \0
#include <iostream>
#include <string>
int main ()
{
char MyName [20];
strcpy (MyName,"Abebe");
cout << MyName;
return 0;
}
// setting value to string
#include <iostream>
#include<conio.h>
void main()
void namecopy(char dest[], char source[]) {
{
clrscr();
int c = 0;
while(source[c] != ‘\0’) char name[10],de
{
dest[c] = source[c];
cout<< “\n enter
c++; name : ”;
} cin>>name;
dest[c] = ‘\0’;
cout<< “\n your name after copying : ”<<dest; namecopy(dest,n
}
getch();
}
● Another frequently used method to assign values to
an array is by using directly the input stream ( cin ).
● When cin is used with strings of characters it is
usually used with its getline method:
cin.getline ( char buffer [], int length , char delimiter =
' \n');
● Where
○ buffer is the address where to store the input (like an
array)
○ 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, (the default newline or '\n' ).
● Example on how to use cin.getline with strings:
type multid_array_name[row_size][col_size];
●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] ;
●Ex. the way to reference the second
element vertically and fourth
horizontally would be:
matrix[1][3];
● Multidimensional arrays are not limited to two indices (two dimen).
● They can contain so many indices as needed, although it is rare to
have to represent more than 3 dimensions.
● How much amount of memory required???
char century [100][365][24][60][60];
● Assigns a char for each second contained in a century, that is
more than 3 billion chars ! What would consume is about 3000
megabytes of RAM memory if we could declare it?
● Multidimensional arrays are nothing else than an abstraction,
since we can simply obtain the same results with a simple array by
putting a factor between its indices:
int matrix [3][5]; is equivalent to
int matrix [15]; (3 * 5 = 15)
//multidimensional array
#include <iostream.h>
#define WIDTH 5
//one dimensional array
#define HEIGHT 3 #include <iostream.h>
int matrix [HEIGHT][WIDTH];
int n,m; int matrix [15];
int main ()
int n;
{
for (n=0;n<HEIGHT;n++) int main ()
for (m=0;m<WIDTH;m++) {
{ for (n=0;n<15;n++)
matrix [n][m]=(n+1)*(m+1);
} matrix [n]=(n+1);
return 0;
}
return 0;
}
• The above program assign values to the
memory block called matrix in the following way:
#define HEIGHT 4
Structures
● A structure is a collection of one or more
variable types grouped together.
● Structure referred using a single name
(group name) and a member name.
● Structure can be refer 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.
struct [structure tag]
{
Member definition;
Member definition;
…
Member definition;
}[one or more structure variables];
//Example 1: //Example 2:
struct student
struct inventory{
{ char ID[8];
char FName[15]; char description[15];
char LName[15]; char part_no[6];
char Sex;
int quantity;
int age;
float cost;
float CGPA;
}; }; // all structures end with
semicolon
● 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:
inventory inv1,inv2; //or
student Stud1,stud2,Stud3;
● Structure tag is not a variable name.
● 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 like programmer defined data type.
Referencing members of a structure
● To refer to the members of a structure use dot operator (.)
● The General syntax::
VarName.Member;
● Where VarName is the varaibale name of the structure variable and
Member is varaibale name of the members of the structure
Eg:- For the above student structure:
●
….
struct cd_collection
{
char title[25];
char artist[20];
int num_songs;
float price;
char date_purchased[9];
} cd1 = {"Red Moon","Sams and 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> //initialize members here
.... strcpy(cd1.title,"Red Moon Men");
strcpy(cd1.artist,"Sams");
void main() cd1.num_songs= 12;
{ cd1.price = 11.95;
strcpy(cd1.date_purchased,"22/12/02");
struct cd_collection{ //print the data
char title[25]; cout<<"\nHere is the info"<<endl;
cout<<"Title : "<<cd1.title<<endl;
char artist[20]; cout<<"Artist : "<<cd1.artist<<endl;
int num_songs; cout<<"Songs :
"<<cd1.num_songs<<endl;
float price; cout<<"Price : "<<cd1.price<<endl;
char date_purchased[9]; cout<<"Date purchased :
"<<cd1.date_purchased;
}cd1;
}
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];
#include<iostream.h>
Referencing the array structure
● The dot operator (.) works the same way for structure
array element as it does for regular array.
● If the number of employees for the fifth store (store[4])
increased by three, you could update the structure
variable like this:
store[4].employees += 3;
● Unlike in the case of arrays, where the whole content of
an array could not be copied to another one using a
simple statement, in structures, you can assign complete
structures to one another by using array notation.
● To assign all the members of the 20th store to the 45th
store, you would do this:
store[44] = store[19];//copies all members from 20th
store to 45th
use of array of structures, and how to
pass and return structures
voidtodisp_menu(void);
struct inventory enter_data();
functions.
void see_data(inventory disk[125],int num_items);
#include<iostream.h>
#include<conio.h> void main()
{ clrscr();
#include<stdio.h> inventory disk[125];
#include<iomanip.h> int ans;
int num_items = 0; //total number of items in the inventory
struct inventory
{ do{
long storage; do{
disp_menu();
int accesstime; cin>>ans;
char vendorcode; }while(ans<1 || ans>3);
float cost;
float price;
};
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()
{ inventory enter_data()
cout<<"\n\n*** Disk Drive {
inventory disk_item;//local variable to fill with
Inventory System ***\n\n"; input
cout<<"Do you want to : \n\n"; cout<<"\n\nWhat is the next drive's storage in
cout<<"\t1. Enter new item in bytes? ";
inventory\n\n"; cin>>disk_item.storage;
cout<<"\nWhat is the drive's access time in
cout<<"\t2. See inventory data\ ms ? ";
n\n"; cin>>disk_item.accesstime;
cout<<"\t3. Exit the program\n\ cout<<"What is the drive's vendor code (A, B,
n"; C, or D)? ";
disk_item.vendorcode = getchar();
cout<<"What is your choice ? ";
cout<<"\nWhat is the drive's cost? ";
return; 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;
}
Chapter End!