Data Structure with C

163
1

description

third semester CSE/ISE Engineering

Transcript of Data Structure with C

Page 1: Data Structure with C

1

Page 2: Data Structure with C

2

Page 3: Data Structure with C

Syllabus

Prof. A. Syed Mustafa (Ph.D)3

Page 4: Data Structure with C

Syllabus

Prof. A. Syed Mustafa (Ph.D)4

Page 5: Data Structure with C

Syllabus

Prof. A. Syed Mustafa (Ph.D)5

Page 6: Data Structure with C

Syllabus

Prof. A. Syed Mustafa (Ph.D)6

Page 7: Data Structure with C

7

Evaluation

• Grade Percentage

– FCD : 70% and above

– FC : 60% - 69%

– SC : 35% - 59%

– FL : less than 35%

• Syllabus Coverage Schedule

– 1st IA Test : 30% [ Portion- first 2.5 Units ]

– 2nd IA Test : 30% [ Portion- next 2.5 Units ]

– 3rd IA Test : 40% [ Portion- Last 3 Units ]

Page 8: Data Structure with C

8

Evaluation• Assignments

– Total : 3

– Each Assignment to be submitted before the IA test

begins

• Attendance

– Class Participation: 85%

• You may get detained if you miss (more than) ¼ of the whole classes

• Academic dishonesty (e.g. cheating, copying, late coming and etc.) will be taken seriously

Page 9: Data Structure with C

9

Announcement• Class Website

• The link for the CMS portal is:

– Intranet link: http:\\172.17.0.2\moodle

– Internet link: http:\\61.8.153.222\moodle

– http://gg.gg/hkbkis

• Class information such as lecture notes can be accessible through this website

• We will also use Moodle for online test

Page 10: Data Structure with C

10

Announcement

• Programming Assignments

– We encourage to study and discuss together for doing programming assignments.

– However, you must do programming YOURSELF.

– You must not share any of source code with other students.

– Any kind of academic dishonesty will be viewed very seriously.

Page 11: Data Structure with C

Unit -1

Prof. A. Syed Mustafa (Ph.D)11

Basic concepts

Page 12: Data Structure with C

Prof. A. Syed Mustafa (Ph.D)12

Basic Concepts

Topics :

Pointers and Dynamic Memory Allocation

Algorithm Specification

Data Abstraction

Performance Analysis

Performance Measurement

Page 13: Data Structure with C

Prof. A. Syed Mustafa (Ph.D)13

Basic Concepts

Objectives

Understanding core concepts of memory management, performance analysis.

Applying the pointer concepts to actual programming

managing memory efficiently

Improve the performance.

Page 14: Data Structure with C

Prof. A. Syed Mustafa (Ph.D)14

Basic Concepts

Course Outcome:

Able to apply the pointer concepts to actual programming

Able to use memory efficiently

Able to increase the performance of the program.

Page 15: Data Structure with C

Prof. A. Syed Mustafa (Ph.D)15

Basic Concepts

System Life Cycle

• Large-Scale program contains many complex interacting

parts.

• Programs undergo a development process called the system

life cycle.

• Solid foundation in

1. data abstraction

2. algorithm specification

3. performance analysis and measurement

provides necessary methodology.

Page 16: Data Structure with C

Prof. A. Syed Mustafa (Ph.D)16

Basic Concepts

System Life Cycle

5 phases of system life cycle:

1. Requirements: Begins with defining purpose of the project.What inputs (needs), outputs (results)

2. Analysis: Break the problem down into manageable pieces.bottom-up vs. top-down, divide and conquer

3. Design: data objects and operations creation of abstractdata types, the specification of algorithms and algorithmdesign strategies, ignore coding details.

4. Refinement & coding: choose representations for our dataobjects and write algorithms for each operation on them.

we should write those algorithms that are independent ofthe data objects first.

Page 17: Data Structure with C

Prof. A. Syed Mustafa (Ph.D)17

Basic Concepts

System Life Cycle

5. Verification: consists of developing correctness proofs for theprogram, testing the program with a variety of input data andremoving errors.

Correctness proofs: proofs are very time-consuming anddifficult to develop for large projects. Scheduling constraintsprevent the development of a complete set of proofs for alarge system.

Testing: before and during the coding phase. testing is usedat key checkpoints in the overall process to determinewhether objectives are being met.

Error Removal: system tests will indicate erroneous code.Errors can be removed depending on the design & codingdecisions made earlier.

Page 18: Data Structure with C

18

• For any type T in C there is a corresponding type pointer-to-T.

