NCS 301 DATA STRUCTURE USING C - · PDF fileNCS 301 Data Structure Using C 03-08-15 Subject...

13
NCS 301 Data Structure Using C 03-08-15 Subject Notes by Hammad Lari 1 NCS 301 DATA STRUCTURE USING C Hammad Mashkoor Lari Assistant Professor Allenhouse Institute of Technology www.ncs301ds.wordpress.com Unit-1 Part-3 Arrays Introduction Array is a contiguous memory of homogeneous elements. Arrays can store multiple values which can be referenced by a single name Array name is actually a pointer to the first location of memory block allocated to name of array. No bound checking concept for arrays in C. 03-08-2015

Transcript of NCS 301 DATA STRUCTURE USING C - · PDF fileNCS 301 Data Structure Using C 03-08-15 Subject...

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 1

NCS 301

DATA STRUCTURE USING C

Hammad Mashkoor Lari

Assistant Professor

Allenhouse Institute of Technology

www.ncs301ds.wordpress.com

Unit-1 Part-3 Arrays

Introduction

Array is a contiguous memory of homogeneous elements.

Arrays can store multiple values which can be referenced by asingle name

Array name is actually a pointer to the first location of memory

block allocated to name of array.

No bound checking concept for arrays in C.

03-08-2015

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 2

One dimensional ArrayIndex Data

Num[0] 22

Num[1] 30

Num[2] 2

Num[3] 5

Num[4] 76

Num[5] 8

Num[6] 34

03-08-2015

Example:-

Int num[7];

One subscript specification is needed

Syntax:-

Datatype var_name [Expression]; //subscript

should be a integer value

Size = (upper bound – lower bound ) + 1

Size of array num=(6-0)+1=7

Size in bytes=size of array X size of (base type

)

Size in bytes=7 X 2=14

Initialization One Dimensional Array

03-08-2015

ANSI C allows automatic array variables to be initialized in declarations by

constant initializers .

The initializers are specified within braces and separated by commas.

Example:

Int ex[10]={ 12, 23, 9, 17, 16, 49 };

Char word[10]={‘h’, ’e’, ’l’, ’l’, ’o’, ’\0’};

If there are not enough initializers for whole array the remaining elements of

array are initialized to zero.

Note:-initializations are not assignment statements, they are declarations

that allocate and initialize memory.

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 3

Accessing One Dimensional Array

Individual elements of array can be accessed using following syntax:

Array_name[index or subscript];

Example:

Num[1]=90;

Program:

Int a[10],i;

For (i=0;i<=9;i++)

Scanf(“%d”,&a[i]);

For(i=0;i<=9;i++)

Printf(“%d”,a[i]);

03-08-2015

Implementation of One Dimensional

Array in memory

03-08-2015

Address of a particular element in a 1-D array is given by relation:

Address of element a[k]=B+W*k

Example:

B=2000 and each element of array occupies 4 bytes then

5th element of 1D array will be:

Address of element a[5]= 2000+4*5= 2000+20= 2020

Base address Size of each

element of

array

No of required

element in

array(index)

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 4

Passing arrays to function

Arrays like other simple variables can be passed to function.

Arrays are by default passed to function by call by reference method

because array name is itself a pointer to the first memory location of the

array.

But we can also pass individual array elements through call by value method.

Program:

{

For (i=0;i<=9;i++)

Scanf(“%d”,&a[i]);

Sum=funarray(a,9);

Printf(“%d”,sum);

}

03-08-2015

Int funarray(int p[],int n)

{

Int s=0,i=0;

For(i=0;i<=n-1;i++)

{

S=s+p[i];

}

Return s;

}

Insertion in 1D Insertion can be done in two ways

1. Insertion at end of array(easily if space enough to accommodate)

2. Insertion at required position-elements must be moved downwards to new

location.

03-08-2015

i v

a[0] 1

a[1] 5

a[2] 7

a[3] 6

a[4] 22

a[5] 90

a[6] 0

a[7] 0

a[8] 0

a[9] 0

i v

a[0] 1

a[1] 5

a[2] 7

a[3] 6

a[4]

a[5] 22

a[6] 90

a[7] 0

a[8] 0

a[9] 0

i v

a[0] 1

a[1] 5

a[2] 7

a[3] 6

a[4] 20

