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

Lecture 1

Uploaded by

khaledhekl2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Lecture 1

Uploaded by

khaledhekl2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Data Structures

Lecture No.01

1
Need for Data Structures

 Data structures organize data  more


efficient programs.
 More powerful computers  more
complex applications.
 More complex applications demand more
calculations.

2
Organizing Data
 Any organization for a collection of records
that can be searched, processed in any
order, or modified.
 The choice of data structure and algorithm
can make the difference between a
program running in a few seconds or many
days.

3
Efficiency
 A solution is said to be efficient if it solves
the problem within its resource constraints.
– Space
– Time

 The cost of a solution is the amount of


resources that the solution consumes.

4
Selecting a Data Structure
Select a data structure as follows:
1. Analyze the problem to determine the
resource constraints a solution must
meet.
2. Determine the basic operations that must
be supported. Quantify the resource
constraints for each operation.
3. Select the data structure that best meets
these requirements.
5
Arrays
• A list of values with the same data type
that are stored in contiguous locations
using a single group name (array
name).

6
One-Dimensional Arrays

• General array declaration statement:


data-type array-name[number-of-items];
• The number-of-items must be specified
before declaring the array.
const int SIZE = 100;
float arr[SIZE];

7
One-Dimensional Arrays (cont.)

• Individual elements of the array can be


accessed by specifying the name of the
array and the element's index:
arr[3]
• Warning: indices assume values from 0 to
number-of-items -1!!

8
One-Dimensional Arrays (cont.)

The array name arr identifies the starting


location of the array

arr[0] arr[1] arr[2] arr[3] arr[4]

element 3

Skip over 3 elements to get


the starting location of
element 3

Start here
9
1D Array Initialization
• Arrays can be initialized during their declaration
int arr[5] = {98, 87, 92, 79, 85};
int arr[5] = {98, 87} - what happens in this case??
• What is the difference between the following two
declarations ?
char codes[] = {'s', 'a', 'm', 'p', 'l', 'e'};
char codes[] = "sample";
codes[0] codes[1] codes[2] codes[3] codes[4] codes[5] codes[6]

s a m p l e \0

10
Two-dimensional Arrays

• A two-dimensional array consists of both rows and


columns of elements.

• General array declaration statement:


data-type array-name[number-of-rows][number-of-columns];

11
Two-dimensional Arrays (cont.)

• The number-of-rows and number-of-columns must


be specified before declaring the array.
const int ROWS = 100;
const int COLS = 50;
float arr2D[ROWS][COLS];
• Individual elements of the array can be accessed
by specifying the name of the array and the
element's row, column indices.
arr2D[3][5]
12
2D Array Initialization

• Arrays can be initialized during their


declaration
int arr2D[3][3] = { {98, 87, 92}, {79, 85, 19},
{32, 18, 2} };
• The compiler fills the array row by row
(elements are stored in the memory in the
same order).

13
1D Arrays as Arguments

• Individual array elements are passed to a


function in the same manner as other
variables.
max = find_max(arr[1], arr[3]);
• To pass the whole array to a function, you
need to specify the name of the array only!!

14
1D Arrays as Arguments (cont.)
#include <iostream>
using namespace std;
float find_average(int[], int);
int main()
{
const int numElems = 5;
int arr[numElems] = {2, 18, 1, 27, 16};
cout << "The average is " << find_average(arr, numElems) << endl;
return 0;
}
float find_average(int vals[], int n)
{
int i;
float avg=0;
for(i=0; i<n; i++)
avg += vals[i];
avg = avg/n;
return avg; 15
}
1D Arrays as Arguments (cont.)

• Important: this is essentially "call by


reference":
a) The name of the array arr stores the address of the
first element of the array arr[0] (i.e., &arr[0]).
b) Every other element of the array can be accessed by
using its index as an offset from the first element.

arr[0] arr[1] arr[2] arr[3] arr[4]

The starting address of arr array is &arr[0].


This is passed to the function find_average()
16
2D Arrays as Arguments

• Individual array elements are passed to a function


in the same manner as other variables.
max = find_max(arr2D[1][1], arr2D[1][2]);
• To pass the whole array to a function, you need to
specify the name of the array only!!
• The number of columns must be specified in the
function prototype and function header.

17
2D Arrays as Arguments (cont.)
#include <iostream>
using namespace std;
float find_average(int vals[][3], int, int);
int main()
{
const int Rows = 2;
const int Cols = 3;
int arr2D[Rows][Cols] = {5, 15, 11, 10,7,3};
float average;
average = find_average(arr2D, Rows, Cols);
cout << "The average is " << average << endl;
return 0;
}

18
2D Arrays as Arguments (cont.)
float find_average(int vals[][3], int n, int m)
{
int i, j;
float avg=0;
for(i=0; i<n; i++)
for(j=0; j<m; j++)
avg += vals[i][j];
avg = avg/(n*m);
return avg;
}

19
2D Arrays as Arguments (cont.)

• Important: this is essentially "call by


reference":
a) The name of the array arr2D stores the address
of arr2D[0] (i.e., &arr2D[0])
b) arr2D[0] stores the address of the first element
of the array arr2D[0][0] (&arr2D[0][0])
c) Every other element of the array can be
accessed by using its indices as an offset from
the first element.

20
Pointers

• Pointers are simply variables that are


used to store the addresses of other
variables.

21
Getting the address of a variable

• You need to use the address operator &


#include <iostream>
using namespace std;
int main()
{
int num;
num = 22;
cout << "num= " << num << endl;
cout << "The address of num = " << &num << endl;
return 0;
}

