0% found this document useful (0 votes)
27 views

Arrays

The document discusses arrays and structures in C++. It explains that arrays allow storing multiple variables of the same type under one name and accessing elements using indexes. Structures allow grouping related data as a user-defined type with members. Functions can accept arrays and structures as arguments to operate on the elements or members.

Uploaded by

GAMES TECH
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Arrays

The document discusses arrays and structures in C++. It explains that arrays allow storing multiple variables of the same type under one name and accessing elements using indexes. Structures allow grouping related data as a user-defined type with members. Functions can accept arrays and structures as arguments to operate on the elements or members.

Uploaded by

GAMES TECH
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Arrays

When arrays are used?

• Simulate what happens when many balls are


moving in a box (eg: gas molecules)
• Given the road map of tamil nadu, find the
shortest route from Coimbatore to Erode
How to handle lot of data?
• Fundamental problem: Writing out variable
names to store information would be tiring.
• Double pressure 1, pressure 2, .... Pressure
1000;
• This is the problem solved using arrays.
Arrays
• Double pressure[1000]
• Essentially defines 1000 variables (“array elements”)
• Variables are named pressure[0],
pressure[1],...,pressure[999].
• General form:
data-type array-name[size];
• Size is also called length
• Array name[index] gives index-th variable
• Condition: 0<=index<size
Array element operations
• Double pressure [1000]
Cin>>pressure[0]>>pressure[2];
Pressure[1]=(pressure[0]+pressure[2])/2;
o For(int i=0; i<1000;i++)
o Cin>>pressure[i];
o Cout<<pressure[439]*3.33<<endl;
For(int i=0; i<999;i++)
Pressure[i]=(pressure[i-1]+pressure[i+1])/2;
• Array index can be an expression which will be evaluated during
execution and then the corresponding element will be used.
Index out of range
• Double pressure[1000];
Pressure[1000]=1.2;
Double d= pressure[-5];
• In the assignment above, the array index is
outside the allowed range: 0 through size-1
• If the array index is out of range, it may run,
produce wrong results and halt with some
message.
Initialization while defining
• Int squares[4] = {0, 1, 4, 9};
• Int cubes[]= {0,1,2,3,4};
• //size=5 inferred
• Int x, p[12], y[]={1,2,3,4};
Mark display problem
• Read in marks of 100 students in a class, given in
roll number order, 0 to 99.
• After that:
o Students may arrive in any order and give their
roll number.
o The program must respond by giving their marks.
o If any illegal number is given as roll number, the
program must terminate.
Computer’s view of array definition
• int q[4]={11,12,13,14};
• Assumption: a single int uses one four byte
word
• 4 consecutive words of memory are allocated
to q
• Allocated memory used to store the variables
q[0], q[1], q[2], q[3] in order.
• Initial values stored in the allocated region.
Possible outcome
Address Used for Content
1004 q[0] 11
1008 q[1] 12
1012 q[2] 13
1016 q[3] 14
Computer’s interpretation of array name
• Array name= address of allocated region.
• Here it starts from 1004 to 1019
• Address of 0-th array element
• For our array q=1004
• Type of q:int *
• Array name is a pointer, but it’s value cannot be changed.
• q=1008 is illegal
• q is referring to this array and not telling us how long this
array extends.
• It’s similar is to ‘const’ data type
In general
• elemtype name [length];
• Block of memory of length S*length is allocated.
• S=size in bytes of a single elemtype variable.
• name=starting address of zeroth element=address of
allocated block.
• Value of name cannot be changed
• Type of name: elemtype*
• Value of name= address of the zeroth element of the
array
• Type of name[i]:elemtype
Exercise
• What is printed when the following executes?
int q[4]={11,12,13,14}, r=2;
cout<<q<<r<<&r<<endl;
cout<<q[0]<<&q[0]<<endl;
• Make reasonable assumption and say if some
value cannot be predicted.
• Reasonable assumption: compiler allocated
memory in increasing order of addresses. Starting
address 1004. address of r=1111
How does the computer interpret
name[index]
• [] is a binary operator
• name[index]=name[] index
• Name[index] means
o The variable stored at name + S*index, where S=size
of the single element of the type name points to.
o Array is called random access data structure
because we can get to any element of array in
essentially same amount of time by doing single
addition and multiplication.
Example
Example
• q[3]:
• Variable of the type that q points to
• q has the type int*, so q[3] has type int.
• Stored at address q+S*3 where S is size of a
single variable of the type that q points to.
• Variable of type int, stored at 1004+4*3 =1016
• Same as what we call q[3]
Index out of range
• q[10]=34
Mechanical interpretation as per our rule:
• Variable of the type that q points to, stored at address
q+10*S where S is the size of single variable of the type
tat q points to.
• Variable of type int, stored at 1004+10*4=1044
• 34 will store in address 1044 which is not part of q!
• 34 will be stored in some strange part of memory which
has nothing to do with q.
• x=q[10]; x will get some strange value
Contd...
• If you read or write from an improper address such as 1044:
o You may store data into some wrong place
o You may get data from wrong place
o Occasionally, the addressed may have been deemed
protected – then your program may abort.
o Protected memory- Memory allotted for storing code or
program of a computer.
• Automatic index checking is possible in some programming
language. But in C++ automatic checking is not done and it
is assumed as duty of programmer’s.
Example
Int q[4];
Int *r;
r=q;
r[3]=5;
cout<<q[3]<<endl;
cout<<r[3]<<endl;
Function calls on arrays
We might like functions to:
• Find the largest value in the array
• Find whether the given value is present in the
array
• Find the average of elements in the array
Things to be checked
• Type of the arguments to a call must match
the type of the parameter.
• Example program: function call using arrays
• The expression m[i] can be used in the called
function to access the i-th element
• Array elements are not copied. If the function
modifies the element then the modification
will be seen in the calling program.
Remarks
• When you pass name of an array in a function call, its
value, the starting address of the array, is copied to the
corresponding parameter.
• Because we pass the starting address of the array, we
are effectively enabling the function to pass the array.
• Array name is passed by value- eg: q in this case
• Array element are passed by pointer
• [] operator: given the address of an array and an index,
it can get us to the corresponding element, even if the
address belongs to a different activation frame.
Remarks
• An alternate syntax is allowed
int avg(double m[], int n)
{....}
• In this double m* is synonymous with double*
m, but slightly more indicative that we expect
‘m’ to be an array name and not just any old
pointer.
Unit 2