• The actual value of a pointer type is an address of memory.

– & the address operator.

– * the dereferencing ( or indirection ) operator.

– Declaration

• int i , *ip; // i is an integer variable and ip is a pointer to an integer.

• ip = &i;

then &i returns the address of i and assigns it as the value of pi.

Basic Concepts

Pointers

Prof. A. Syed Mustafa (Ph.D)

Page 19: Data Structure with C

19

Basic Concepts

Pointers

• i = 10 or *ip = 10;

In both cases the integer 10 is stored as the

value of i.

In second case, the * in front of the pointer ip

causes it to be dereferenced,

by which we mean that instead of storing 10 into

the pointer, 10 is stored into the location

pointed at by the pointer ip.

Prof. A. Syed Mustafa (Ph.D)

Page 20: Data Structure with C

20

Basic Concepts

Pointers

The size of a pointer can be different on

different computers.

The size of a pointer to a char can be longer

than a pointer to a float.

Test for the null pointer in C

if (ip == NULL) or if (ip==0) or if (!ip)

Page 21: Data Structure with C

21

Basic Concepts

Pointers

The null pointer points to no object or

function.

The null pointer is represented by the integer

as 0 an in character as ‘\0’. The ASCII value for

NULL is 0.

The null pointer is interpreted as false in

relational expressions.

Prof. A. Syed Mustafa (Ph.D)

Page 22: Data Structure with C

22

Basic Concepts

Dynamic Memory Allocation

• When we write program, we may not know how

much space we may need, to store data.

• C provides a mechanism called a heap, for

allocating storage at run-time.

• The function malloc() is used to allocate a new

area of memory.

Prof. A. Syed Mustafa (Ph.D)

Page 23: Data Structure with C

23

Basic Concepts

Dynamic Memory Allocation

malloc()Syntax

void *malloc(size_t size)

Parameters

• size -- This is the size of the memory block, in bytes.

Return Value

• This function returns a pointer to the allocated memory,

or NULL if the request failsProf. A. Syed Mustafa (Ph.D)

Page 24: Data Structure with C

24

Basic Concepts

Dynamic Memory Allocation

malloc()

• The name malloc stands for "memory allocation".

• The function malloc() reserves a block of memory

of specified size and return a pointer of

type void which can be casted into pointer of any

form.Prof. A. Syed Mustafa (Ph.D)

Page 25: Data Structure with C

25

Basic Concepts

Dynamic Memory Allocation

• When memory is no longer needed, we may

free it by calling free() function.

• The call to malloc() determines size of

storage required to hold int or the float.

• The notations (int *) and (float *) are type

cast expressions.

Prof. A. Syed Mustafa (Ph.D)

Page 26: Data Structure with C

26

Basic Concepts

Dynamic Memory Allocation

• The result is a pointer to the first byte of a

storage area of the proper size.

• The return value of the malloc() is void *.

• A call to malloc() may fail for lack of sufficient

memory

Prof. A. Syed Mustafa (Ph.D)

Page 27: Data Structure with C

27

Basic Concepts

Dynamic Memory Allocation

Example:int *pi; float *pf;

pi = (int *) malloc (sizeof(int));

pf = (float *) malloc(sizeof(float));

*pi=1024; *pf=3.124;

printf(“an integer = %d, a float = %f\n”,*pi,*pf);

free(pi); free(pf);

Prof. A. Syed Mustafa (Ph.D)

Page 28: Data Structure with C

28

Basic Concepts

Dynamic Memory Allocation

• When programming in C it is a wise practice to set all pointers to NULL

when they are not pointing to an object.

• Use explicit type casts when converting between pointer types:

pi = malloc(sizeof(int)); /* assign to pi a pointer to int */

pf = (float *) pi; /* casts an int pointer to float pointer */

• In many systems, pointers have the same size as type int. int is the

default type specifier.

Prof. A. Syed Mustafa (Ph.D)

Page 29: Data Structure with C

29

Basic Concepts

Dynamic Memory Allocation

calloc()

• The name calloc stands for "contiguous memory

allocation“ or ‘c’ for cleared.

• The function calloc() allocates a block of memory for an

array of num elements, each of them size bytes long, and

initializes all its bits to zero.

Page 30: Data Structure with C

30

Basic Concepts

Dynamic Memory Allocation

calloc()Syntax

void* calloc (size_t num, size_t size);

Parameters

• num -- Number of elements to allocate.

• size -- Size of each element

• size_t is an unsigned integral type.

Return Value

• On success, a pointer to the memory block allocated by the function.