a[5] 22

a[6] 90

a[7] 0

a[8] 0

a[9] 0

Position for 20

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 5

Algorithm

1. [Initialize the value of i] set i=len

2. Repeat for i=len down to pos

1. [shift elements down by 1 position]

2. Set a[i+1]=a[i]

3. [end of loop]

3. [insert element at required position]

1. Set a[pos]=num

4. [reset len] set len=len +1

5. Display the new list of array

6. End

03-08-2015

a= linear array

num= number

len= total no of elements

pos= position at which num will be inserted

Delete from 1D

Deleting an element at end of array present no difficulty

Deleting element somewhere in middle of array would require to shift all

elements to fill the space emptied.

03-08-2015

i v

a[0] 15

a[1] 7

a[2] 20

a[3] 13

a[4] 66

a[5] 90

a[6] 5

a[7] 10

a[8] 50

a[9] 8

i v

a[0] 15

a[1] 7

a[2] 20

a[3] 13

a[4] 66

a[5] 5

a[6] 10

a[7] 50

a[8] 8

a[9]

i v

a[0] 15

a[1] 7

a[2] 20

a[3] 13

a[4] 66

a[5]

a[6] 5

a[7] 10

a[8] 50

a[9] 8

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 6

Algorithm

1. Set item= a[pos]

2. Repeat for j=pos to n-1

1. [shift elements 1 position upward]

2. Set a[j]=a[j+1]

3. [end of loop]

4. reset n=n-1

3. Display the new list of array

4. End

03-08-2015

Traversing of Array

It means access to all elements of array.

Algorithm

1. Let LB be the lower bound and UB be the upper bound of linear array a.

2. [initialize counter] set i at lower bound LB

3. Repeat for i=LB to UB

1. visit element] display a[i]

2. [End of loop]

4. Exit

03-08-2015

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 7

Merging two Arrays Combining elements of two arrays to form a new array.

First copy all elements of one array into a third empty array and then copy all

elements of other array into third array.

If sorting is needed you can sort resultant array or sort during merging(its more

efficient).

03-08-2015

i v

a[0] 10

a[1] 17

a[2] 20

a[3] 25

a[4] 50

a[5] 100

i v

b[0] 10

b[1] 17

b[2] 20

b[3] 25

Array aArray b

i v

c[0] 10

c[1] 14

c[2] 16

c[3] 17

c[4] 19

c[5] 20

c[6] 25

c[7] 30

c[8] 50

c[9] 100

Array c

Algorithm

1. Create three arrays a1,a2,a3.

2. Enter the element p and q in ascending order in a1,a2.

3. Initialize m and n (lower bounds to 0)

4. Check if (a1[m]-a2[n]

[assign elements of a1 to a3] a3[c]=a1[m++)

Set c=c+1

Else

[assign elements of a2 to a3] a3[c]=a2[n++]

Set c=c+1

[End of If]

5. Assign remaining elements of a1,a2 and a3

6. Display elements of array 3

7. End

03-08-2015

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 8

Multi Dimensional arrays

Int int_array[10];

Int int_array2d[10][10];

Initialization a 2D Array

Int array2d[3][3]={1,2,3,4,5,6,7,8,9};

Initialization a 3D Array

Int array3d[3][3][3]={ 1,2,3

4,5,6

7,8,9

10,11,12

13,14,15

16,17,18

19,20,21

22,23,24

25,26,27 };03-08-2015

[0][0] [0][1] [0][2]

[1][0] [1][1] [1][2]

[2][0] [2][1] [2][2]

Array3d[1][2][0]=16;

Why?

1-second grid(first grid will be 0)

2-third row

0-first element of that row

Implementation of a 2d Array

A 2d array can be implemented in a P.L in 2 ways:-

1. Row major implementation

2. Column major implementation

Row major implementation

Linearization technique(elements of array are reader from keyboard row wise

i.e. The complete first row is stored then the complete second row is stored

and so on).

Example:-

03-08-2015

a00 a01 a02 a10 a11 a12 a20 a21 a22

Row1 Row2 Row3

Actual Physical Storage

Matrix form is logical representation of array

vs

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 9

Address of elements in Row major

Address of element a[i][j]=B +W (n ( i - L1) + ( j - L2))

Example

A 2d array defined as a[4..7,-1…3] requires 2 bytes of storage space.Calculate

address of element at location a[6][2].Given base address is 100.

Solution

Base address B=100 size W=2 bytes L1=4 L2=-1 U1=7 U2=3

i=6,j=2

No of columns n=U2-L2+1= 3-(-1)+1=5

Address of a[6][2] = 100+2(5(6-4)+(2-(-1)))

=100+2(5*2+3)= 100+26= 12603-08-2015

Base

address

Base

addressSize of each

array

element

Size of each

array

element

Number of

columns(U2-L2)

Number of

columns(U2-L2)

L1-lower bound of row

L2-lower bound of column

L1-lower bound of row

L2-lower bound of column

Column major implementation

The complete first column is stored then the complete second column is

stored and so on).