Structures
A difficulty
• A large program will have lots of variables
• Just managing all the variables is tiring
o Lots of paper strewn over the table
o We can bring some neatness by putting
related papers into the file.
o Can we do something like that with variables?
• The solution: structures
Structures
Most entities we deal with in programming have
lots of attributes.
• If our program is about simulating movement of
stars- Each star has a position, velocity, mass, ...
• If our program is about managing books in a
library – Each book has author, library number,
who has borrowed it,...
• Key idea: Collect together all information about
an entity into a group/supervariable=structure.
Structure - Overview
• Structure=Collection of variables
• Members of a structure : variables in the
collection
• Structure=super variable, denotes the memory
used for all members.
• Each structure has a name, the name refers to
the super variable, i.e., entire collection.
• Each structure has a type: the type defines what
variables will be there in the collection.
Defining a structure type
• General form
struct structure-type
{
Member1-type member1-name;
Member2-type member2-name;
};
• Example
struct book
{
char title[50];
double price;
};
• A structure – type is a user defined data type, just as int, char, double are primitive data types.
• Structure types and member names can be any identifier.
• Struct book is a user defined data type and structure data type as built in type.
Creating structures of type defined earlier
• To create structure of structure type book, just write: book p, q;
//creating variables or instances of an already created structure
type//also called as object declaration.
• This creates two structures: p and q of type book.
• Each created structure has all members defined in structure
type definition
• Member X of structure Y can be accessed by writing Y.X
• p.price=399;
• //stores 399 into p.price
• Cout<<p.tittle;
• //prints the name of the book p.
Initializing structures during creation
• struct book{
char title[100];
double price;
};
book b = {“on education”, 399};
• Stores “on education” in b.title (null terminated as usual) and
399 into b.price
• A value must be given for initializing each member.
• We can make a structure unmodifiable by adding the key word
const:
Const book c={“The 5 AM club”, 300}
One structure can contain another
• struct point
{
double x, y;
};
• struct disk
{
point center;
double radius;
};
• disk.d;
d.radius=10;
d.center.x=15;
//sets the x member of center member of d
Possible Assignment
• One structure can be assigned to another
o All members on right hand side copied into corresponding
members on the left.
o Structure name stands for entire collection unlike array
name which stands for address.
o A structure can be thought of as a (super)variable.
book b={“on education”, 399};
book c;
c=b; // all members are copied
Cout<<c.price<<endl; // will print 399
Structure and functions
• Structures can be passed to function by value
o Members are copied
• Structures can also be passed by reference
o Same structure is used in called function
• Structures can also be returned
o All data members are copied back to a
temporary structure in the calling program.
Program
Structure- passing by value
Passing by reference
• Program-Passing by reference
• Saves the execution time if the structure being
passed are large
• Normally, reference parameters are expected
to be variables.
Array of structures
• Disk d[10];
• Book lib[100];
• Creates arrays with appropriate structures as element.
Cin>>d[0].center.x;
• Reads value into the x co-ordinate of center of 0-th
disk in array d.
Cout<<lib[5].tittle[3]
• Prints 3-rd character of the title of the 5-th book in
array library.
Program
• Structures with functions and arrays to display
disk with overlapping.
Example – Non overlapping disks

You might also like