• The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.

•If the function failed to allocate the requested block of memory, a null pointer is returned.

Prof. A. Syed Mustafa (Ph.D)

Page 31: Data Structure with C

31

Basic Concepts

Dynamic Memory Allocation

calloc()Example

int *ptr1,*ptr2;

ptr1 = (int *)calloc(10, sizeof(int));

ptr2=(int *)calloc(20,sizeof(float));Prof. A. Syed Mustafa (Ph.D)

Page 32: Data Structure with C

32

Basic Concepts

Dynamic Memory Allocation

malloc () & calloc()Differrence

The only difference between malloc() and calloc() is

that, malloc() allocates single block of memory

whereas calloc() allocates multiple blocks of

memory each of same size and sets all bytes to

zero. Prof. A. Syed Mustafa (Ph.D)

Page 33: Data Structure with C

33

Basic Concepts

Dynamic Memory Allocation

malloc () & calloc()Differrence

malloc function, whereas the area reserved to the states that

are undefined, the area allocated by the calloc function

contains a 0.

In fact, the calloc function is internally may be a function that

calls malloc. After securing function by malloc, the area is

filled with 0.

Prof. A. Syed Mustafa (Ph.D)

Page 34: Data Structure with C

34

Basic Concepts

Dynamic Memory Allocation

free()Syntax

void free(void *ptr)

Parameters

• ptr -- Pointer to a memory block previously allocated with malloc(),

calloc() or realloc().Return Value

• None

Note:

If the memeory is not freed , then Dangling pointer arises which leads to garbage collection.

Prof. A. Syed Mustafa (Ph.D)

Page 35: Data Structure with C

35

Basic Concepts

Dynamic Memory Allocation

Prof. A. Syed Mustafa (Ph.D)

Page 36: Data Structure with C

36

Basic Concepts

Dynamic Memory Allocation

Prof. A. Syed Mustafa (Ph.D)

Page 37: Data Structure with C

37

Basic Concepts

Dynamic Memory Allocation

Prof. A. Syed Mustafa (Ph.D)

Page 38: Data Structure with C

38

Basic Concepts

Dynamic Memory Allocation

Prof. A. Syed Mustafa (Ph.D)

Page 39: Data Structure with C

39

Basic Concepts

Dynamic Memory Allocation

realloc() -Reallocate memory block

void *realloc(void *ptr, size_t size)

• The C library function attempts to resize the memory block pointed to by ptr that was previously

allocated with a call to malloc or calloc or realloc

Parametersptr -- This is the pointer to a memory block previously allocated with malloc, calloc orrealloc to be reallocated.If this is NULL, a new block is allocated and a pointer to it isreturned by the function

•size -- This is the new size for the memory block, in bytes.If it is 0 and ptr points to anexisting block of memory, the memory block pointed by ptr is deallocated and a NULLpointer is returned.

Return ValueThis function returns a pointer to the newly allocated memory, or NULL if the requestfails.

Prof. A. Syed Mustafa (Ph.D)

Page 40: Data Structure with C

40

Basic Concepts

Dynamic Memory Allocation

realloc() -Reallocate memory block

• The function realloc() reallocates a memory block with a specific new size.

• If we call realloc() the size of the memory block pointed to by the pointer is

changed to the given size in bytes.

• This way we are able to expand and reduce the amount of memory you

want to use (if available of course.)

• It is possible that the function moves the memory block to a new location,

in which way the function will return this new location.

• If the size of the requested block is larger then the previous block then the

value of the new portion is indeterminate.

Prof. A. Syed Mustafa (Ph.D)

Page 41: Data Structure with C

41

Basic Concepts

Dynamic Memory Allocation

realloc() -Reallocate memory block

• The return value is a pointer to the reallocated memory block, which

may be either the same as ptr or a new location.

• The type of return pointer is void*, which can be cast to the desired

type of data pointer in order to be dereferenceable

• If the pointer is NULL then the function will behave exactly like the function

malloc(). It will assign a new block of a size in bytes and will return a pointer to

it.

• If the size is 0 then the memory that was previously allocated is freed as if a call

of the function free() was given. It will return a NULL pointer in that case.

Prof. A. Syed Mustafa (Ph.D)

Page 42: Data Structure with C

42

•.

#include <stdlib.h>

#include <stdio.h> int main()