22
Declaring Pointers

• You need to specify two things:


(a) the data type of the variable pointed to
by the pointer.
(b) the dereferencing operator * followed by
the name of the pointer.
int *num_addr;

23
Dereferencing pointers
• To obtain the contents of the variable pointed to by
a pointer, we need to use the dereferencing
operator *, followed by the name of the pointer.
#include <iostream>
using namespace std;
int main()
{
int *p;
int x, y;
x = 22;
p = &x;
cout << "Address stored in p is " << p << endl;
cout << "Value pointed to by p is " << *p << endl;
y = 158;
p = &y;
cout << "Address stored in p is " << p << endl;
cout << "Value pointed to by p is " << *p << endl;
return 0; 24
}
Passing a pointer variable to a
function (cont.)
#include <iostream>
using namespace std;
void newval(int *, int *); // function prototype
int main()
{
int x, y;
cout << "Enter the value of x: ";
cin >> x;
cout << "Enter the value of y: ";
cin >> y;
newval(&x, &y); // pass the address explicitly !!
cout <<"the value of x is "<< x << endl;
cout<<"the value of y is "<< y << endl;
return 0;
}
void newval(int *xnum, int *ynum)
{
*xnum = *xnum + 5; // dereferencing is required !!
*ynum = *ynum + 5; 25

}
Array names as pointers

• When an array is created, the compiler


automatically creates an internal pointer
constant (i.e., we cannot change its
contents) for it and stores the starting
address of the array in this pointer.
• The name of the array becomes the name of
the pointer constant.

26
Array names as pointers (cont.)

*arr is equivalent to arr[0]


27
Array names as pointers (cont.)

• Referring to the fourth element of the array cause


the compiler, internally, to make the following
address computation:
&arr[3] = &arr[0] + (3 * sizeof(int))
(offset to arr[3] = 3 x 2 = 6 bytes)

• Alternatively, we can refer to arr[3] as follows:


*(arr + 3)

28
Array names as pointers (cont.)
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 5;
int i, arr[SIZE] = {98, 87, 92, 79, 85};
int *p=arr;//&arr[0]
for(i=0; i<SIZE; i++)
cout << arr[i] <<"\t"<< *(arr + i) <<"\t"<< *(p + i) << endl;
cout<<"printing reverse array\n"; //printing reverse array using pointer
p=&arr[4];
while(p>=&arr[0]) {
cout << *p << endl; p--;
}
return 0; 29

}
Static Array Allocation
• Static 2D arrays are stored in the memory as
1D arrays..

30
Dynamic Array Allocation
• To avoid wasting memory, array allocation or
deallocation can take place at run time.
• To allocate memory, we need to use the new
operator
Reserves the number of bytes requested by the
declaration. Returns the address of the first reserved
location or NULL if sufficient memory is not available.
• To deallocate memory (which has previously been
allocated using the new operator) we need to use
the delete operator.
Releases a block of bytes previously reserved. The
address of the first reserved location is passed as an
argument to the function. 31
case of 1D arrays
cout << "Enter array size: ";
cin >> SIZE;

int *arr;
arr = new int[SIZE]; // allocation

delete [] arr; // deallocation

32
case of 2D arrays
cout << "Enter numRows and numCols: ";
cin >> numRows >> numCols;

int **arr2D;
arr2D = new int* [numRows]; // allocation
for(i=0; i<numRows; i++)
arr2D[i] = new int[numCols];

for(i=0; i<numRows; i++) // deallocation


delete [] arr2D[i];
delete [] arr2D;

(individual elements can be accessed using indices!!


(e.g., arr2D[0][2]=10;))

33
case of 2D arrays (cont.)

Very Important diagram;


don’t memorize it,
Understand it !! 34
Passing an array to a function

• When an array is passed to a function, its address is the


only item actually passed to the function.
Passing a 1D array to a function
#include <iostream>
using namespace std;
float find_average(int*, int);
int main()
{
const int numElems = 5;
int *arr;
arr = new int[numElems];
arr[0] = 2; arr[1] = 18; arr[2] = 1;
arr[3] = 27; arr[4]= 16;
cout << "The average is " << find_average(arr, numElems) << endl;
return 0;
} 37
Passing a 1D array to a function (cont.)

float find_average(int *vals, int n)


{
int i;
float avg=0.0;
for(i=0; i<n; i++)
avg += vals[i];
avg = avg/n;
return avg;
}

38
Passing a 2D array to a function

#include <iostream>
#include <stdlib.h>
using namespace std;
float find_average(int**, int, int);
int main()
{
int **arr2D, i, j, numRows=2, numCols=3;
float average;
cout << "Enter numRows and numCols: ";
cin >> numRows >> numCols;
arr2D = new int*[numRows];
for(i=0; i<numRows; i++)
arr2D[i] = new int[numCols];
for(i=0; i<numRows; i++)
{
for(j=0; j<numCols; j++)
{
39
Passing a 2D array to a function (cont.)

arr2D[i][j] = rand()%100;
cout<<arr2D[i][j]<<"\t";
}
cout<<endl;
}
average = find_average(arr2D, numRows, numCols);
cout << "The average is " << average << endl;
return 0;
}
float find_average(int **vals, int n, int m)
{
int i, j;
float avg=0.0;
for(i=0; i<n; i++)
for(j=0; j<m; j++)
avg += vals[i][j];
avg = avg/(n*m);
return avg;
}
40

You might also like