27
Data Structures Data Structures Lecture 2: Array Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Embed Size (px)

Citation preview

Page 1: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Data StructuresData Structures

Lecture 2: ArrayLecture 2: Array

Azhar MaqsoodNUST Institute of Information Technology (NIIT)

Page 2: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Features of c++ you need to knowFeatures of c++ you need to know

VariablesVariables Parameter PassingParameter Passing PointersPointers Classes and ObjectsClasses and Objects InheritanceInheritance OthersOthers

Page 3: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

VariablesVariables

You must be very comfortable with the notion You must be very comfortable with the notion of a variable as an abstraction for a region of a of a variable as an abstraction for a region of a memory. A variable has attributes such as memory. A variable has attributes such as namename, , typetype, , valuevalue, , addressaddress sizesize, , lifetimelifetime and and scopescope. .

Page 4: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Parameter PassingParameter Passing

There are two parameter passing mechanisms There are two parameter passing mechanisms in C++: in C++: pass-by-valuepass-by-value and and pass-by-referencepass-by-reference. It . It is essential that you understand the behavioral is essential that you understand the behavioral difference between the two methods as well difference between the two methods as well as the performance implications of using each as the performance implications of using each of them. of them.

Page 5: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

PointersPointers

Mastering the use of pointers is essential Mastering the use of pointers is essential when programming in C++. The key to when programming in C++. The key to understanding pointers is to :understanding pointers is to : recognize that a pointer variable has exactly the recognize that a pointer variable has exactly the

same set of attributes as any other C++ variable. same set of attributes as any other C++ variable. It is crucial that you keep straight the distinctions It is crucial that you keep straight the distinctions

between the :between the : valuevalue of a pointer, of a pointer, the the addressaddress of a pointer of a pointer the object to which a pointer points.the object to which a pointer points.

Page 6: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Classes and ObjectsClasses and Objects

A C++ class encapsulates a set of A C++ class encapsulates a set of Values Values

The values are represented by the member variables of The values are represented by the member variables of the classthe class

operations. operations. The operations by the member functions of the class. The operations by the member functions of the class.

In C++ a class definition introduces a new In C++ a class definition introduces a new typetype. . The instances of a class type are called objects. The instances of a class type are called objects. Special role of the constructor and the destructor Special role of the constructor and the destructor

member functions of a class and when the C++ member functions of a class and when the C++ compiler invokes each of them. compiler invokes each of them.

Page 7: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

InheritanceInheritance

In C++ one class may be derived from another. In C++ one class may be derived from another. The derived class The derived class inheritsinherits all the member variables and the member all the member variables and the member

functions of the base class or classes. functions of the base class or classes. In addition, inherited member functions can be In addition, inherited member functions can be

overridden in the derived class and new member overridden in the derived class and new member variables and functions can be defined. variables and functions can be defined.

You should understand how the compiler You should understand how the compiler determines the code to execute when a particular determines the code to execute when a particular member function is called. member function is called.

Page 8: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

InheritanceInheritance

In C++ one class may be derived from another. In C++ one class may be derived from another. The derived class The derived class inheritsinherits all the member variables all the member variables

and the member functions of the base class or and the member functions of the base class or classes. classes.

In addition, inherited member functions can be In addition, inherited member functions can be overridden in the derived class and new member overridden in the derived class and new member variables and functions can be defined. variables and functions can be defined.

You should understand how the compiler You should understand how the compiler determines the code to execute when a particular determines the code to execute when a particular member function is called. member function is called.

Page 9: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Other FeaturesOther Features

features such as features such as templates, templates, exceptions exceptions run-time type informationrun-time type information and more as we learn furtherand more as we learn further

Page 10: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Features of c++ you need to knowFeatures of c++ you need to know

VariablesVariables Parameter PassingParameter Passing PointersPointers Classes and ObjectsClasses and Objects InheritanceInheritance OthersOthers

Page 11: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

In Today’s lectureIn Today’s lecture

How to Input arraysHow to Input arrays How to process arraysHow to process arrays How to insert an item in an arrayHow to insert an item in an array How to pass an arrayHow to pass an array

StructuresStructures Their basic implementationTheir basic implementation

Page 12: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

The first Data StructureThe first Data Structure

An Array! An Array! The simplest form of an Array is a The simplest form of an Array is a one dimensional one dimensional

arrayarray that may be defined as a that may be defined as a finite orderedfinite ordered set set of of homogenoushomogenous elements elements

For ExampleFor Exampleint a[100];int a[100];

Page 13: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Basic OperationsBasic Operations

ExtractionExtraction A function that accepts an A function that accepts an array “a”array “a” and an and an index index

“i“i”, and returns an element of the array.”, and returns an element of the array. ExampleExample

a[i]a[i]

StoringStoring It accepts It accepts array “a”array “a” an an index “iindex “i” and an element ” and an element x.x. ExampleExample a[i]=xa[i]=x

Page 14: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

One Dimensional ArrayOne Dimensional Array

range = range = upper - lower+1upper - lower+1

Neither the Neither the upper boundupper bound nor nor the the lower boundlower bound can be can be changed and as well as the changed and as well as the rangerange can be changed during can be changed during the program execution.the program execution.

LowerBound [0]

UpperBound

Range

Page 15: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Implementation of 1Dimenional ArrayImplementation of 1Dimenional Array

int b[100];int b[100]; Reserves 100 successive locations, each large enough to Reserves 100 successive locations, each large enough to