{ char *str;

str=(char *) malloc(4); /* Initial memory allocation */

strcpy(str, “data");

printf("String = %s, Address = %p\n", str, str);

/* Reallocating memory */

str = (char *) realloc(str, 13);

strcat(str, “structure");

printf("String = %s, Address = %p\n", str, str);

free(str);

return(0);

}

Basic Concepts

Dynamic Memory Allocation

Prof. A. Syed Mustafa (Ph.D)

Page 43: Data Structure with C

43

Basic Concepts

Dynamic Memory Allocation

free()• Deallocate memory block

• A block of memory previously allocated by a call to malloc(), calloc() or realloc() is deallocated, making it available again for further allocations.

If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior.

If ptr is a null pointer, the function does nothing.

This function does not change the value of ptr itself, hence it still points to the same (now invalid) location.

Prof. A. Syed Mustafa (Ph.D)

Page 44: Data Structure with C

44

Basic Concepts

Dynamic Memory Allocation

free()/* example */

#include <stdlib.h> /* malloc, calloc, realloc, free */

int main ()

{

int * i1, * i2, * i3;

i1 = (int*) malloc (100*sizeof(int));

i2 = (int*) calloc (100,sizeof(int));

i3 = (int*) realloc (i2,500*sizeof(int));

free (i1);

free (i3);

return 0;

}

Prof. A. Syed Mustafa (Ph.D)

Page 45: Data Structure with C

45

Basic Concepts

Algorithm Specification

An algorithm is a finite set of instructions that, if followed, accomplishes a

particular task.

Algorithms must satisfy following criteria:

Input: there are zero or more quantities that are externally supplied.

Output: at least one quantity is produced.

Definiteness: Each instruction is clear and unambiguous.

Finiteness: for all cases, the algorithm terminates after a finite number of

steps.

Effectiveness: Every instruction must be basic enough to be carried out, it

must also be feasible. Prof. A. Syed Mustafa (Ph.D)

Page 46: Data Structure with C

46

Basic Concepts

Algorithm Specification

• Difference between an algorithm and a program :

The program does not have to satisfy the fourth condition

(Finiteness).

• Describing an algorithm:

Natural language such as English can be used. Make sure

resulting instructions are definite.

• Flowchart:

work well only for algorithm, small and simple.

Prof. A. Syed Mustafa (Ph.D)

Page 47: Data Structure with C

47

Basic Concepts

Algorithm Specification

• Difference between an algorithm and a program :

The program does not have to satisfy the fourth condition

(Finiteness).

• Describing an algorithm:

Natural language such as English can be used. Make sure

resulting instructions are definite.

• Flowchart:

work well only for algorithm, small and simple.

Prof. A. Syed Mustafa (Ph.D)

Page 48: Data Structure with C

48

Basic Concepts

Algorithm Specification

Translating a Problem into an Algorithm

Example - Selection Sort

Devise a program that sorts a set of n integers,

where n>= 1, from smallest to largest.

Solution I:

From those integers that are currently unsorted,

find the smallest and place it next in the sorted list

. Prof. A. Syed Mustafa (Ph.D)

Page 49: Data Structure with C

49

Basic Concepts

Algorithm Specification

Translating a Problem into an Algorithm

Describes sorting technique, but it is not an algorithm

Problems:1. Does not describe where and how the integers are initially

sorted.2. Does not indicate where to place the result..

Prof. A. Syed Mustafa (Ph.D)

Page 50: Data Structure with C

50

Basic Concepts

Algorithm Specification

Translating a Problem into an Algorithm

Solution II: Selection Sort

An algorithm, written in partially C and English

for (i= 0; i< n; i++){

Examine list[i] to list[n-1] and suppose thatthe smallest integer is list[min];

Interchange list[i] and list[min];}

.

Page 51: Data Structure with C

51

Basic Concepts

Algorithm Specification

Selection Sort

-find the smallest integer

-interchange or swap

-we can solve the problem using a function or macro

void swap(int *x, int *y) // both arguments are pointers

{

int temp= *x;

*x= *y;

*y= temp;

}Prof. A. Syed Mustafa (Ph.D)

Page 52: Data Structure with C

52

Basic Concepts

Algorithm Specification

Selection Sort

#define swap(x,y,t)((t)= (x), (x)= (y), (y)= (t))

void sort(int list[ ], int n)

{

int i, j, min, temp;

for (i= 0; i< n-1; i++){

min= i;

for (j= i+1; j< n; j++){

if (list[j]< list[min]) min= j;

}

swap(list[i], list[min], temp);

}Prof. A. Syed Mustafa (Ph.D)

Page 53: Data Structure with C

53

Basic Concepts

Algorithm Specification

Theorem 1.1:

sort(a, n) correctly sorts a set of n ≥ 1 integers; the

result remains in a[0] … a[n-1] such that

a[0] ≤ a[1] ≤ … ≤ a[n–1].

Prof. A. Syed Mustafa (Ph.D)

Page 54: Data Structure with C

54

Basic Concepts

Algorithm Specification

Example: Binary Search

Assume that we have n ≥ 1 distinct integers that

are already sorted and stored in the array a[0] … a[n-1].

Our task is to determine if the integer x is present and

if so to return j such that x = a[j]; otherwise return -1.

Prof. A. Syed Mustafa (Ph.D)

Page 55: Data Structure with C

55

Basic Concepts

Algorithm Specification

Example: Binary Search

1. Let left and right, respectively, denote the left and right ends of the list to be searched.

2. Initially, left = 0 and right = n – 1.

3. Let middle = (left + right) / 2 be the middle position in the list.

4. If we compare a[middle] with x, we obtain one of the three results.

Prof. A. Syed Mustafa (Ph.D)

Page 56: Data Structure with C

56

Basic Concepts

Algorithm Specification

Example: Binary Search

1. x < a[middle] In this case, if x is present, it must be in the positions between 0 and middle – 1. Therefore, we set right to middle – 1.

2. x == a[middle]In this case, we return middle.

3. x > a[middle] In this case, if x is present, it must be in the positionsbetween middle+1 and n-1. So, we set left tomiddle+1.

Prof. A. Syed Mustafa (Ph.D)

Page 57: Data Structure with C

57

Basic Concepts

Algorithm Specification

Binary Search.

Prof. A. Syed Mustafa (Ph.D)

Page 58: Data Structure with C

58

Basic Concepts

Algorithm Specification

Binary Search.

int compare (int x, int y)

{

if (x < y) return -1;

else if ( x == y) return 0;

else return 1;

} // end of compare

Macro

#define compare (x, y) ( ( (x) < (y) ) ? -1: ( (x) == (y) ) ? 0 : 1 )

Prof. A. Syed Mustafa (Ph.D)

Page 59: Data Structure with C

59

Basic Concepts

Algorithm Specification

Algorithms are implemented as functions in C.

Functions divide the programs into manageable

pieces.

They make program easier to read.

Functions can be tested separately.

Declare function first then define it later.

Prof. A. Syed Mustafa (Ph.D)

Page 60: Data Structure with C

60

Basic Concepts

Algorithm Specification

Recursive algorithm

There are mainly two approaches for repetitive

approach.

1. Iteration

2. Recursion

Recursion is a repetitive process in which an

algorithm calls itself.

Prof. A. Syed Mustafa (Ph.D)

Page 61: Data Structure with C

61

Basic Concepts

Algorithm Specification

Recursive algorithm

The following Figure 1 and Figure 2 portrayed the typical

pictorial examples for recursive calling.

Prof. A. Syed Mustafa (Ph.D)

Page 62: Data Structure with C

62

Basic Concepts

Algorithm Specification

Recursive algorithm

The following Figure2 portrayed the typical pictorial

examples for recursive calling.

Prof. A. Syed Mustafa (Ph.D)

Page 63: Data Structure with C

63

Basic Concepts

Algorithm Specification

Recursive algorithm

The following Figure portrayed the typical pictorial

examples for recursive calling.

Prof. A. Syed Mustafa (Ph.D)

Page 64: Data Structure with C

64

Basic Concepts

Algorithm Specification

Recursive algorithm

Recursion is a programming technique in

which a method can call itself to solve a

problem.

Two Types:

1. Direct Recursion

2. Indirect recursion

Prof. A. Syed Mustafa (Ph.D)

Page 65: Data Structure with C

65

Basic Concepts

Algorithm Specification

Recursive algorithm

1. Direct Recursion

Functions calls themselves

2. Indirect recursionFunctions calls other function that invoke the

calling function again.

Any function that we can write using assignment, if-

else and while statements can be written recursively.

Prof. A. Syed Mustafa (Ph.D)

Page 66: Data Structure with C

66

Basic Concepts

Algorithm Specification

Value of Recursion

This is well suited an alternative concept in the following

situations

1. Recursion can be used to replace loop

2. A recursive procedure is mathematically more elegant than

one using loops

3. Sometime procedure that would tricky to write a loop are

straightforward to using recursion.

4. Recursively defined data structure, like list, are very well

suited to processing by recursive procedures and functionsProf. A. Syed Mustafa (Ph.D)

Page 67: Data Structure with C

67

Basic Concepts

Algorithm Specification

Prof. A. Syed Mustafa (Ph.D)

Page 68: Data Structure with C

68

Basic Concepts

Algorithm Specification

Prof. A. Syed Mustafa (Ph.D)

Page 69: Data Structure with C

69

Basic Concepts

Algorithm Specification

Algorithm to compute factorial using recursive method:

Factorial (N)

1. Receive N

2. if N > 1 return

Factorial(N-1) * N

else

return 1

Prof. A. Syed Mustafa (Ph.D)

Page 70: Data Structure with C

70

Basic Concepts

Algorithm Specification

program to compute factorial using recursive function:#include<stdio.h>

long factorial(int);

int main()

{ int n; long f;

printf("Enter an integer to find factorial\n");

scanf("%d", &n);

if (n < 0)printf("Negative integers are not allowed\n");

else { f = factorial(n);printf("%d! = %ld\n", n, f); }

return 0; }

long factorial(int n)

{ if (n == 0) return 1;

else return(n * factorial(n-1));

}Prof. A. Syed Mustafa (Ph.D)

Page 71: Data Structure with C

71

Basic Concepts

Algorithm Specification

program to compute factorial using recursive function:

Prof. A. Syed Mustafa (Ph.D)

Page 72: Data Structure with C

72

Basic Concepts

Algorithm Specification

program to compute factorial using recursive function:

Prof. A. Syed Mustafa (Ph.D)

Page 73: Data Structure with C

73

Basic Concepts

Algorithm Specification

program to compute factorial using recursive function:

Prof. A. Syed Mustafa (Ph.D)

Page 74: Data Structure with C

74

Basic Concepts

Algorithm Specification

program to compute factorial using recursive function:

Prof. A. Syed Mustafa (Ph.D)

Page 75: Data Structure with C

75

Basic Concepts

Algorithm Specification

program to compute factorial using recursive function:

Prof. A. Syed Mustafa (Ph.D)

Page 76: Data Structure with C

76

Basic Concepts

Algorithm Specification

Prof. A. Syed Mustafa (Ph.D)

Page 77: Data Structure with C

77

Basic Concepts

Algorithm Specification

Prof. A. Syed Mustafa (Ph.D)

Page 78: Data Structure with C

78

Basic Concepts

Algorithm Specification

Prof. A. Syed Mustafa (Ph.D)

Page 79: Data Structure with C

79

Basic Concepts

Algorithm Specification

Recursive program: Fibonacci int main(){

int n=10;printf(“%d”, rfib(n));

}

int rfib(int n){

if (n==1 || n==2) return 1;return rfib(n1) + rfib(n2);

}

Prof. A. Syed Mustafa (Ph.D)

Page 80: Data Structure with C

80

Basic Concepts

Algorithm Specification

Recursive program: Fibonacci

Prof. A. Syed Mustafa (Ph.D)

Page 81: Data Structure with C

81

Basic Concepts

Algorithm Specification

Recursive program: Fibonacci

Prof. A. Syed Mustafa (Ph.D)

Page 82: Data Structure with C

82

Basic Concepts

Algorithm Specification

Recursive program: Fibonacci

Prof. A. Syed Mustafa (Ph.D)

Page 83: Data Structure with C

83

Basic Concepts

Algorithm Specification

Recursive algorithm: Greatest Common Divisor(x, y)

Prof. A. Syed Mustafa (Ph.D)

Page 84: Data Structure with C

84

Basic Concepts

Algorithm Specification

/* PROGRAM TO FIND GCD OF TWO NUMBER USING RECURSION

EUCLIDS*/

#include<stdio.h>

#include<conio.h>

int gcd(int,int);

int main()

{ int a,b;

clrscr();

printf("\n Enter two number:" );

scanf("%d %d",&a,&b);

printf("GCD of two number : %d" ,gcd(a,b));

getch();

return(0);

}

Prof. A. Syed Mustafa (Ph.D)

Page 85: Data Structure with C

85

Basic Concepts

Algorithm Specification

/* PROGRAM TO FIND GCD OF TWO NUMBER USING RECURSION

int gcd(int m, int n)

{

if(m==0)

return n;

if(n==0)

return m;

return gcd(n,m%n);

}

Prof. A. Syed Mustafa (Ph.D)

Page 86: Data Structure with C

86

Basic Concepts

Algorithm Specification

/* PROGRAM TO FIND GCD OF TWO NUMBER USING RECURSION

int gcd(int a, int b)

{ if (a != b)

{if (a > b)

return gcd(a - b, b);

elsereturn gcd(a, b - a);

}return a;

}Prof. A. Syed Mustafa (Ph.D)

Page 87: Data Structure with C

87

Basic Concepts

Algorithm Specification

Recursive algorithm: Greatest Common Divisor(x, y)

Prof. A. Syed Mustafa (Ph.D)

Page 88: Data Structure with C

88

Basic Concepts

Algorithm Specification

Recursive algorithm

Prof. A. Syed Mustafa (Ph.D)

Page 89: Data Structure with C

89

Basic Concepts

Algorithm Specification

Recursive algorithm

Prof. A. Syed Mustafa (Ph.D)

C(n, k) = C(n-1, k-1) + C(n-1, k) C(n, 0) = C(n, n) = 1

Page 90: Data Structure with C

90

Basic Concepts

Algorithm Specification

Recursive algorithm-Binomial Coefficient

Prof. A. Syed Mustafa (Ph.D)

int binomialCoeff(int n, int k) // Returns value of Binomial Coefficient C(n, k)

{

if (k==0 || k==n) // Base Cases

return 1;

return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k); // Recur

}

int main() /* program to test above function*/

{

int n = 5, k = 2;

printf("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k)); // C(5,2) is 10

return 0;

}

Page 91: Data Structure with C

91

Basic Concepts

Algorithm Specification

Recursive algorithm -Binomial Coefficient

Prof. A. Syed Mustafa (Ph.D)

Page 92: Data Structure with C

92

Basic Concepts

Algorithm Specification

Recursive algorithm: Towers of Hanoi

Prof. A. Syed Mustafa (Ph.D)

Page 93: Data Structure with C

93

Basic Concepts

Algorithm Specification

Recursive algorithm: Towers of Hanoi

Prof. A. Syed Mustafa (Ph.D)

•Label the stands Src, Intr, Dest.

•Let n be the total number of discs.

•Number the discs from 1 (smallest, topmost) to n (largest, bottommost).

To move n discs from stand Src to stand Dest:

1.Move n-1 plates from Src to Intr. This leaves plate #n alone on plate Src.

2.Move plate #n from Src to Dest.

3.Move n-1 plates from Intr to Dest so they sit on plate #n.

Page 94: Data Structure with C

94

Basic Concepts

Algorithm Specification

Recursive algorithm: Towers of Hanoi

Prof. A. Syed Mustafa (Ph.D)

Page 95: Data Structure with C

95

Basic Concepts

Algorithm Specification

Recursive algorithm: Towers of Hanoi

Prof. A. Syed Mustafa (Ph.D)

FUNCTION MoveTower(disk, source, dest, inter)IF disk == 1, THEN:

move disk from source to destELSE:

MoveTower(disk - 1, source, inter, dest) // Step 1 abovemove disk from source to dest // Step 2 above

MoveTower(disk - 1, inter, dest, source) // Step 3 above

END IF

Page 96: Data Structure with C

96

Basic Concepts

Algorithm Specification

Recursive algorithm: Towers of Hanoi

Prof. A. Syed Mustafa (Ph.D)

Page 97: Data Structure with C

97

Basic Concepts

Algorithm Specification

Recursive algorithm: Towers of Hanoi

Prof. A. Syed Mustafa (Ph.D)

Page 98: Data Structure with C

98

Basic Concepts

Algorithm Specification

Recursive algorithm: Towers of Hanoi

Prof. A. Syed Mustafa (Ph.D)

Page 99: Data Structure with C

99

Basic Concepts

Algorithm Specification

Limitations of Recursion

Recursion should not be used if the answer to any of the

following questions is no:

Is the algorithm or data structure naturally suited to recursion (tree

is the first choice) ?

Is the recursive solution shorter and more understandable?

Does the recursive solution run within acceptable time and space

limits ?

As a general rule, recursive algorithms should be effectively used

only when their efficiency is logarithmic.

Prof. A. Syed Mustafa (Ph.D)

Page 100: Data Structure with C

100

Basic Concepts

Data Abstraction

Abstraction is the process by which data and

programs are defined with a representation similar to

its meaning (semantics), while hiding away the

implementation details.

Prof. A. Syed Mustafa (Ph.D)

Page 101: Data Structure with C

101

Basic Concepts

Data Abstraction

Abstraction tries to reduce and factor out details so that

the programmer can focus on a few concepts at a time. A

system can have several abstraction layers whereby

different meanings and amounts of detail are exposed to

the programmer.

For example, low-level abstraction layers expose details

of the hardware where the program is run, while high-

level layers deal with the business logic of the program.Prof. A. Syed Mustafa (Ph.D)

Page 102: Data Structure with C

102

Basic Concepts

Data Abstraction

Prof. A. Syed Mustafa (Ph.D)

Page 103: Data Structure with C

103

Basic Concepts

Data Abstraction

Prof. A. Syed Mustafa (Ph.D)

Page 104: Data Structure with C

104

Basic Concepts

Data Abstraction

Prof. A. Syed Mustafa (Ph.D)

Page 105: Data Structure with C

105

Basic Concepts

Data Abstraction

Prof. A. Syed Mustafa (Ph.D)

Page 106: Data Structure with C

106

Basic Concepts

Data Abstraction

Prof. A. Syed Mustafa (Ph.D)

Page 107: Data Structure with C

107

Basic Concepts

Data Abstraction

Prof. A. Syed Mustafa (Ph.D)

Page 108: Data Structure with C

108

Basic Concepts

Data Abstraction

Prof. A. Syed Mustafa (Ph.D)

Page 109: Data Structure with C

109

Basic Concepts

Data Abstraction

Prof. A. Syed Mustafa (Ph.D)

Page 110: Data Structure with C

110

Basic Concepts

Data Abstraction

Prof. A. Syed Mustafa (Ph.D)

Page 111: Data Structure with C

111

Basic Concepts

Data Abstraction

Prof. A. Syed Mustafa (Ph.D)

Page 112: Data Structure with C

112

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 113: Data Structure with C

113

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Space & Time

Does the program efficiently use primary and

secondary storage ?

Is the program’s running time acceptable for the

task ?

Page 114: Data Structure with C

114

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 115: Data Structure with C

115

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

The space complexity of a program is the

amount of memory that it needs to run to

completion.

The time complexity of a program is the amount

of computer time that it needs to run to

completion

Page 116: Data Structure with C

116

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 117: Data Structure with C

117

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 118: Data Structure with C

118

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 119: Data Structure with C

119

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 120: Data Structure with C

120

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 121: Data Structure with C

121

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 122: Data Structure with C

122

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 123: Data Structure with C

123

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 124: Data Structure with C

124

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 125: Data Structure with C

125

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 126: Data Structure with C

126

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

TP(n) = Ca ADD(n)+ CsSUB(n)+CLLDA(n)+CstSTA(n)

n –Instance Characteristic

Ca , Cs , CL , Cst – constants-time needed to perorm

each operation

ADD - No of additionsSUB - No of SubtractionLDA – No of LoadsSTA – No of Stores

Performed when the program is run with instance characteristic n.

Page 127: Data Structure with C

127

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 128: Data Structure with C

128

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 129: Data Structure with C

129

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 130: Data Structure with C

130

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 131: Data Structure with C

131

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 132: Data Structure with C

132

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

General statements in a C programStep count

1. Comments 02. Declarative statements 03. Expressions and assignment statements 14. Iteration statements N5. Switch statement N6. If-else statement N7. Function invocation 1 or N8. Memory management statements 1 or N9. Function statements 010.Jump statements 1 or N

Page 133: Data Structure with C

133

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Note that a step count does not necessarily

reflect the complexity of the statement.

Step per execution (s/e):

The s/e of a statement is the amount by which

count changes as a result of the execution of

that statement.

Page 134: Data Structure with C

134

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 135: Data Structure with C

135

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 136: Data Structure with C

136

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 137: Data Structure with C

137

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 138: Data Structure with C

138

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 139: Data Structure with C

139

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 140: Data Structure with C

140

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 141: Data Structure with C

141

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 142: Data Structure with C

142

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 143: Data Structure with C

143

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 144: Data Structure with C

144

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 145: Data Structure with C

145

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 146: Data Structure with C

146

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 147: Data Structure with C

147

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 148: Data Structure with C

148

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 149: Data Structure with C

149

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 150: Data Structure with C

150

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 151: Data Structure with C

151

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 152: Data Structure with C

152

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 153: Data Structure with C

153

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 154: Data Structure with C

154

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 155: Data Structure with C

155

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 156: Data Structure with C

156

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 157: Data Structure with C

157

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 158: Data Structure with C

158

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 159: Data Structure with C

159

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 160: Data Structure with C

160

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 161: Data Structure with C

161

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 162: Data Structure with C

162

Basic Concepts

Performance Analysis

Prof. A. Syed Mustafa (Ph.D)

Page 163: Data Structure with C

Prof. A. Syed Mustafa (Ph.D) 163