Example:-

Address of element in Column Major implementation

Address of element a[i][j]= B + W (m (j – L2) + ( i – L1))

Where m is number of rows (U1-L1)

Example:-a[-20…20,10…35] requires 1 bytes of storage .B=500.Find a[0][30]

U1-L1+1=20-(-20)+1=41

Address of a[0][30]=500+1(41(30-10)+(0-(-20)))

=500+1(41*20+20)=500+1(840)=134003-08-2015

a00 a01 a02 a10 a11 a12 a20 a21 a22

Column1 Column 2 Column 3

Row major implementation

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 10

Pointers and 1D Arrays

Pointer along with 1D can be used either to access a single element or it can

also be used to access the whole array.

int ar[5], *ip;

ip=6; //wrong in C

int ar[5], *ip;

ip=&ar[3];//&--address of

&-takes address of an object

*-the thing pointed to by the pointer

&1.5-error(constants don’t have addresses)

*p=0;//writes zero into thing pointed to by p

*p+=1;//adds one to where p points03-08-2015

ar[0] ar[1] ar[2] ar[3] ar[4]

Ip

&ar[3]

ar[0] ar[1] ar[2] ar[3] ar[4]

Program to display 1D array elements

Without pointers

Int I;

Int num[]={10,20,30,40,50,60};

i=0;

While(i<=5)

{

Printf(“Address=%u”,&num[i]);

Printf(“element=%d”,num[i]);

i++;

}

03-08-2015

Using pointers

Int *ptr,I;

Int num[]={10,20,30,40,50,60};

i=0;

Ptr=&a[0];

While(i<=5)

{

Printf(“Address=%u”,ptr);

Printf(“element=%d”,*ptr);

i++;

Ptr++;

}

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 11

Program to display 2D array elements

03-08-2015

Using pointers

Int *ptr,i,j;

Int a[3][2]={{100,200},{300,400},{500,600}};

Ptr=&a[0][0];

for(i=0;i<=2;i++)

{

Printf(“\n”);

for(j=0;j<=1;j++)

{

Printf(“%d\t”,*ptr);

Ptr++;

}

}

Array of Pointers

Array of pointers refer to homogeneous collection of pointers .

int *ptr[50];

int a[20],b[30],c[10];

Int *ptr[50];

Ptr[0]=&a[0];

Ptr[20]=&b[0];

Ptr[40]=&c[0];

Program

Char *ptr[3];

Ptr[0]=“hello”;

Ptr[1]=“how”;

Ptr[2]=“home”;

Printf(“%s%s%s”,ptr[0],ptr[1],ptr[2]); 03-08-2015

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 12

Array of Structures

Struct employee

{

Int number;

Char sex;

Int salary;

};

employee data[3]={{146,’m’,1000},{200,’f’,5000},{250,’m’,10000}};

03-08-2015

Memory space for 3

objects

Practice Problems

1. Wap to evaluate average of 5 numbers

2. Wap to find whether given prime number is palindrome or not.

3. Wap for addition of two matrix.

4. Wap for multiplication of two matrix.

5. Wap for transpose of a matrix

6. Wap to find highest and lowest element in an array

7. Wap to determine if matrix is symmetrical(A=A’).

8. Wap to combine two strings

9. Wap to compare two string

10. Wap to count number of vowels and digits in a given string.

11. Wap to check whether a string is palindrome or not.

03-08-2015

NCS 301 Data Structure Using C 03-08-15

Subject Notes by Hammad Lari 13

Class Website

www.ncs301ds.wordpress.com

03-08-2015