contain a single integer.contain a single integer. The address of the first of these locations is called the The address of the first of these locations is called the base base

Address: base(b)Address: base(b) Reference to element b[0] is to the element at location Reference to element b[0] is to the element at location

base(b)base(b) Reference to b[1] is to the element at Reference to b[1] is to the element at

base(b) + 1* esizebase(b) + 1* esizeHence Hence bb gives you the starting memory address of the array b gives you the starting memory address of the array b

Page 16: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Memory view of an arrayMemory view of an array

22 33 44 77 88

22

33

44

77

88

a[0]a[0]

a[1]a[1]

a[2]a[2]

a[3]a[3]

a[4]a[4]

int a[5]int a[5]

//Help me give output of this program

void main(void){

int a[5] = { 2,3,4,7,8 };cout << a[3] << endl;cout << a <<endl;cout << *(a+1)

<<endl;cout << *a+1 <<endl;

}

0x40x4

0x80x8

0xC0xC

0x100x10

0x140x14

Page 17: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

*a +1*a +1 without brackets leads to adding 1 to without brackets leads to adding 1 to contents (value) of a[0]contents (value) of a[0]

Page 18: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Array of Variable LengthArray of Variable Length

A[0]A[0]

A[1]A[1]

A[2]A[2]

A[3]A[3]

55 HH EE LL LL OO

66 BB II C C SS EE 44

Page 19: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Array of Variable length cont.Array of Variable length cont.

A[0]A[0]

A[1]A[1]

A[2]A[2]

A[3]A[3]

HH EE LL LL OO \0\0

BB II CC SS EE 22 \0\0

CC OO TT TT OO NN \0\0

pp ee nn \0\0

char *A[4]

Page 20: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Character arrays (Strings)Character arrays (Strings)ReviewReview

AA LL II \0\0

AA

LL

II

\0\0

GarbagGarbagee

A[0]A[0]

A[1]A[1]

A[2]A[2]

A[3]A[3]

A[4]A[4]

Page 21: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

How to determine length of the stringHow to determine length of the string#include <iostream.h>#include <iostream.h>#include <conio.h>#include <conio.h>#include <stdio.h>#include <stdio.h>int len_str(char str[25]);int len_str(char str[25]);int len_str_while(char s[25]);int len_str_while(char s[25]);void main(void)void main(void){{ char l[25];char l[25];

cin >> l;cin >> l;cout << len_str(l) << endl << len_str_while(l);cout << len_str(l) << endl << len_str_while(l);

}}

//function with for loop//function with for loopint len_str(char s[25])int len_str(char s[25]){{

for (int i = 0; s[i] != '\0'; i++);for (int i = 0; s[i] != '\0'; i++);return i;return i;

}}

Page 22: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Cont…Cont…

//another method using while loop//another method using while loopint len_str_while(char s[25])int len_str_while(char s[25]){{

int i=0;int i=0;while (s[i] != '\0')while (s[i] != '\0'){{

i++;i++;}}return i;return i;

}}

Page 23: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Two dimensional ArraysTwo dimensional Arrays

Page 24: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

#include <iostream.h>#include <iostream.h>#include <conio.h>#include <conio.h>void mult_matrices(int a[][2], int b[][2], int result[][2]);void mult_matrices(int a[][2], int b[][2], int result[][2]);void print_matrix(int a[][2]);void print_matrix(int a[][2]);void main(void)void main(void){{ int p[2][2] = { {10, 20}, {30,40 } };int p[2][2] = { {10, 20}, {30,40 } }; int q[2][2] = { {50, 60}, {70, 80} };int q[2][2] = { {50, 60}, {70, 80} }; int r[2][2];int r[2][2]; print_matrix(p);print_matrix(p); print_matrix(q);print_matrix(q); mult_matrices(p, q, r);mult_matrices(p, q, r); print_matrix(r);print_matrix(r);}}

Main ProgramMain Program

Why New Array?

Page 25: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Print a MatrixPrint a Matrixvoid print_matrix(int a[][2])void print_matrix(int a[][2]){{ int i, j;int i, j; for (i=0; i<2; i++)for (i=0; i<2; i++) {{

for (j=0; j<2; j++)for (j=0; j<2; j++) {{ cout << "\t" << a[i][j];cout << "\t" << a[i][j]; }} cout << endl; cout << endl;

}} cout << endl;cout << endl;}}

Why mention 2?

Page 26: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Multiply a MatrixMultiply a Matrixvoid mult_matrices(int a[][2], int b[][2], int result[][2])void mult_matrices(int a[][2], int b[][2], int result[][2]){{ int i, j, k;int i, j, k; for(i=0; i<2; i++)for(i=0; i<2; i++) {{

for(j=0; j<2; j++)for(j=0; j<2; j++) {{ result[i][j] = 0;result[i][j] = 0;

for(k=0; k<2; k++)for(k=0; k<2; k++) {{

result[i][j] = result[i][j] + (a[i][k] * b[k][j]);result[i][j] = result[i][j] + (a[i][k] * b[k][j]); }} }}

}}}}

Why passed so many

variables?

Are theseVariablesCalled by

reference orBy value?

Page 27: Data Structures Lecture 2: Array Azhar Maqsood NUST Institute of Information Technology (NIIT)

Submission DateSubmission Date

13th13th March, 2008 March, 2008 Before 1500 Hrs Before 1500 Hrs Late submission rules applyLate submission rules apply