engineering colleges 2015 16 even semester minimum …

206
ENGINEERING COLLEGES 2015 16 Even Semester MINIMUM STUDY MATERIAL (MSM) Department of CSE SUBJECT CODE: CS6202 SUBJECT NAME: Programming and Data Structures I Regulation: 2013 Semester and Year: 02 and I Prepared by Sl. No. Name of the Faculty Designation Affiliating College 1 Mrs.T.Subbulakshmi Asso. Prof/IT FXEC 2 Mrs.C.Vinola AP/CSE FXEC 3 Mrs. P.Brundha AP/CSE FXEC 4 Mrs.Lourdes Mary Asso.Prof/CSE SCADCET 5 Mr.Amala Princeton AP/CSE SMTEC Verified by DLI, CLI and Approved by the Centralized Monitoring Team www.Vidyarthiplus.com www.Vidyarthiplus.com

Upload: others

Post on 14-Mar-2022

1 views

Category:

Documents


0 download

TRANSCRIPT

ENGINEERING COLLEGES

2015 – 16 Even Semester MINIMUM STUDY MATERIAL (MSM)

Department of CSE

SUBJECT CODE: CS6202

SUBJECT NAME: Programming and Data Structures I

Regulation: 2013 Semester and Year: 02 and I

Prepared by

Sl.

No. Name of the Faculty Designation

Affiliating

College

1 Mrs.T.Subbulakshmi Asso. Prof/IT FXEC

2 Mrs.C.Vinola AP/CSE FXEC

3 Mrs. P.Brundha AP/CSE FXEC

4 Mrs.Lourdes Mary Asso.Prof/CSE SCADCET

5 Mr.Amala Princeton AP/CSE SMTEC

Verified by DLI, CLI and Approved by the Centralized Monitoring Team

www.Vidyarthiplus.com

www.Vidyarthiplus.com

ANNA UNIVERSITY SYLLABUS COPY (REGULATION 2013)

CS6202 PROGRAMMING AND DATA STRUCTURES I L T P C 3 0 0 3 UNIT I C PROGRAMMING FUNDAMENTALS- A REVIEW 9 Conditional statements – Control statements – Functions – Arrays – Preprocessor - Pointers - Variation in pointer declarations – Function Pointers – Function with Variable number of arguments UNIT II C PROGRAMMING ADVANCED FEATURES 9 Structures and Unions - File handling concepts – File read – write – binary and Stdio - File Manipulations UNIT III LINEAR DATA STRUCTURES – LIST 9 Abstract Data Types (ADTs) – List ADT – array-based implementation – linked list implementation ––singly linked lists- circularly linked lists- doubly-linked lists – applications of lists –Polynomial Manipulation – All operation (Insertion, Deletion, Merge, Traversal) UNIT IV LINEAR DATA STRUCTURES – STACKS, QUEUES 9 Stack ADT – Evaluating arithmetic expressions- other applications- Queue ADT – circular queue implementation – Double ended Queues – applications of queues UNIT V SORTING, SEARCHING AND HASH TECHNIQUES 9 Sorting algorithms: Insertion sort - Selection sort - Shell sort - Bubble sort - Quick sort - Merge sort -Radix sort – Searching: Linear search –Binary Search Hashing: Hash Functions – Separate Chaining – Open Addressing – Rehashing – Extendible Hashing

TOTAL: 45 PERIODS TEXT BOOKS: 1. Brian W. Kernighan and Dennis M. Ritchie, ―The C Programming Language‖, 2nd Edition, Pearson Education, 1988. 2. Mark Allen Weiss, ―Data Structures and Algorithm Analysis in C‖, 2nd Edition, Pearson Education, 1997. REFERENCES: 1. Thomas H. Cormen, Charles E. Leiserson, Ronald L.Rivest, Clifford Stein, ―Introduction

to Algorithms", Second Edition, Mcgraw Hill, 2002. 2. Reema Thareja, ―Data Structures Using C‖, Oxford University Press, 2011 3. Aho, Hopcroft and Ullman, ―Data Structures and Algorithms‖, Pearson Education,1983. 4. Stephen G. Kochan, ―Programming in C‖, 3rd edition, Pearson Ed., 5. Anita Goel & Ajay Mittal, ―Computer Fundamentals and Programming in C‖, Pearson Education. 6. Byron S.Gotfried ―Programming with C‖, Second Edition, Tata Mc.Graw Hill.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

TABLE OF CONTENTS Sl.no Topic Page No

a Aim and Objective of the Subject 1 b Detailed Lesson Plan 2

UNIT I C PROGRAMMING FUNDAMENTALS- A REVIEW c Part A 4 d Part B 8 1 Conditional Statements 8 2 Control Statements 15 3 Types of functions 20 4 Functions(Pointers and Variable Arguments) 27 5 Arrays 30 6 Preprocessor Operators 35 7 C programs 38

UNIT II C PROGRAMMING ADVANCED FEATURES e Part A 44 f Part B 47 8 Structures 47 9 Unions 57 10 File Manipulation Functions 60 11 Programs in structures 69 12 Programs in File Handling 78

UNIT III LINEAR DATA STRUCTURES – LIST g Part A 82 h Part B 86 13 Doubly Linked list 86 14 Singly Linked List 97 15 Polynomial Manipulation 109 16 Circularly Linked list 112 17 Array Implementation of List 120

UNIT IV LINEAR DATA STRUCTURES – STACKS, QUEUES i Part A 126 j Part B 129

18 Stack ADT implementation 129 19 Evaluating Arithmetic expressions 134 20 Applications of Stack 136 21 Queue ADT implementation 141 22 Circular Queue Implementation 145 23 Double Ended Queues 148

UNIT V SORTING, SEARCHING AND HASH TECHNIQUES k Part A 153 l Part B 156

24 Shell sort & Insertion sort 156 25 Selection sort & Insertion sort 160 26 Quick, Merge & Radix sort 165 27 Hashing & Collision Resolution Techniques 175 28 Linear Search & Binary Search 183 29 Rehashing & Extendible Hashing 187 30 Problems in Hashing 190 m Industrial/Practical Connectivity of the subject 194 31 University Question Bank 195

www.Vidyarthiplus.com

www.Vidyarthiplus.com

1

AIM AND OBJECTIVE OF THE SUBJECT

To introduce the basics and advanced concepts of C programming

language

Be familiar with writing programs using techniques in C programming.

To introduce the concepts of ADTs

To Master the implementation of linked data structures such as linked lists,

stacks and queues.

Be familiar with several algorithms including quicksort, mergesort and

radix sort.

To introduce the concepts of Hashing

To Master analyzing problems and writing program solutions to problems

using the above techniques

www.Vidyarthiplus.com

www.Vidyarthiplus.com

2

DETAILED LESSON PLAN

TEXT BOOKS: 1. Brian W. Kernighan and Dennis M. Ritchie, ―The C Programming Language‖, 2nd Edition, Pearson Education, 1988. 2. Mark Allen Weiss, ―Data Structures and Algorithm Analysis in C‖, 2nd Edition, Pearson

Education, 1997. REFERENCES: 1. Thomas H. Cormen, Charles E. Leiserson, Ronald L.Rivest, Clifford Stein, ―Introduction to Algorithms", Second Edition, Mcgraw Hill, 2002. 2. Reema Thareja, ―Data Structures Using C‖, Oxford University Press, 2011 3. Aho, Hopcroft and Ullman, ―Data Structures and Algorithms‖, Pearson Education,1983. 4. Stephen G. Kochan, ―Programming in C‖, 3rd edition, Pearson Ed., 5. Anita Goel & Ajay Mittal, ―Computer Fundamentals and Programming in C‖, Pearson Education. 6. Byron S.Gotfied ―Programming with C‖, Second Edition, Tata Mc.Graw Hill.

Sl. No

Unit Topic / Portions to be Covered Hours

Required / Planned

Cumulative Hrs

Books Referred

UNIT I C PROGRAMMING FUNDAMENTALS- A REVIEW

1 1 Conditional statements 1 1 RB5

2 1 Control statements 1 2 RB5

3 1 Functions 1 3 RB5

4 1 Arrays- 1-d arrays & 2-d arrays 2 5 RB5

5 1 Preprocessor 1 6 RB5

6 1 Pointers -Variation in pointer declarations 2 8 RB5

7 1 Function Pointers 1 9 RB5

8 1 Function with Variable number of arguments

1 10 RB5

UNIT II C PROGRAMMING ADVANCED FEATURES

9 2 Structures 2 12 RB5

10 2 Unions 1 13 RB5

11 2 File handling concepts 2 15 RB6

12 2 File-read 1 16 RB6

13 2 File-write 1 17 RB6

14 2 Binary and stdio 1 18 RB6

15 2 File manipulations 1 19 RB6

16 2 Programs in File handling 1 20 RB6

www.Vidyarthiplus.com

www.Vidyarthiplus.com

3

Sl. No Unit Topic / Portions to be Covered

Hours Required /

Planned

Cumulative Hrs

Books Referred

UNIT III LINEAR DATA STRUCTURES – LIST

17 3 Abstract Data Types (ADTs) 1 21 TB2

18 3 List ADT- Array-based implementation 1 22 TB2

19 3 Linked list implementation 1 23 TB2

20 3 Singly linked lists 2 25 TB2

21 3 Circularly linked lists 1 26 TB2

22 3 Doubly-linked lists 1 27 TB2

23 3 Applications of lists –Polynomial Manipulation

2 29 TB2

24 3 All operation (Insertion, Deletion, Merge, Traversal)- programs

1 30 TB2

UNIT IV LINEAR DATA STRUCTURES – STACKS, QUEUES

25 4 Stack ADT 1 31 TB2

26 4

Evaluating arithmetic expressions-infix,postfic

2 33 TB2

27 4 Other applications 2 35 TB2

28 4 Queue ADT 1 36 TB2

29 4 Circular queue implementation 2 38 TB2

30 4 Double ended Queues 1 39 TB2

31 4 Applications of queues 1 40 TB2

UNIT V SORTING, SEARCHING AND HASH TECHNIQUES

37 5 Sorting algorithms: Insertion sort 1 41 TB2

38 5 Selection sort - Shell sort 1 42 TB2

39 5 Bubble sort - Quick sort 1 43 TB2

40 5 Merge sort -Radix sort 2 45 TB2

41 5 Searching: Linear search 1 46 TB2

42 5 Binary Search 1 47 TB2

43 5 Hashing: Hash Functions – Separate Chaining

1 48 TB2

44 5 Open Addressing – Rehashing 1 49 TB2

45 5 Extendible Hashing 1 50 TB2

www.Vidyarthiplus.com

www.Vidyarthiplus.com

4

UNIT I C PROGRAMMING FUNDAMENTALS- A REVIEW

PART-A

1. What are control statements? Control statements are used to break the normal flow of the program and execute part of the statement based on some condition. They include i. Branching statements ii. Iteration statements 2.What are the various branching and looping statements available in C ? Branching statements: If statement if…else statement nested if statement if…else ladder statement switch statement Looping statements: for while do…while

3. What is the difference between while and do….while statement? The while is an entry controlled statement. The statement inside the while may not be executed at all when the condition becomes false at the first attempt itself. Example: i=0; while(i<=100) { i++; } Here the condition is checked first and then if it is true i is incremented. The do …while is an exit controlled statement. The statements in the block are executed at

least once. do { i++; }while(i<=100);

Conitional statements – Control statements – Functions – Arrays – Preprocessor - Pointers -Variation in pointer declarations – Function Pointers – Function with Variable number of arguments

www.Vidyarthiplus.com

www.Vidyarthiplus.com

5

Here the value of i is incremented and then the condition is checked. 4. Define function? Functions are group of statements that can perform a task. Functions reduce the amount of coding and one function can be called from another function. Example: void fun() { ---- ---- } main() { fun(); } Here fun() is called from main() function. 5. Define array. Give an example. Nov/Dec 2014 An array is a collection of data of same data type. The elements of the array are stored in continuous memory location and array elements are processing using its index. Example: int a[10]; Here "a" is an array name. 6. What is two dimensional array? Two dimensional is an array of one dimensional array also called as matrix. The elements in the array are referenced with help of its row and column index. Example: int a[2][2]; Here a 2*2 matrix is created containing a total of 4 elements. 7. Distinguish between Call by value Call by reference. Nov/Dec 2014

Call by value Call by reference In call by value, the value of actual values is passed to formal arguments.

In call by reference, the address of actual arguments is passed to the formal arguments.

Formal arguments are photocopies of the actual argument values.

Formal arguments values are pointers to actual arguments.

Changes made in formal arguments do not affect the actual arguments

Changes are made in both the arguments

void swap(int a,int b){ int t; t=a;

void swap(int *a,int *b){ int t; t=*a;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

6

Call by value Call by reference a=b; b=t;}

*a=*b; *b=t;}

8. Define recursive function and differentiate with iterative function? What is recursion? Give example. Nov/Dec 2015 A function is a set of instructions used to perform a specified task which repeatedly occurs in the main program. If a function calls itself again and again , then that function is called recursive function. Example: int fact(int n) { if(n==0||n==1) return 1; else return(n*fact(n-1)); } Difference of recursion and iteration:

RECURSION ITERATION

Recursive function – is a function that is partially defined by itself

Iterative Instructions –are loop based repetitions of a process

Infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges on some condition.(base case)

An infinite loop occurs with iteration if the loop-condition test never becomes false

Recursion terminates when a base case is recognized

Iteration terminates when the loop-condition fails

Recursion is usually slower then iteration due to overhead of maintaining stack

Iteration does not use stack so it's faster than recursion

Recursion uses more memory than iteration

Iteration consume less memory

Recursion makes code smaller Iteration makes code longer

9. What is a Pointer? List the uses of pointers. Pointer is a variable which holds the address of another variable of the same data type. Pointer Declaration: datatype *variable-name; Example: int *x, c=5; x=&c;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

7

Uses: Pointers are used to return more than one value to the function Pointers are more efficient in handling the data in arrays

Pointers reduce the length and complexity of the program They increase the execution speed The pointers save data storage space in memory 10. What will be the output of the following program? #include<stdio.h> int main() { int i=3; int *j; int **k; j=&i; k=&j; printf(“%u %u %d”,k,*k,**k); return 0; } k j 2000 i 1000 Output: 2000 1000 3 11. Define null pointer? A pointer is said to be a null pointer when its right value is 0, a null pointer can never point to a valid data. For checking a pointer, if it is assigned to 0 or NULL, then it is a null pointer and is not valid Example: int *a; int *b; a=b=0; 12. Define pre-processor in C. May/June 2014,April/May 2015 Preprocessor is a translator that converts a program written in one high level language into an equivalent program written in another high level language. It is controlled by directives called preprocessor directives. Important Directives are as follows: Macro inclusion

2000(&j) 1000(&i) 3

www.Vidyarthiplus.com

www.Vidyarthiplus.com

8

#define PI 3.14 PI-macro which is replaced by 3.14 in the statements used Conditional inclusion #ifdef #endif File inclusion #include<stdio.h>

13. What are function pointers in C? Explain with example April/May 2015 A pointer to a function commonly known as function pointer is a variable that points to the starting address of the function. Example: int(*ptr)(int)=fun; fun is the name of the function the address of which is assigned to the pointer. fun can be called as (*ptr)(5); 14. With the help of printf function show how C handles functions with variable number of arguments. May/June 2014 A function that accepts a variable number of arguments is called a variable argument function. printf is a variable argument function which accepts one or more arguments , first one being char * and no constraint on the remaining type of arguments. The following calls are valid: printf("Hello\n"); Displays Hello printf("%d",a); Displays integer value of a printf(%d %f",a,b); Displays integer a and floating point b 15. What are the macros used in variable argument functions? va_list va_start va_arg

va_end They are available in stdarg.h

PART-B

1. CONDITIONAL STATEMENTS

Explain the various conditional statements in C language with example in detail Nov/Dec2014/ Nov/Dec 2015

Conditional statements(Branching statements) are used to execute a statement or a group of statement based on certain conditions. The ability to control the flow of our program, letting it make decisions on what code to execute, is valuable to the programmer. One of the

www.Vidyarthiplus.com

www.Vidyarthiplus.com

9

important functions of the conditional statement is that it allows the program to select an action based upon the user's input. Following are the conditional statements: if

if else else if switch

goto IF STATEMENT If the test expression is true then, statements for the body if, i.e, statements inside parenthesis are executed. But, if the test expression is false, the execution of the statements for the body of if statements are skipped. Syntax: if (test expression){ statement/s to be executed if test expression is true; } Flowchart:

Example of if statement: Write a C program to print the number entered by user only if the number entered is negative. #include <stdio.h> void main() { int num; printf("Enter a number to check.\n"); scanf("%d",&num);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

10

if(num<0) /* checking whether number is less than 0 or not. */ printf("Number=%d\n",num); /*If test condition is true, statement above will be executed, otherwise it will not be executed */ printf("The if statement in C programming is easy.") } Output Enter a number to check.-2 Number=-2 The if statement in C programming is easy. When user enters -2 then, the test expression (num<0) becomes true. Hence, Number=-2 is displayed in the screen. IF ..ELSE: The if...else statement is used, if the programmer wants to execute some code, if the test expression is true and execute some other code if the test expression is false. Syntax of if...else: if (test expression) statements to be executed if test expression is true; else statements to be executed if test expression is false; Flowchart of if...else statement:

Example of if...else statement: Write a C program to check whether a number entered by user is even or odd #include <stdio.h> void main(){ int num; printf("Enter a number you want to check.\n"); scanf("%d",&num); if((num%2)==0) //checking whether remainder is 0 or not. printf("%d is even.",num);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

11

else printf("%d is odd.",num); } Output 1 Enter a number you want to check. 25 25 is odd. Output 2 Enter a number you want to check. 2 2 is even. IF.. ELSE IF..ELSE: The if...else statement can be used in nested form when a serious decision are involved. Syntax of nested if...else statement: if (test expression) statements to be executed if test expression is true; else if(test expression 1) statements to be executed if test expressions 1 is true; else if (test expression 2) . . else statements to be executed if all test expressions are false; How nested if...else works? If the test expression is true, it will execute the code before else part but, if it is false, the control of the program jumps to the else part and check test expression 1 and the process continues. If all the test expression are false then, the last statement is executed. Example of nested if else statement #include <stdio.h> void main(){

int numb1, numb2; printf("Enter two integers to check".\n); scanf("%d %d",&numb1,&numb2); if(numb1==numb2) //checking whether two integers are equal. printf("Result: %d=%d",numb1,numb2); else if(numb1>numb2) //checking whether numb1 is greater than numb2. printf("Result: %d>%d",numb1,numb2); else

www.Vidyarthiplus.com

www.Vidyarthiplus.com

12

printf("Result: %d>%d",numb2,numb1); } Output 1 Enter two integers to check. 5 3 Result: 5>3 Output 2 Enter two integers to check. -4 -4 Result: -4=-4 SWITCH....CASE STATEMENT: If a programmar has to choose one among many alternatives if...else can be used but, this makes programming logic complex. This type of problem can be handled in C programming using switch...case statement. Syntax of switch...case: switch (expression) {

case constant1: codes to be executed if expression equals to constant1; break; case constant2: codes to be executed if expression equals to constant3; break; . default: codes to be executed if expression doesn't match to any cases;

}

www.Vidyarthiplus.com

www.Vidyarthiplus.com

13

In switch...case, expression is either an integer or a character. If the value of switch expression matches any of the constant in case, the relevant codes are executed and control moves out of the switch...case statement. If the expression doesn't match any of the constant in case, then the statements in the default section are executed. Example of switch...case statement: Write a program that asks user an arithmetic operator('+','-','*' or '/') and two operands and perform the corresponding calculation on the operands. /* C program to demonstrate the working of switch...case statement */ /* Program to create a simple calculator for addition, subtraction, multiplication and division */ # include <stdio.h> int main(){ char operator; float num1,num2; printf("Enter operator +, - , * or / :\n"); operator=getche(); printf("\nEnter two operands:\n"); scanf("%f%f",&num1,&num2); switch(operator) { case '+': printf("num1+num2=%.2f",num1+num2); break; case '-': printf("num1-num2=%.2f",num1-num2); break; case '*': printf("num1*num2=%.2f",num1*num2); break; case '/': printf("num2/num1=%.2f",num1/num2); break; default: /* if operator is other than +, -, * or /, error message is shown */ printf(Error! operator is not correct"); break; } return 0; } Output

www.Vidyarthiplus.com

www.Vidyarthiplus.com

14

Enter operator +, -, * or / : / Enter two operators: 34 3 num2/num1=11.33 Notice break statement at the end of each case, which cause switch...case statement to exit. If break statement is not used, all statements below that case statement are also executed. GOTO: In C programming, goto statement is used for altering the normal sequence of program execution by transferring control to some other part of the program. Syntax of goto statement: goto label; ............. ............. ............. label: statement; In this syntax, label is an identifier. When, the control of program reaches to goto statement, the control of the program will jump to the label: and executes the code/s after it. Example of goto statement: /* C program to demonstrate the working of goto statement. It finds the average of the given numbers after a negative number is encountered or after the total count is reached*/ # include <stdio.h> void main(){ float num,average,sum; int i,n; printf("Maximum no. of inputs: "); scanf("%d",&n); for(i=1;i<=n;++i){ printf("Enter n%d: ",i); scanf("%f",&num); if(num<0.0) goto jump; /* control of the program jumps to label jump */ sum=sum+num; } jump: average=sum/(i-1); printf("Average: %.2f",average);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

15

} Output: Maximum no. of inputs: 4 Enter n1: 1.5 Enter n2: 12.5 Enter n3: 7.2 Enter n4: -1 Average: 7.07

2. CONTROL STATEMENTS Explain the various control statements in C language with example in detail Nov/Dec 2014 Control statements enable us to specify the flow of program control; ie, the order in which the instructions in a program must be executed. They make it possible to make decisions, to perform tasks repeatedly or to jump from one section of code to another. They are as follows: 1. Branching statements(Discussed above) 2. Iteration(or)Looping statements 3. Jump statements Iteration statements: Iteration statements are used to execute a particular set of instructions repeatedly until a particular condition is met or for a fixed number of iterations. THE FOR STATEMENT: The for statement or the for loop repeatedly executes the set of instructions that comprise the body of the for loop until a particular condition is satisfied. Syntax: for(initialization; termination; increment/decrement) { //statements to be executed } The for loop consists of three expressions: The initialization expression, which initializes the looping index. The looping index controls the looping action. The initialization expression is executed only once, when the loop begins. The termination expression, which represents a condition that must be true for the loop to continue execution.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

16

The increment/decrement expression is executed after every iteration to update the value of the looping index. The following program uses the for loop to print the Fibonacci series: 0,1,1,2,3,5,8,13 … to n

terms. #include<stdio.h> int main() { int i,n, a, b, sum=0; printf("Enter the number of terms:"); scanf("%d",&n); a=0; b=1; printf("%d %d",a,b); for(i=2;i<n;i++) { sum=a+b; printf(" %d",sum); a=b; b=sum; } return 0; } Output: Enter the number of terms: 5 0 1 1 2 3 The while statement: The while statement executes a block of statements repeatedly while a particular condition is true. while (condition) { //statement(s) to be executed } The statements are executed repeatedly until the condition is true. Example: Program to calculate the sum of the digits of a number (eg, 456; 4+5+6 = 15) #include<stdio.h> int main() {

int n, a,sum=0; printf("\n Enter a number:"); scanf("%d", &n);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

17

while(n>0) {

a=n%10; //extract the digits of the number sum=sum+a; //sum the digits n=n/10; //calculate the quotient of a number when divided by 10.

} printf("\n Sum of the digits=\t %d",sum); return 0;

} Output: Enter a number 123 Sum of the digits= 6 The above program uses the while loop to calculate the sum of the digits of a number. The do-while loop: The do-while statement evaluates the condition at the end of the loop after executing the block of statements at least once. If the condition is true the loop continues, else it terminates after the first iteration. Syntax: do { //statements to be executed; } while(condition); Note the semicolon which ends the do-while statement. The difference between while and do while is that the while loop is an entry-controlled loop — it tests the condition at the beginning of the loop and will not execute even once if the condition is false, whereas the do-while loop is an exit-controlled loop — it tests the condition at the end of the loop after completing the first iteration. Most programs that work with while can also be implemented using do-while. The following program calculates the sum of digits in the same manner, except that it uses the do-while loop: #include<stdio.h> int main() { int n, a,sum=0;

printf("n Enter a number:");

www.Vidyarthiplus.com

www.Vidyarthiplus.com

18

scanf("%d", &n); do {

a=n%10; sum=sum+a; n=n/10;

}while(n>0); printf("n Sum of the digits=t %d",sum); return 0;

} Output: Enter a number 123 Sum of the digits = 6 However, the do-while statement should be used only in situations where the loop must execute atleast once whether or not the condition is true.A practical use of the do-while loop is in an interactive menu-driven program where the menu is presented at least once, and then depending upon the choice of the user, the menu is displayed again or the session is terminated. Jump statements: Break statement: The syntax of break statement is break; The break statement can appear only inside or as a body of a switch statement or a loop. A break statement terminates the execution of the nearest enclosing switch or the nearest enclosing loop. The execution resumes with the statement present next to the terminated switch statement or the terminated loop. Example 1: #include<stdio.h> main() { int i; for(i=1;i<=10;i++) { if(i==5) break; printf(―%d ‖,i); }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

19

if(i<11) printf(―\nPremature termination\n‖); } Output: 1 2 3 4 Premature termination Example 2: /* Program to check whether the no is prime or not*/ #include<stdio.h> main() { int n,i; printf(―Enter the number\n‖); scanf(―%d‖,&n); for(i=2;i<n;i++) { if(n%i==0)/*check if divisible by any no represented by i*/ break; } if(i==n)

printf(―Number is prime\n‖); else printf(―Number is not prime\n‖); } Output: Enter the number 9 Number is not prime Continue Statement: Syntax: The syntax of the continue statement is continue; A continue statement terminates the current iteration of the loop. On execution of the continue statement the program control is immediately transferred to the header of the loop. Example: /*Program to display the odd numbers from 1 to 10*/

www.Vidyarthiplus.com

www.Vidyarthiplus.com

20

#include<stdio.h> main() { int i; for(i=1;i<=10;i++) { if(i%2==0) continue; printf(―%d ―,i); } } Output: 1 3 5 7 9 For even numbers, the printf statement is ignored and therefore odd numbers are only displayed.

3. TYPES OF FUNCTIONS

a. What are functions? Explain the different types of functions with examples A function is a self contained program segment that carries out some specific, well defined task. A function takes some data from main () and returns a value.There are two types of function. They are: · Library function: Library functions are the in-built function in C programming system. For example:

printf() · User defined function: C allows programmer to define their own function according to their requirement. These types of functions are known as user-defined functions. For example: sum(). Elements of user defined function: In order to write an efficient user defined function,the programmer must be familiar the following three elements: Function Declaration: Like the normal variable the function must be declared before it is defined and called or invoked. Syntax : return_type function_name(arg1, arg2,..........)

www.Vidyarthiplus.com

www.Vidyarthiplus.com

21

Example : int add(int x, int y); OR int add(int,int); b. Function Definition: It is the process of specifying and establishing the user defined function by specifying all its elements and characteristics. Syntax: return_type function_name(arg1,arg2............) { Local variable declaration ___________ Body of the function ___________ Return(expr); } Example: int add(int a,int b) { int c; c=a+b; return(c); } Function Call: The function can be simply called by specifying the name of the function,return value and parameters if present. Syntax: function_name(); OR function_name(arg1,arg2..............) OR return_value=function_name(arg1,arg2..............); Example: add(); OR add(x,y); OR z=add(x,y); Every C program begins from main() and program starts executing the codes inside main() function. When the control of program reaches to function_name() inside main()function.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

22

The control of the program jumps to void function_name() and executes the codes inside it. When all the codes inside that user-defined function are executed, control of the program jumps to the statement just after function_name() from where it is called as given below:

Program: #include<stdio.h> #include<conio.h> void main() {

int c,a,b; int add(int,int); clrscr(); printf("Enter the values of a and b to perform addition:"); scanf("%d%d",&a,&b); c=add(a,b); printf("The sum is %d",c); getch();

} int add(int a1, int b1) {

return(a1+b1); } Output: Enter the values of a and b to perform addition: 2 3 The sum is 5 The user defined functions can be broadly classified into four types as below:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

23

a. Function without arguments and without return type In this prototype no data transfer takes place between the calling function and called function i.e. the called program does not receive any data from the calling program and does not send back any value to the calling program. The main function does not have control over the way they receive the input data

Program: #include<stdio.h> #include<conio.h> void main() {

void add(); clrscr(); add(); getch();

} void add() {

int a,b,c; printf("Enter the values of a and b"); scanf("%d%d",&a,&b); c=a+b; printf("The addition of %d and %d is %d", a,b,c);

} Output: Enter the values of a and b 2 3 The addition of 2 and 3 is 5 b. Function with argument and without return type: In this prototype data is transferred from calling function to called function i.e. the called program receives some data from the calling program and does not send back any value to the calling program. Such functions are partly dependent on the calling function.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

24

Program: #include<stdio.h> #include<conio.h> void main() { void add(int,int); int a,b; clrscr(); printf("Enter the values of a and b"); scanf("%d%d",&a,&b); add(a,b); getch(); } void add(int a1,int b1) { int c; c=a1+b1; printf("The addition of %d and %d is %d", a1,b1,c); } Output: Enter the values of a and b 2 3 The addition of 2 and 3 is 5 c. Function with argument and with return type: In this prototype data is transferred from calling function and called function i.e. the called program receives some data from the calling program and send back a value to the calling program.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

25

Program: #include<stdio.h> #include<conio.h> void main() { int add(int,int); int a,b,c; clrscr(); printf("Enter the values of a and b"); scanf("%d%d",&a,&b); c=add(a,b); printf("The addition of %d and %d is %d",a,b,c); getch(); } int add(int a1,int b1) { return(a1+b1); } Output: Enter the values of a and b 2 3 The addition of 2 and 3 is 5 d. Function without argument and with return type: In this prototype the calling program cannot pass any argument to the called program but the called program may send some return value to the calling program.

Program: #include<stdio.h> #include<conio.h> void main()

www.Vidyarthiplus.com

www.Vidyarthiplus.com

26

{ int add(); int c; clrscr(); c=add(); printf("The sum of is %d",c); getch(); } Output: Enter the values of a and b 2 3 The sum is 5 b. Write a function, which will take an array as an argument along with another argument size and based on the passed arguments, it will return average of the numbers passed through the array. Nov/Dec 2015 #include<stdio.h> float average(float a[],int n); void main() { float a[10],avg; int n,i; printf(―Enter the no of values\n‖); scanf(―%d‖,&n); printf(―Enter the values\n‖); for(i=0;i<n;i++) scanf(―%d‖,&a[i]); avg=average(a,n); printf(―The average is:\n %f‖,avg); } float average(float a[],int n) { int i; float sum=0,avg; for(i=0;i<n;i++) sum=sum+a[i]; avg=sum/n; return avg; } Enter the no of values 3 Enter the values 12.5 13.2

www.Vidyarthiplus.com

www.Vidyarthiplus.com

27

11.6 The average is: 12.4333

4. FUNCTIONS(POINTERS AND VARIABLE ARGUMENTS)

Briefly discuss about: Nov/Dec 2014 i. Function with variable number of arguments Sometimes, we may come across a situation, when we want to have a function, which can take variable number of arguments, i.e., parameters, instead of predefined number of parameters. The C programming language provides a solution for this situation and we are allowed to define a function which can accept variable number of parameters based on your requirement. The following example shows the definition of such a function. int func(int, ... ) { . . . } int main() { func(2, 2, 3); func(3, 2, 3, 4); } It should be noted that function func() has last argument as ellipses i.e. three dotes (...) and the one just before the ellipses is always an int which will represent total number variable arguments passed. To use such functionality you need to make use of stdarg.h header file which provides functions and macros to implement the functionality of variable arguments and follow the following steps: Define a function with last parameter as ellipses and the one just before the ellipses is always an int which will represent number of arguments.

Create a va_list type variable in the function definition. This type is defined in stdarg.h header file. Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file. Use va_arg macro and va_list variable to access each item in argument list. Use a macro va_end to clean up the memory assigned to va_list variable. Now let us follow the above steps and write down a simple function which can take variable

www.Vidyarthiplus.com

www.Vidyarthiplus.com

28

number of parameters and returns their average: #include <stdio.h> #include <stdarg.h> double average(int num,...) { va_list valist; double sum = 0.0; int i; /* initialize valist for num number of arguments */ va_start(valist, num); /* access all the arguments assigned to valist */ for (i = 0; i < num; i++) { sum += va_arg(valist, int); } /* clean memory reserved for valist */ va_end(valist); return sum/num; } int main() { printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5)); printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15)); } When the above code is compiled and executed, it produces the following result. Average of 2, 3, 4, 5 = 3.5 Average of 5, 10, 15 = 10 It should be noted that the function average() has been called twice and each time first argument represents the total number of variable arguments being passed. Only ellipses will be used to pass variable number of arguments. ii. Function pointers (or) Pointers to Functions: Nov/Dec 2015 Functions like all other identifiers do have a type. Function type is one of the derived data types. It contains return type of the function and types of its parameters. For example, type of a function mult that accepts one integer and one float argument snd returns a float value is float(int,float). It is possible to create a pointer to any type. Hence the creation of a pointer to a function type is also possible. A pointer to a function commonly known as function pointer is a variable that points to the starting address of the function.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

29

Declaration of function pointer: If fact is a function which accepts an integer and returns an integer value(factorial), the type of the function is int(int). A pointer to this function is declared as int(*ptr)(int); In the above declaration ptr is a pointer to a function that accepts an integer and returns an integer value. Assigning or Initializing a function pointer A pointer to a function type T can be assigned or initialized with the address of the function of type T or with a pointer of the same type. To assign or initialize a pointer it is enough to assign the function name to the pointe, which refers to the starting address of the function. For example, int add(int,int); When the above function is declared the following statements are allowed int(*atr)(int,int)=add; (or) int(*atr)(int,int); atr=add; Calling a function using function pointer A function pointer can be used to call a function in any one of the following two ways: 1. By explicitly dereferencing it using dereference operator 2. By using its name instead of function's name The following program illustrates the method of calling a function using function pointers #include<stdio.h> int add(int a,int b); main() { //Assigning address to pointers int (*ptr1)(int,int)=add; int (*ptr2)(int,int)=add; printf("Calling functions using function pointer\n"); (*ptr1)(1,3); ptr2(2,4); } int add(int a,int b) { printf("The result of addition is %d\n",a+b); } Output:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

30

Calling functions using function pointer The result of addition is 4 The result of addition is 6

Passing function to a function as an argument: A function can accept arguments of pointer type. Pointers can also be used to pass functions to a function. #include<stdio.h> int add(int,int); int sub(int,int); void f_calling_f(int,int,int(*)(int,int)); void main() { printf("Passing function to function\n"); f_calling_f(10,20,add); f_calling_f(10,20,sub); } void f_calling_f(int a,int b,int(*f)(int,int)) { fun(a,b); } int add(int a,int b) { printf("The result of addition of %d and %d is %d\n",a,b,a+b); } int sub(int a,int b) { printf("The result of subtraction of %d and %d is %d\n",a,b,a-b); }

5. ARRAYS

a. Write Short notes on array C programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

31

Declaring Arrays To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows: type arrayName [ arraySize ]; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement: double balance[10]; Now balance is a variable array which is sufficient to hold upto 10 double numbers. Initializing Arrays: We can initialize array in C either one by one or using a single statement as follows: double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write: double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0}; Following is the pictorial representation of the same array we discussed above:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

32

Accessing Array Elements: An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example: double salary = balance[9]; The above statement will take 10th element from the array and assign the value to salary variable. Following is an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays: #include <stdio.h> int main () { int n[ 10 ]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; /* set element at location i to i + 100 */ } /* output each array element's value */ for (j = 0; j < 10; j++ ) { printf("Element[%d] = %d\n", j, n[j] ); } return 0; } When the above code is compiled and executed, it produces the following result: Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 Two-dimensional array: The array which is used to represent and store data in two dimensions called two dimensional array. Declaration of 2-d array Syntax: <data type> <array name> [row size] [column size];

www.Vidyarthiplus.com

www.Vidyarthiplus.com

33

where <data type> refers to the type of the array variable. <array name> refers to the name of the array. [row size] refers to the number of rows in the array. [column size] refers to the number of columns in the array. Example: int a[3][3];

column 0 column 1 column 2 rows 0 a[0][0] a[0][1] a[0][2] rows 1 a[1][0] a[1][1] a[1][2] rows 2 a[2][0] a[2][1] a[2][2]

Initialization of 2-d array: Syntax: <data type> <array name> [row size] [column size]= {list of values }; Example: int a[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 } ; /* Program for declaring and initializing 2D array */ #include< stdio.h> #include<conio.h> void main() { int i,j; int a[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Declaring and initializing array clrscr( ); /* The above array can be initialized as shown below a[0][0]=1; a[1][0]=4; a[2][0]=7; a[0][1]=2; a[1][1]=5; a[2][1]=8; a[0][2]=3; a[1][2]=6; a[2][2]=9; */ printf(― The array elements are ―); for ( i=0; i<2; i++) { for ( j=0; j<2; i++) { printf ( ―%d\n‖ , a[i][j] ); } getch( ); } b. Write a C program to find the unique elements in an array using function unique. The function takes the array as a parameter and prints the unique elements. Nov/Dec 2014 #include<stdio.h> #include<conio.h> void printunique(int[],int); void main() { int array[100], size, i, j;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

34

printf("Enter number of elements in array\n"); scanf("%d", &size); printf("Enter %d numbers\n", size); for(i = 0; i < size; i++) { scanf("%d", &array[i]); } printunique(array,size); } void printunique(int a[],int n) { int i,j; printf("Unique Elements\n"); for(i = 0; i < n; i++) { for (j=0; j<i; j++) { if (a[i] == a[j]) break; } if (i == j) { /* No duplicate element found between index 0 to i */ printf("%d ", a[i]); } } Program Output Enter number of elements in array 10 Enter 10 numbers 1 2 8 5 2 3 8 4 1 6 Unique Elements 1 2 8 5 3 4 6 iii. Write a C program to find sum of two matrix of order 2*2 using arrays. Get the elements of matrix from the user. Nov/Dec 2015 #include<stdio.h> main() { int a[2[2],b[2][2],c[2][2],i,j; printf(―Enter the elements of the first matrix\n‖);//Get the first matrix for(i=0;i<2;i++)

www.Vidyarthiplus.com

www.Vidyarthiplus.com

35

{ for(j=0;j<2;j++) { scanf(―%d‖,&a[i][j]); } } printf(―Enter the elements of the second matrix\n‖);//Get the second matrix for(i=0;i<2;i++) { for(j=0;j<2;j++) { scanf(―%d‖,&b[i][j]); } } printf(―The resultant matrix after addition is:\n‖);//Addition of two matrices for(i=0;i<2;i++) { for(j=0;j<2;j++) { c[i][j]=a[i][j]+b[i][j]; printf(―%d\t‖,c[i][j]); } printf(―\n‖); } }

6. PREPROCESSOR OPERATORS

Explain the C preprocessor operators each with a neat example that is used to create macros April/May 2015 The C Preprocessor is not part of the compiler, but is a separate step in the compilation process. In simplistic terms, a C Preprocessor is just a text substitution tool and they instruct compiler to do required pre-processing before actual compilation. The important points for writing preprocessor directives are as follows: All preprocessor commands begin with a pound symbol (#). It must be the first nonblank character.

A new line character ends the pre-processor directive. Preprocessor directives can appear anywhere in a program but are generally placed at the beginning of a program.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

36

The pre-processor operates under the following pre-processor directives: a. File inclusion File inclusion directive tells the preprocessor to replace the directive with the content of the file specified in the directive. It is used to include the header files which contains the prototypes of the library functions and the definitions of the predefined constants.. #include<filename>: It searches the prespecified list of directories for the source file and text embeds the entire content of the source file in place of itself. #include ―filename‖ : It searches the file in the current working directory. If the search fails it is taken as #include<filename>. If it still fails, it will show the error. b. Macro substitution A macro is a facility provided by the C preprocessor by which a token can be replaced by the user-defined sequence of characters. Macros are defined with the help of the define directive. The identifier name immediately following the define directive is called the macro name. Types of Macros: Object like Macros: It is also known as symbolic constant. It is defined as #define macro-name replacement list The define directive causes the macro name to be replaced by the list. Example: #include<stdio.h> #define PI 3.14 main() { int r=5; printf(―Area of the circle is %f\n‖,PI*r*r); } Output: Area of the circle is 78.5 Function like Macros:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

37

A macro with arguments is called a function- like macro. It is used as #define macroname(parameter list) replacement list During pre-processing stage the macro names are expanded and are replaced by their replacement lists. This is called macro expansion. Example: #include<stdio.h> #define SQR(x) ((x)*(x)) main() { int side=5; printf(―Areaof the square is %d\n‖,SQR(side)); } Output: Area of the square is 25 c. Conditional compilation: Conditional Compilation means that a part of a program is compiled only if a certain condition comes out to be true. The available directives are as follows: i. #if: Tests if the compile time condition is true. #if<const_expr> <stmt_seq1> #endif ii. #if and #else: #if<constant_expr> <stmt_seq1> #else <stmt_seq2> #endif iii. #if...#elif...#else: #if<constant_expr> <stmt_seq1> #elif<constant_expr> <stmt_seq2> ....... #endif iv. #ifdef and #ifndef: #ifdef: Returns true if this macro is defined #ifndef: Returns true if this macro is not defined Example:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

38

#ifndef MESSAGE #define MESSAGE "You Wish!" #endif This tells the CPP to define MESSAGE only if MESSAGE isn't already defined. Predefined Macros in C language: Macro Description: __DATE__ The current date as a character literal in "MMM DD YYYY" format __TIME__ The current time as a character literal in "HH:MM:SS" format __FILE__ This contains the current filename as a string literal. __LINE__ This contains the current line number as a decimal constant. __STDC__ Defined as 1 when the compiler complies with the ANSI standard. Example: #include <stdio.h> main() { printf("File :%s\n", __FILE__ ); printf("Date :%s\n", __DATE__ ); printf("Time :%s\n", __TIME__ ); printf("Line :%d\n", __LINE__ ); printf("ANSI :%d\n", __STDC__ ); } When the above code in a file test.c is compiled and executed, it produces the following result: File :test.c Date :Jun 2 2012 Time :03:36:24 Line :8 ANSI :1

7. C PROGRAMS a. Write a C program to find all the roots of a quadratic equation April/May 2015 #include <stdio.h> #include <math.h> /* This is needed to use sqrt() function.*/ int main() { float a, b, c, determinant, r1,r2, real, imag; printf("Enter coefficients a, b and c: "); scanf("%f%f%f",&a,&b,&c);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

39

determinant=b*b-4*a*c; if (determinant>0) { r1= (-b+sqrt(determinant))/(2*a); r2= (-b-sqrt(determinant))/(2*a); printf("Roots are: %.2f and %.2f",r1 , r2); } else if (determinant==0) { r1 = r2 = -b/(2*a); printf("Roots are: %.2f and %.2f", r1, r2); } else { real= -b/(2*a); imag = sqrt(-determinant)/(2*a); printf("Roots are: %.2f+%.2fi and %.2f-%.2fi", real, imag, real, imag); } return 0; } Output 1: Enter coefficients a, b and c: 2.3 4 5.6 Roots are: -0.87+1.30i and -0.87-1.30i Output 2: Enter coefficients a, b and c: 4 1 0 Roots are: 0.00 and -0.25 b. Write a C program to print fibonacci numbers May/June 2014 #include <stdio.h> int main() { int count, n, t1=0, t2=1, display=0; printf("Enter number of terms: "); scanf("%d",&n); printf("Fibonacci Series: %d %d", t1, t2); /* Displaying first two terms */ count=2; /* count=2 because first two terms are already displayed. */ while (count<n) { display=t1+t2;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

40

t1=t2; t2=display; ++count; printf("%d ",display); } return 0; } Output:

Enter number of terms: 10 Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 c. Write a function that returns a pointer to the maximum value of an array of double's. If the array is empty, return NULL. April/May 2015 #include <stdio.h> int find_maximum(double[], int); int main() { int c, size, location, maximum; double array[100]; double *p; printf("Input number of elements in array\n"); scanf("%d", &size); printf("Enter %d double values\n", size); for (c = 0; c < size; c++) scan("lf", &array[c]); p = find_maximum(array, size); if(p==NULL) { printf("The array is empty\n"); } else { printf("The maximum element is %lf present in address %u\n",*p,p); } return 0; } double* find_maximum(double a[], int n) { int c,index; double max = a[0]; if(n==0) return NULL;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

41

for (c = 1; c < n; c++) { if (a[c] > max) { max = a[c]; index=c; } } return &a[index]; } Output: Input number of elements in array 5 Enter 5 double values 20.3 32.5 43.7 32.7 65.3 The maximum element is 65.3 present in address d. Write a C program using function to check whether the given no is palindrome or not April/May 2015 /* C program to check whether a number is palindrome or not */ #include <stdio.h> void checkpalin(int); void main() { int n; printf("Enter an integer: "); scanf("%d",&n); temp=n; while(temp!=0) { rem=temp%10; reverse=reverse*10+rem; temp/=10; } /* Checking if number entered by user and it's reverse number is equal. */ if(reverse==n) printf("%d is a palindrome.",n); else printf("%d is not a palindrome.",n); }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

42

void checkpalin(int n) { int temp=n,rem,reverse; while(temp!=0) { rem=temp%10; reverse=reverse*10+rem; temp/=10; } /* Checking if number entered by user and it's reverse number is equal. */ if(reverse==n) printf("%d is a palindrome.",n); else printf("%d is not a palindrome.",n); } Enter an integer: 12321 12321 is a palindrome. e. Write a C program to multiply two matrices that are represented as pointers. Use a function pointer to the function 'Multiply' which takes the two matrices as parameter and prints the result of the multiplication. May/June 2014 #include<stdio.h> void multiply(int a[10][10],int b[10][10],int r1,int c1,int r2,int c2) { int c[10][10],i,j,k; printf(―The elements of the resultant matrix is\n‖); for(i=0;i<r1;i++) { for(j=0;j<c2;j++) { c[i][j]=0; for(k=0;k<r2;k++) { c[i][j]+=a[i][k]*b[k][j]; printf(―%d\t‖,c[i][j]); } printf(―\n‖); } } } void main() { int a[10][10],b[10][10],r1,c1,r2,c2,i,j; int (*p)(int [][10],int[][10],int,int,int,int)=multiply;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

43

printf(―Enter the no. of rows and columns of first matrix\n‖); scanf(―%d %d‖,&r1,&c1);

printf(―Enter the no. of rows and columns of second matrix\n‖); scanf(―%d %d‖,&r2,&c2); printf(―Enter the elements of the first matrix\n‖); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) { scanf(―%d‖,&a[i][j]); } } printf(―Enter the elements of the second matrix\n‖); for(i=0;i<r2;i++) { for(j=0;j<c2;j++) { scanf(―%d‖,&b[i][j]); } } (*p)(a,b,r1,c1,r2,c2); } Output: Enter the no. of rows and columns of first matrix 2 2 Enter the no. of rows and columns of second matrix 2 3 Enter the elements of the first matrix 1 1 1 1 Enter the elements of the second matrix 2 2 2 2 2 2 The elements of the resultant matrix is 6 6 6 6 6 6 6 6 6

www.Vidyarthiplus.com

www.Vidyarthiplus.com

44

UNIT-II C PROGRAMMING ADVANCED FEATURES

PART-A 1. Compare arrays and structures. Arrays Structures An array is a collection of data items of same data type.

A structure is a collection of data items of different data types.

Arrays can only be declared. Structures can be declared and defined. There is no keyword for arrays. The keyword for structures is struct An array name represents the address of the starting element.

A structure name is known as tag.

int a[10]; struct student { int rno; char name[20]; };

2. Compare structures and unions. May/June2014,Nov/Dec 2014,Nov/Dec 2015 Structure Union Every member has its own memory. All members use the same memory. Memory

is allocated for the no of bytes occupied by the largest member.

The keyword used is struct. The keyword used is union. All members occupy separate memory location.

Different interpretations for the same memory are possible.

Consumes more space compared to union. Conservation of memory is possible struct student { int rno; char name[20]; };---Memory is allocated for rno and name

union student { int rno; char name[20]; };--Memory is allocated for 20 bytes alone.

3. Define Structure in C. A structure contains one or more data items of different data type in which the individual elements can differ in type. A simple structure may contain the integer elements, float elements and character elements etc. and the individual elements are called members.

Structures and Unions - File handling concepts – File read – write – binary and Stdio - File Manipulations

www.Vidyarthiplus.com

www.Vidyarthiplus.com

45

Example: struct result { int marks; float avg; char grade; }std; 4. Define union? Nov/Dec 2014 A union, is a collection of variables of different types, just like structure. Union is a derived data type and the difference between union and structure is in terms of storage. In structure each member has its own storage location, whereas all the members of union use the same memory location. Memory is conserved in the case of union. Example: union result { int marks; float avg; char grade; }std; 5. Will the following declaration work. Justify your answer. May/June 2014 struct student { int rollno=12; float marks[]={55,60,56}; char gender; }; It will not work as the memory allocation will not be done during definition, initialization of data members is not possible. 6. Define file? A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characters, words, lines, paragraph and pages from a textual document. Example: FILE *infile; FILE *outfile; 7. Define binary files? A file stored in binary format is called a binary file. A binary file is computer -readable but not human-readable. All executable programs are stored in binary files. In contrast, text files are stored in a form (usually ASCII) that is human-readable. Binary files can be processed sequentially or, depending on the needs of the application, they can process using random access techniques. In C, processing a file using random access techniques involves moving the current file position to an appropriate place in the file before reading or writing data.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

46

8. Define opening a file? A file requires to be opened first with the file pointer positioned on the first character. No input-output functions on a stream can be performed unless it is opened. When a stream is opened, it is connected to named device or file. C provides various functions to open a file as a stream. Syntax: FILE *fopen(char * filename, char *mode); 9. Define fseek()? fseek() will position the file pointer to a particular byte within the file. The file pointer is a parameter maintained by the operating system and determines where the next read will come from or to where the next write will go. int fseek(FILE *fp, long int offset, int whence)

fp − This is the pointer to a FILE object that identifies the stream. offset − This is the number of bytes to offset from whence. Whence − This is the position from where offset is added (SEEK_SET,SEEK_CUR,SEEK_END)

10. What are the ways to detecting End of File? In Text file: Special character EOF denotes the end of file. As soon as character is read, end of the file can be detected. EOF is defined in stdio.h. Equivalent value of EOF is -1 In binary file: feof function is used to detect the end of file it can also be used in text file. 11. What are key functions required to process a file? fopen - create a new file or open a existing file fclose - close a file fscanf - formatted file read fprintf - formatted file write fread - unformatted file read fwrite - unformatted file write getc()-reads a character from a file putc()-writes a character to file 12. Explain the syntax given below Nov/Dec 2014,April/May 2015 fread(&my-record,sizeof(struct rec),1,ptr_myfile); (or) Write the syntax of fread() and define its usage The above statement is used to read one structure rec variable from the file pointed by ptr_myfile and store it in my-record.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

47

13. What is the functions used to move the file pointer to the beginning of the file and to know the current position of the file pointer? rewind(fp); - Move the pointer fp to the beginning of the file ftell(fp): - Tells the current position of the file pointer fp 14. What are the statement used for reading a file?. Write a simple program to read the numbers from a file and display numbers. Nov/Dec 2014/Nov/Dec 2015 fscanf(fp,format specifier,arguments); fp - File pointer referring to the file from which the content is read. Program: #include<stdio.h> void main() { int n; FILE *fp; fp=fopen(―Input.txt‖,‖r‖); while(!feof(fp)) {

fscanf(fp,‖%d‖,&n); printf(―%d\n‖,n); } } 15. What is the difference between getc() and getchar()? Explain. April/May 2015 The difference between getchar()and getc(FILE *stream)is that, getc can read input from any stream, while getchar can only read from the standard input. Thus you can say that getchar()= getc(stdin).

PART-B

1. STRUCTURES Explain the concept of structures with example. Nov/Dec 2014 Structures: A structure is a collection of variables under a single name and provides a convenient way of grouping several pieces of related information together. Unlike arrays, it can be used for the storage of heterogenous data. There are three aspects of working with structures: 1. Defining a structure type, i.e., creating a new data type 2. Declaring variables of the new data type

www.Vidyarthiplus.com

www.Vidyarthiplus.com

48

3. Using and performing operations on the objects of the structure type. 1. Defining a structure: Syntax: struct tag_name { type member_name1; type member_name2; ….. }variable name; A structure definition consists of keyword struct followed by an identifier known as tag-name and structure declaration list enclosed within the braces. The newly created type is visible, after its definition, only in the scope in which it is defined. Structure declaration list consists of declarations of one or more variables of different types known as structure members or fields. Example: struct book { char title[25]; char author[20]; int pages; float price; }; Two different structure types may contain members of the same name without any conflict. Structure definition does not reserve any space in the memory. It is not possible to initialize the members during definition. Declaring Structure Objects: Variables can be declared either at the time of structure definition or after the structure definition. Syntax: struct tag-name identifier_name={initialization list}; Example: struct book { char title[25]; char author[20];

www.Vidyarthiplus.com

www.Vidyarthiplus.com

49

int pages; float price; }b1,b2; (or) struct book { char title[25]; char author[20]; int pages; float price; }; struct book b1,b2; b1 and b2 are declared as structure variables. The members of a structure object can be initialized using initialization list. The order of initializers must match the order of structure members in the structure definition. struct book b={"ABC","XYZ",200,320.50}; Operations on structures: Operations are classified into two categories: 1. Aggregate Operations: It treats an operand as an entity and operates on the entire operand as a whole instead of operating on its constituent members. The four aggregate operations are

i. Accessing members: Direct member access operator(dot operator) Syntax: structure_object_name.structure_member_name The members can be accessed by using dot operator along with variable name like b1. title to refer to the title of the variable book b1.

ii. Assigning a structure object to a structure variable A structure variable can be assigned with or initialized with a structure object. The assignment operator assigns values of all the members of the object on its right side to the corresponding members of the structure variable on the left side.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

50

#include<stdio.h> struct book { char title[25]; char author[20]; int price; }; main() { struct book b1={"ABC","XYZ",200}; struct book b2=b1;//b1 members are copied one by one to b2. } 2. Segregate operations: Operations on individual members can be performed as like normal objects as shown in the following example. The given example is to create two book structure variables and increase the number of pages and price accordingly. struct book { char title[25]; char author[20]; int pages; float price; }; main() { struct book b1,b2; printf(―Enter the title,author,pages and price of book1\n‖); gets(b1.title); gets(b1.author); scanf(―%d %f‖,&b1.pages,&b1.price); printf(―Enter the title,author,pages and price of book2\n‖); gets(b2.title); gets(b2.author); scanf(―%d %f‖,&b2.pages,&b2.price); printf(―Pages are increased by 100\n‖); printf(―Cost is increased by 10 %\n‖); b1.pages+=100; b2.pages+=100; b1.price+=110/100*b1.price; b2.price+=110/100*b2.price; printf(―Book1 has %d pages\n‖,b1.pages); printf(―Book1 price is %f \n‖,b1.price); printf(―Book2 has %d pages\n‖,b2.pages);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

51

printf(―Book2 price is %f \n‖,b2.price); } Array of structures: It is possible to create an array whose elements are of structure type. Such an array is known as array of structures. For example, to store the information about several books array of structures is a convenient way. struct book b[100]; Here an array of 100 book variables is created. Memory is allocated for each of the variable‘s

data members. Title Author Pages Price

b[0] b[1] . . .

b[99] Example: To create an array of student objects and calculate the marks, the following code is written #include <stdio.h> struct student{ char name[50]; int roll; float marks; }; int main(){ struct student s[10]; int i; printf("Enter information of students:\n"); for(i=0;i<10;++i) { s[i].roll=i+1; printf("\nFor roll number %d\n",s[i].roll); printf("Enter name: "); scanf("%s",s[i].name); printf("Enter marks: "); scanf("%f",&s[i].marks); printf("\n");

www.Vidyarthiplus.com

www.Vidyarthiplus.com

52

} printf("Displaying information of students:\n\n"); for(i=0;i<10;++i) { printf("\nInformation for roll number %d:\n",i+1); printf("Name: "); puts(s[i].name); printf("Marks: %.1f",s[i].marks); } return 0; } Output: Enter information of students: For roll number 1 Enter name: Tom Enter marks: 98 For roll number 2 Enter name: Jerry Enter marks: 89 . . . Displaying information of students: Information for roll number 1: Name: Tom Marks: 98 . . . Pointers to structures: The general form of declaring a pointer to structure is struct tag_name * identifier name The address of the structure variable is assigned to the pointer and the members can be accessed using indirect member access operator (->) also known as arrow operator. The members can also be accessed using dot operator as shown in the following example. Example: struct coord

www.Vidyarthiplus.com

www.Vidyarthiplus.com

53

{ int x,y; }; main() { struct coord pt={2,3}; struct coord *ptr=&pt;// Pointer is declared // Accessing of members through pointers printf(―Co-ordinates are (%d,%d)\n‖,(*ptr).x,(*ptr).y); printf(―Co-ordinates are (%d,%d)\n‖,ptr->x,ptr->y); } Output: Coordinates are (2,3) Coordinates are (2,3) Advantages:

1. It is easier to manipulate the pointer to structures than manipulating structures themselves. Passing a pointer to a structure as an argument to a function is efficient compared to passing a structure to a function as the size of the pointer is less than the actual variable.

2. Data structures use pointers to structures and particularly self-referential structures

which is a type of structure where it contains a pointer to an instance of itself. Example: struct node { int data; struct node *ptr; }; It refers to a node in data structure which contains a member as pointer to itself. Nested Structures: A structure can be nested within another structure. The member access operator is used to access the members of structure members. For example, name structure can be nested within phone book entry structure in any one of the following two ways. Example:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

54

struct name { char fname[20]; char lname[20]; }; struct pb_entry { struct name pname; char mobile_no[15]; }; Or struct pb_entry { struct name { char fname[20]; char lname[20]; }pname; char mobile_no[15]; }; /* The following code creates two phone book entries and displays the information*/ main() { struct pb_entry p1,p2; printf(―Enter the name of person1\n‖); /* Accessing the member of nested structure using dot operator*/

scanf(―%s%s‖, p1.pname.fname,p1.pname.lname); printf(―Enter the mobile no of person1\n‖); gets(p1.mobile_no);

printf(―Enter the name of person2\n‖); scanf(―%s%s‖, p2.pname.fname,p2.pname.lname); printf(―Enter the mobile no of person1\n‖); gets(p2.mobile_no); printf(―Phone book entries are…\n‖); printf(― %s %s \t %s\n‖,p1.pname.fname,p1.pname.lname,p1.mobile_no); printf(― %s %s \t %s\n‖,p2.pname.fname,p2.pname.lname,p2.mobile_no); } Output: Enter the name of the person1

www.Vidyarthiplus.com

www.Vidyarthiplus.com

55

Arun Kumar Enter the mobile no of person1 9898765656 Enter the name of the person2 Dilip Kumar Enter the mobile no of person2 9898888888 Phone book entries are… Arun Kumar 9898765656 Dilip Kumar 9898888888 Functions and Structures: It is possible to pass a structure object to and return a structure object from a function by value.

It can be done in 2 ways.

1. Passing structure to a function by value 2. Passing structure to a function by address(reference)

Example program – passing structure to function in C by value:

In this program, the whole structure is passed to another function by value. It means the whole structure is passed to another function with all members and their values. So, this structure can be accessed from called function. #include <stdio.h> #include <string.h> struct student { int id; char name[20]; float percentage; }; void func(struct student record); int main() { struct student record; record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; func(record);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

56

return 0; } void func(struct student record) { printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); } Output: Id is: 1 Name is: Raju Percentage is: 86.500000 Example program – Passing structure to function in C by address: In this program, the whole structure is passed to another function by address. It means only the address of the structure is passed to another function. The whole structure is not passed to another function with all members and their values. So, this structure can be accessed from called function by its address. #include <stdio.h> #include <string.h> struct student { int id; char name[20]; float percentage; }; void func(struct student *record); int main() { struct student record; record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; func(&record); return 0; }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

57

void func(struct student *record) { printf(" Id is: %d \n", record->id); printf(" Name is: %s \n", record->name); printf(" Percentage is: %f \n", record->percentage); } Id is: 1 Name is: Raju Percentage is: 86.500000

2. UNIONS

Explain the concept of Union with example. April/May 2015 Like structures, Unions are used to create the user defined data types. A union is a collection of one or more variables, possibly of different data types. In structures separate memory is allocated to each member while in unions, all the members of an object share the same memory. A union object is used only if one of its constituent members is to be used at a time. In such a situation it proves to be memory efficient when compared to structures. Defining union type: Union keyword is used to define a union type as follows union car{ char name[50]; int price; }; Declaring union object: Objects can be declared at the time of definition or after the definitionin a separate declaration statement. union tag_name variable_list; Example: Union car c1,c2,c3; - Three union variables are declared. Accessing members of union object: The members of a union variable are accessed using dot operator similar to structure variables. For example, c1.name and c1.price refers to the name and price of the car variable c1 respectively.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

58

Though unions are similar to structure in so many ways, the difference between them is crucial to understand. This can be demonstrated by this example: #include <stdio.h> union job { //defining a union char name[32]; float salary; int worker_no; }u; struct job1 { char name[32]; float salary; int worker_no; }s; int main(){ printf("size of union = %d",sizeof(u)); printf("\nsize of structure = %d", sizeof(s)); return 0; } Output: size of union = 32 size of structure = 40 There is difference in memory allocation between union and structure as suggested in above example. The amount of memory required to store a structure variables is the sum of memory size of all members.

But, the memory required to store a union variable is the memory required for largest element of an union.

Example for union: #include <stdio.h> union job { char name[32];

www.Vidyarthiplus.com

www.Vidyarthiplus.com

59

float salary; int worker_no; }u; int main(){ printf("Enter name:\n"); scanf("%s",&u.name); printf("Enter salary: \n"); scanf("%f",&u.salary); printf("Displaying\nName :%s\n",u.name); printf("Salary: %.1f",u.salary); return 0; } Output Enter name Hillary Enter salary 1234.23 Displaying Name: (Garbage value will be displayed) Salary: 1234.2 Initially, Hillary will be stored in u.name and other members of union will contain garbage value. But when user enters value of salary, 1234.23 will be stored in u.salary and other members will contain garbage value. Thus in output, salary is printed accurately but, name displays some random string. Since the members of a union object share the memory in an overlapped fashion, only one member at a time can be assigned a value. Accessing the value of that member gives a meaningful result, but accessing other members gives a garbage value. The following program uses structure and union to get and display the student details. #include<stdio.h> #include<conio.h> void main() { struct student { char name[30]; char sex; int rollno; float percentage; }; union details {

www.Vidyarthiplus.com

www.Vidyarthiplus.com

60

struct student st; }; union details set; printf("Enter details:"); printf("\nEnter name : "); scanf("%s", set.st.name); printf("\nEnter roll no : "); scanf("%d", &set.st.rollno); printf("\nEnter sex : "); scanf("%c", &set.st.sex); printf("\nEnter percentage :"); scanf("%f", &set.st.percentage); printf("\nThe student details are : \n"); printf("\name : %s", set.st.name); printf("\nRollno : %d", set.st.rollno); printf("\nSex : %c", set.st.sex); printf("\nPercentage : %f", set.st.percentage); getch(); } Output: Enter details: Enter name : Pritesh Enter rollno: 10 Enter sex: M Enter percentage: 89 The student details are: Name : Pritesh Rollno : 10 Sex : M Percentage : 89.000000

3. FILE MANIPULATION FUNCTIONS

Explain about file manipulations in detail with suitable program Nov/Dec2014 May/June/2014/Nov/Dec 2015 A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characters, words,

www.Vidyarthiplus.com

www.Vidyarthiplus.com

61

lines, paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from a graphical image. In C, the stream is a common, logical interface to the various devices that comprise the computer. In its most common form, a stream is a logical interface to a file. Essentially there are two kinds of files that programmers deal with text files and binary files. ASCII Text files: A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time. Similarly, since text files only process characters, they can only read or write data one character at a time. Binary files: A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a byte and a character are equivalent. Hence a binary file is also referred to as a character stream. Binary files can be either processed sequentially or, depending on the needs of the application they can be processed using random access techniques. In C Programming Language, processing a file using random access techniques involves moving the current file position to an appropriate place in the file before reading or writing data. File pointer:

A file pointer is a pointer to a structure, which contains information about the file, including its name, current position of the file, whether the file is being read or written, and whether errors or end of the file have occurred. The user does not need to Know the details, because the definitions obtained from stdio.h include a structure declaration called FILE. The only declaration needed for a file pointer is symbolized by

FILE *fp; This says that fp is the file pointer that points to a FILE structure. File operations: Opening Files: We can use the fopen( ) function to create a new file or to open an existing file, this call will initialize an object of the type FILE, which contains all the information necessary to control the stream. Following is the prototype of this function call:

FILE *fopen( const char * filename, const char * mode );

www.Vidyarthiplus.com

www.Vidyarthiplus.com

62

Here, filename is string literal, which you will use to name your file and access mode can have one of the following values: Mode Description r Opens an existing text file for reading purpose. w Opens a text file for writing, if it does not exist then a new file is created. Here our

program will start writing content from the beginning of the file. a Opens a text file for writing in appending mode, if it does not exist then a new file is

created. Here our program will start appending content in the existing file content. r+ Opens a text file for reading and writing both. w+ Opens a text file for reading and writing both. It first truncate the file to zero length if

it exists otherwise create the file if it does not exist. a+ Opens a text file for reading and writing both. It creates the file if it does not exist.

The reading will start from the beginning but writing can only be appended. If you are going to handle binary files then you will use below mentioned access modes instead of the above mentioned: "rb", "wb", "ab", "ab+", "a+b", "wb+", "w+b", "ab+", "a+b" Closing a File To close a file, use the fclose( ) function. The prototype of this function is:

int fclose( FILE *fp ); The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This function actually, flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h. Reading a File Following is the simplest function to read a single character from a file: int fgetc( FILE * fp ); The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error it returns EOF. The following functions allow you to read a string from a stream: char *fgets( char *buf, int n, FILE *fp );

www.Vidyarthiplus.com

www.Vidyarthiplus.com

63

The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string. If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including new line character. We can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file but it stops reading after the first space character encounters. It can also be used to read variables of different data types also. For example, fscanf(fp,"%d%c%s",&a,&b,c); - Used to read integer variable a, character variable b and string c. Writing a File Following is the simplest function to write individual characters to a stream: int fputc( int c, FILE *fp ); The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream: int fputs( const char *s, FILE *fp ); The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file. It can also be used to display variables of different data types also. fprintf(fp,"%d\t%c\t%s",a,b,c); - Used to display integer variable a, character variable b and string c. Example Programs for File operations: 1. Creating a file and output some data /* Program to create a file and write some data the file */ #include <stdio.h> #include <stdio.h> main( ) { FILE *fp;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

64

char stuff[25]; int index; fp = fopen("TENLINES.TXT","w"); /* open for writing */ strcpy(stuff,"This is an example line."); for (index = 1; index <= 10; index++) fprintf(fp,"%s Line number %d\n", stuff, index); fclose(fp); /* close the file before ending program */ } After the program is executed the following is written to the file TENLINES.TXT This is an example line Line number 1 This is an example line Line number 2 This is an example line Line number 3 This is an example line Line number 4 This is an example line Line number 5 This is an example line Line number 6 This is an example line Line number 7 This is an example line Line number 8 This is an example line Line number 9 This is an example line Line number 10 2. Reading: #include <stdio.h> void main() { FILE *fopen(), *fp; int c; fp = fopen("prog.c","r"); c = fgetc(fp) ; while (c!= EOF) { putchar(c); c = getc(fp); } fclose(fp); } File ―prog.c‖ is opened in read mode and the file is read character by character till EOF character and displayed in the screen. 3. Writing #include <stdio.h> int main()

www.Vidyarthiplus.com

www.Vidyarthiplus.com

65

{ FILE *fp; file = fopen("file.txt","w"); /*Create a file and add text*/ fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/ fclose(fp); /*done!*/ return 0; } file.txt contains the line ―This is just an example‖ after the program is executed. 3. Appending #include <stdio.h> int main() { FILE *fp file = fopen("file.txt","a"); fprintf(fp," %s","This is just an example :)"); /*append some text*/ fclose(fp); return 0; } file.txt before execution Hello file.txt after execution Hello This is just an example Binary I/O Functions: There are following two functions, which can be used for binary input and output: size_t fread(void *buffer, size_t size,size_t num, FILE *fp); The fread() function reads from the file associated with fp, num number of objects, each object size bytes long, into buffer pointed to by buffer. It returns the number of objects actually read. If this value is 0, no objects have been read, and either end of file has been encountered or an error has occurred. size_t fwrite(void *buffer, size_t size,size_t num, FILE *fp); The fwrite() function is the opposite of fread(). It writes to fil1 associated with fp, num number of objects, each object size bytes long, from the buffer pointed to by buffer. It returns the number of objects written. This value will be less than num only if an output error as occurred.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

66

int feof(FILE *fp);

The feof() function returns non-0 if the file associated with fp has reached the end of file, otherwise it returns 0. This function works for both binary files and text files.

int ferror(FILE *fp);

The ferror() function returns non-0 if the file associated with fp has experienced an error, otherwise it returns 0.

As a simple example, this program write an integer value to a file called MYFILE using its internal, binary representation.

#include stdio.h /* header file */ #include stdlib.h void main(void) {

FILE *fp; /* file pointer */ int i; /* open file for output */ if ((fp = fopen("myfile", "w"))==NULL){ printf("Cannot open file \n"); exit(1); } i=100; if (fwrite(&i, 2, 1, fp) !=1){ printf("Write error occurred"); exit(1); } fclose(fp); /* open file for input */ if ((fp =fopen("myfile", "r"))==NULL){ printf("Read error occurred"); exit(1); } fread(&i,2,1,fp); printf("i is %d",i); fclose(fp);

} Output: i is 100

www.Vidyarthiplus.com

www.Vidyarthiplus.com

67

Other functions:

rewind()

void rewind(FILE *fp);

We can position a file's current location to the start of the file using rewind().

The following example shows the usage of rewind() function.

#include <stdio.h> int main() { char str[] = "This is a C program"; FILE *fp; int ch; /* First let's write some content in the file */ fp = fopen( "file.txt" , "w" ); fwrite(str , 1 , sizeof(str) , fp ); fclose(fp); fp = fopen( "file.txt" , "r" ); while(!feof(fp))// Displays the contents in the file { ch = fgetc(fp); printf("%c", ch); } rewind(fp);//Rewinds the file pointer to the beginning printf("\n"); while(!feof(fp))//Displays again the contents of the file { ch = fgetc(fp); printf("%c", ch); } fclose(fp); return(0); }

Let us assume we have a text file file.txt that have the following content −

www.Vidyarthiplus.com

www.Vidyarthiplus.com

68

This is a C program

Now let us compile and run the above program to produce the following result −

This is a C program This is a C program

fseek()

int fseek(FILE *stream, long offset, int whence);

The fseek() function is used to set the file position indicator for the stream to a new position. This function accepts three arguments. The first argument is the FILE stream pointer returned by the fopen() function. The second argument ‗offset‘ tells the amount of bytes to seek. The third argument ‗whence‘ tells from where the seek of ‗offset‘ number of bytes is to be done.

The available values for whence are SEEK_SET, SEEK_CUR, or SEEK_END. These three values (in order) depict the start of the file, the current position and the end of the file.

Upon success, this function returns 0, otherwise it returns -1.

The following example shows the usage of fseek() function.

#include <stdio.h> int main () { FILE *fp; fp = fopen("file.txt","w+"); fputs("This is a program", fp); fseek( fp, 7, SEEK_SET ); fputs(" C Programming Language", fp); fclose(fp); return(0); }

Let us compile and run the above program that will create a file file.txt with the following content. Initially program creates the file and writes This is a C program but later we had reset the write pointer at 7th position from the beginning and used puts() statement which over-write the file with the following content C programming Language.

This is C Programming Language

www.Vidyarthiplus.com

www.Vidyarthiplus.com

69

ftell()

long int ftell(FILE *stream)

This function returns the current value of the position indicator. If an error occurs, -1L is returned, and the global variable errno is set to a positive value.

The following program demonstrates the use of ftell. It displays the total size of the file in bytes.

#include <stdio.h>

int main () { FILE *fp; int len; fp = fopen("file.txt", "r"); if( fp == NULL ) { perror ("Error opening file"); return(-1); } fseek(fp, 0, SEEK_END); len = ftell(fp); fclose(fp); printf("Total size of file.txt = %d bytes\n", len); return(0); }

Let us assume we have a text file file.txt, which has the following content −

This is a C program

Now let us compile and run the above program that will produce the following result if file has above mentioned content otherwise it will give different result based on the file content −

Total size of file.txt = 19 bytes

4. PROGRAMS IN STRUCTURES

a. Write a C program that uses functions to perform the following operations using structure i. Reading a complex number ii. Writing a complex number

www.Vidyarthiplus.com

www.Vidyarthiplus.com

70

iii. Addition of two complex numbers iv. Multiplication of two complex numbers May/June 2014/April/May 2015/Nov/Dec 2015 #include<stdio.h> #include<conio.h> struct complex { double r,i; }; void read(struct complex *); struct complex add(struct complex *,struct complex *); struct complex mul(struct complex *,struct complex *); struct complex div(struct complex *,struct complex *); void write(struct complex *); void main() { struct complex a,b,c,d,e; int opern; clrscr();

printf(―Enter first complex number\n‖); read(&a); printf(―Enter second complex number\n‖); read(&b); printf("\n\n \t\t\t***** MAIN MENU *****");

printf("\n\n Select your option: \n 1 : ADD\n 2 : MULTIPLY\n 3 : DIVIDE\n\n\t\t Enter your Option\n");

scanf("%d",&opern); switch(opern) { /*addition of complex number*/

case 1: c=add(&a,&b);

printf("Sum=%.1f+%.1fi",c.real,c.imag); break;

/*multiplication of complex number*/ case 2:

c=mul(&a,&b); printf("Product=%.1f+%.1fi",c.real,c.imag); break; /*Division of complex number*/ case 3: c=div(&a,&b);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

71

printf("Division Result=%.1f+%.1fi",c.real,c.imag); break; default: printf(―Wrong choice\n‖);

} } void read(struct complex *x) { printf("Enter Real Part : "); scanf("%d",&(x->r)); printf("Enter Imag Part : "); scanf("%d",&(x->i)); } struct complex add(struct complex *x,struct complex *y) { struct complex z; z.r=x->r+y->r; z.i=x->i+y->i; return(z); } struct complex mul(struct complex *x,struct complex *y) { struct complex z; z.r=(x->r)*(y->r)-(x->i)*(y->i); z.i=(x->r)*(y->i)+(x->i)*(y->r); return(z); } struct complex div(struct complex *x,struct complex *y) { struct complex z; z.r=((x->r)*(y->r)+(x->i)*(y->i))/((y->r)*(y->r)+(y->i)*(y->i)); z.i=((x->i)*(y->r)-(x->r)*(y->i))/ ((y->r)*(y->r)+(y->i)*(y->i)); return(z); } Output: Enter first complex number Enter Real Part : 10 Enter Imag Part : 12 Enter second complex number Enter Real Part : 13 Enter Imag Part : 32 ***** MAIN MENU *****

www.Vidyarthiplus.com

www.Vidyarthiplus.com

72

Select your option: 1 : ADD 2 : MULTIPLY 3 : DIVIDE Enter your Option 2 Product=-254+476i b. Write a program to perform the following operations for the customers of a bank using the concept of structures May/June 2014 i. Input the customer details like name, account number and balance ii. When a withdrawal transaction is made the balance must change to reflect it iii. When a deposit transaction is made the balance must change to reflect it. #include<stdio.h> #include<conio.h> void creation(); void deposit(); void withdraw(); void bal(); int a=0,i = 101; struct bank { int no; char name[20]; float bal; float dep; }s[20]; void main() { int ch; while(1) { clrscr(); printf("\n*********************"); printf("\n BANKING "); printf("\n*********************"); printf("\n1-Creation"); printf("\n2-Deposit"); printf("\n3-Withdraw");

www.Vidyarthiplus.com

www.Vidyarthiplus.com

73

printf("\n4-Balance Enquiry"); printf("\n5-Exit"); printf("\nEnter your choice"); scanf("%d",&ch); switch(ch) { case 1: creation(); break; case 2: deposit(); break; case 3: withdraw(); break; case 4: bal(); break; case 5: exit(0); default: printf("Enter 1-5 only"); getch(); } } } void creation() { printf("\n*************************************"); printf("\n ACCOUNT CREATION "); printf("\n*************************************"); printf("\nYour Account Number is :%d",i); s[a].no = i; printf("\nEnter your Name:"); scanf("%s",s[a].name); printf("\nYour Deposit is Minimum Rs.500"); s[a].dep=500; a++; i++; getch(); } void deposit() { int no,b=0,m=0; float aa; printf("\n*************************************"); printf("\n DEPOSIT "); printf("\n*************************************"); printf("\nEnter your Account Number");

www.Vidyarthiplus.com

www.Vidyarthiplus.com

74

scanf("%d",&no); for(b=0;b<i;b++) { if(s[b].no == no) m = b; } if(s[m].no == no) { printf("\n Account Number : %d",s[m].no); printf("\n Name : %s",s[m].name); printf("\n Deposit : %f",s[m].dep); printf("\n How Much Deposited Now:"); scanf("%f",&aa); s[m].dep+=aa; printf("\nDeposit Amount is :%f",s[m].dep); getch(); } else { printf("\nACCOUNT NUMBER IS INVALID"); getch(); } } void withdraw() { int no,b=0,m=0; float aa; printf("\n*************************************"); printf("\n WITHDRAW "); printf("\n*************************************"); printf("\nEnter your Account Number"); scanf("%d",&no); for(b=0;b<i;b++) { if(s[b].no == no) m = b; } if(s[m].no == no) { printf("\n Account Number : %d",s[m].no); printf("\n Name : %s",s[m].name); printf("\n Deposit : %f",s[m].dep); printf("\n How Much Withdraw Now:");

www.Vidyarthiplus.com

www.Vidyarthiplus.com

75

scanf("%f",&aa); if(s[m].dep<aa+500) { printf("\nCANNOT WITHDRAW YOUR ACCOUNT HAS MINIMUM BALANCE"); getch(); } else { s[m].dep-=aa; printf("\nThe Balance Amount is:%f",s[m].dep); } }

else {

printf("INVALID"); getch(); } getch(); } void bal() { int no,b=0,m=0; float aa; printf("\n*************************************"); printf("\n BALANCE ENQUIRY "); printf("\n*************************************"); printf("\nEnter your Account Number"); scanf("%d",&no); for(b=0;b<i;b++) { if(s[b].no == no) m = b; } if(s[m].no==no) { printf("\n Account Number : %d",s[m].no); printf("\n Name : %s",s[m].name); printf("\n Deposit : %f",s[m].dep); getch(); } else { printf("INVALID"); getch();

www.Vidyarthiplus.com

www.Vidyarthiplus.com

76

} } Output: ********************* BANKING ********************* 1-Creation 2-Deposit 3-Withdraw 4-Balance Enquiry 5-Exit Enter your choice 1 ************************************* ACCOUNT CREATION ************************************* Your Account Number is : 101 Enter your Name: Deepa Your Deposit is Minimum Rs.500 ********************* BANKING ********************* 1-Creation 2-Deposit 3-Withdraw 4-Balance Enquiry 5-Exit Enter your choice 2 ************************************* DEPOSIT ************************************* Enter your Account Number 101 Account Number : 101 Name : Deepa Deposit : 500 How Much Deposited Now: 4000 Deposit Amount is : 4500

www.Vidyarthiplus.com

www.Vidyarthiplus.com

77

********************* BANKING ********************* 1-Creation 2-Deposit 3-Withdraw 4-Balance Enquiry 5-Exit Enter your choice iii). Create a structure employee(data members- Name and Salary). Write a function using array of objects get 5 employee details and display them. Nov/Dec 2015 struct employee { char name[20]; float salary; }; //Read employee details void read_emp(struct employee e[]) { printf("Enter the employee details\n"); for(i=0;i<5;i++) { scanf("%s%f",e[i].name,&e[i].salary); } } //Display employee details void disp_emp(struct employee e[]) { printf("The employee details are as follows\n"); for(i=0;i<5;i++) { printf("Employee %d\n",i+1); printf("Name : %s \n",e[i].name); printf("Salary: %f\n",e[i].salary); } } void main() { struct employee e[5];// Array of employee objects are allocated read_emp(e); disp_emp(e); };

www.Vidyarthiplus.com

www.Vidyarthiplus.com

78

5. PROGRAMS IN FILE HANDLING a. Perform the following to manipulate file handling in C i. Define an input file handle called input_file, which is a pointer to type FILE ii. Using input_file, open the file results.dat for read mode. iii.Write C statements which tests to see if input_file has opened the data file successfully. If not, print an error message and exit the program. iv.Write C code which will read a line of characters (terminated by '\n') from input_file into a character array called buffer upon reading a \n. v. Close the file associated with input_file. April/May 2015 void main ( void ) { const char filename[] = "results.dat"; char line [ 128 ]; /* or other suitable maximum line size */\ //1. File handle is created FILE *input_file; //2. File is opened input_file= fopen (filename, "r"); int ch, loop = 0; char buffer[200]; //3. Check whether the file is opened if(input_file!=NULL) { //4. Read Characters till ‗\n‘ in buffer ch = fgetc( input_file ); while( (ch != '\n') && (ch != EOF) ) { buffer[loop] = ch; loop++; ch = fgetc( input_file ); } buffer[loop] = ‗\0‘; } else { Printf(―Error in File open operation\n‖); } //5. Close the file fclose(input_file); }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

79

b. Write a C program to read the contents of a file "in.txt" from first to last and write the contents to "out.txt". #include <stdio.h> void main() { FILE *fp,*fr; char ch; clrscr(); //in.txt is opened for reading and out.txt is opened for writing fp=fopen(―in.txt‖,‖r‖); fr=fopen(―out.txt‖,‖w‖); while(!feof(fp))//Counting the number of characters in the file { ch=fgetc(fp); fputc(ch,fr); } fclose(fp); fclose(fr); } c. Write a C program to read the contents of a file "in.txt" from last to first and write the contents to "out.txt". May/June 2014 #include <stdio.h> #include <math.h> #include <stdlib.h> #include <ctype.h> void main() { FILE *fp,*fr; char ch; int i=-1,j=0; clrscr(); //in.txt is opened for reading and out.txt is opened for writing fp=fopen(―in.txt‖,‖r‖); fr=fopen(―out.txt‖,‖w‖); while(!feof(fp))//Counting the number of characters in the file { ch=fgetc(fp); j++; } fseek(fp,i,SEEK_END); while(1) { /* Reading a character from input file and writing to output */

www.Vidyarthiplus.com

www.Vidyarthiplus.com

80

ch=fgetc(fp); fputc(ch,fr); i--; /*Move the file pointer one character before the current position*/ fseek(fp,i,SEEK_END); if(-i>j)// All the characters are read from the file break; } fclose(fp); fclose(fr); } d. Display the contents of a file on screen. April/May 2015 #include <stdio.h> #include <math.h> #include <stdlib.h> #include <ctype.h> void main() { FILE *fp,*fr; char ch; clrscr(); fp=fopen(―in.txt‖,‖r‖); /* Till the end of the file character is read and displayed*/ while(!feof(fp)) { ch=fgetc(fp); putc(ch,stdout); } fclose(fp); } e. Write a program to read a file and count the number of characters and lines in it Nov/Dec 2015 #include<stdio.h> #include<conio.h> void main() {

int noc=0,now=0,nol=0; FILE *fr; char fname[20],ch; clrscr();

www.Vidyarthiplus.com

www.Vidyarthiplus.com

81

printf("\n enter the source file name"); gets(fname); fr=fopen(fname,"r"); if(fr==NULL) { printf("\n error \n"); exit(0); } ch=fgetc(fr); while(ch!=EOF) { noc++; if(ch==' '); now++; if(ch=='\n') { nol++; now++; } ch=fgetc(fr); } fclose(fr); printf("\n total no of character=%d",noc); printf("\n total no of words=%d",now); printf("\n total no of lines=%d",nol); getch();

} Program displays the total number of characters,words and lines in a file.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

82

UNIT – III LINEAR DATA STRUCTURES – LIST

Abstract Data Types (ADTs) – List ADT – Array-based implementation – Linked list implementation –– Singly linked lists - Circularly linked lists- Doubly-linked lists – applications of lists – Polynomial Manipulation – All operation (Insertion, Deletion, Merge, Traversal)

PART A

1. What is an abstract data type? Nov/Dec 2006 , Nov/Dec 2014, May/June 2005 Nov / Dec 2011 Define ADT. Apr / May 2015 What is ADT? Give Example. Apr / May 2008, Nov / Dec 2015 Define Abstract Data type (ADT). May / June 2007 What is the advantage of ADT? May / June 2014 An Abstract Data Type (ADT) is defined as a mathematical model of the data objects that make up a data type as well as the functions that operate on these objects. The definition of ADT has the following two parts: (i) Description of the way in which components are related to each other. (ii)Statements of operations that can be performed on that data type. Example: Objects such as lists, sets and graphs. Logical behavior of ADT is defined by a set of values and a set of operations. Advantages: Robust Encapsulation Localization of change Flexibility 2. Define Data Structure. May / June 2007 A data structure is a mathematical or logical way of organizing data in the memory that consider not only the items stored but also the relationship to each other and also it is characterized by accessing functions. A Data Structure is a particular way of organizing data in a computer so that it can be used efficiently. Data structure is an implementation of one or more particular abstract data types (ADT). Eg. Stack, Queue. 3. What is a Circular Linked List? List its advantages. Nov / Dec 2014 A Circular linked list is a linked list in which the head element's previous pointer points to the tail element and the tail element's next pointer points to the head element. In a circularly linked list, all nodes are linked in a continuous circle, without using NULL. Next Next Next

Data Data Data

www.Vidyarthiplus.com

www.Vidyarthiplus.com

83

Advantages: It allows traversing the list starting at any point. It allows quick access to the first and last records. Circularly doubly linked list allows traversing the list in both directions. 4. Define a List. Mention any two operations that are performed on a list. Nov / Dec 2006 List the operations and implementations of List ADT. May / June 2006

List is a sequential data structure. A list or sequence is an abstract data type that represents an ordered sequence of values. List is a linear collection of data items. The general form of the list is A1, A2, A3,.....,AN where A1 - First element of the list, AN - Last element of the list, N - Size of the list. If the element at position i is Ai then its successor is Ai+1 and its predecessor is Ai-1.

Operations: Create a list Insert an element in the list Delete an element from the list Return the position of the element in the list Display the contents of the list Make the list empty. Implementations: Array implementation Linked list implementation Cursor based implementation 5. Should arrays or linked lists be used for the following types of applications? Justify your answer. May / June 2014 (a) Many search operations in sorted list - Array. It is a linear data structure and supports searching easily. (b) Many search operations in unsorted list.- Linked List. Pointer traversal so searching is easier. 6. What is a static and dynamic linked list? State any two applications of Linked list. Apr / May 2015 Static Linked List – data structure has a fixed size. Dynamic Linked List - data structure is dynamic. It grows and shrinks dynamically. Applications of linked list: Polynomial ADT Radix Sort Multilist Array

www.Vidyarthiplus.com

www.Vidyarthiplus.com

84

Stack Queue 7. Distinguish between linear and non-linear data structures. Nov / Dec 2010

Feature Linear Data Structure Non Linear Data

Structure

Organization of data

Data elements are not organized in a sequential fashion.

Data elements are not organized in a sequential fashion.

Construction

Data elements in a linear data structure are traversed one after the other

Nonlinear data structures are constructed by attaching a data element to several other data elements

Implementation Easy to implement Difficult to implement.

Examples arrays, linked lists, stacks and queues

Trees and Graphs

8. Write the syntax of calloc() and realloc() and mention its application in linked list. April/May 2015 calloc () function is used to allocate space in memory during the execution of the program. But calloc () initializes the allocated memory to zero.

calloc (number, sizeof(int)); realloc () function modifies the allocated memory size by malloc () and calloc () functions to new size.If enough space doesn‘t exist in memory of current block to extend, new block is

allocated for the full size of reallocation, then copies the existing data to new block and then frees the old block.

realloc (pointer_name, number * sizeof(int)); 9. Write a segment of code to print the elements of a single linked list. Nov /Dec 2009 void print(struct node * start) { while (start!=NULL) { printf(―%d‖, start→date) start=start→next; } }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

85

10. Differentiate Arrays and Linked List. ARRAY LINKED LIST

Size of an array is fixed Size of a list is not fixed

Memory is allocated from stack Memory is allocated from heap

It is necessary to specify the number of elements during declaration (i.e., during compile time).

It is not necessary to specify the number of elements during declaration. (i.e., memory is allocated during run time).

It occupies less memory than a linked list for the same number of elements.

It occupies more memory.

Inserting new elements at the front is potentially expensive because existing elements need to be shifted over to make room.

Inserting a new element at any position can be carried out easily.

Deleting an element from an array is not possible.

Deleting an element is possible.

11. What is a Linked List? (Nov / Dec 2008) List the advantages and disadvantages of Linked Lists Linked list is a linear collection of data elements called nodes, where the linear order is implemented by means of pointers. A linked list allocates memory for storing elements and connects elements together using pointers. Advantages of linked lists: 1. Linked lists are dynamic data structures. i.e., they can grow or shrink during the execution of a program. 2. Linked lists have efficient memory utilization. 3. Insertion and Deletions are easier, flexible and efficient. 4. Many complex applications can be easily carried out with linked lists. Disadvantages of linked lists: 1. It consumes more space because every node requires a additional pointer to store address of the next node. 2. Searching a particular element in list is difficult and also time consuming. 12. What is a Singly linked list? In a singly linked list, a node is connected to the next node by a single link. A node in this type of linked list contains two types of fields. Data - which holds a list element and Next - which stores a link to the next node in the list. Next Next Next

Data Data Data NULL

www.Vidyarthiplus.com

www.Vidyarthiplus.com

86

.13. What is a Doubly linked list? In a doubly linked list, a node is connected to other node by two links. A node in this type of linked list contains three types of fields. Data -which holds a list element. Prev - which stores a link to the previous node in the list. Next - which stores a link to the next node in the list.

Advantages Deletion operation is easier. Finding the predecessor & Successor of a node is easier. Disadvantages More Memory Space is required since it has two pointers. 14. What is Doubly circularly Linked List? It is a doubly linked list where the last node is linked to the first node of the list. The previous link of first node points to last node and next link of last node points to first node.

15. Define Polynomial ADT. A polynomial object is a homogeneous ordered list of pairs <exponent, coefficient>, where each coefficient is unique.

Operations include returning the degree, extracting the coefficient for a given exponent, addition, multiplication, evaluation for a given input. 10x4+5x2+1

PART – B

1. DOUBLY LINKED LIST

Write an algorithm to perform insertion and deletion on a doubly linked list. (16) Nov / Dec 2015 & (16) May / June 2014 Describe the creation of doubly linked list and appending the list. Give relevant coding in C. (16) Nov / Dec 2014 Doubly Linked List: A doubly linked list is a two-way list in which all nodes will have two links. This helps in accessing both successor node and predecessor node from the given node position. It provides bi-directional traversing.

Prev Next Prev Next Prev Next

NULL Data Data Data NULL

Prev Next Prev Next Prev Next

Data Data Data

www.Vidyarthiplus.com

www.Vidyarthiplus.com

87

Each node contains three fields: Left link. Data. Right link. The left link points to the predecessor node and the right link points to the successor node. The data field stores the required data. Many applications require searching forward and backward through nodes of a list. For example searching for a name in a telephone directory would need forward and backward scanning thru a region of the whole list. The basic operations in a double linked list are: Creation. Insertion. Deletion. Traversing.

Structure of a doubly linked list: The beginning of the double linked list is stored in a "start" pointer which points to the first node. The first node‘s left link and last node‘s right link is set to NULL.

Figure 3.1.1 Doubly Linked List

A doubly linked list is shown in fig.3.1. The following code gives the structure definition:

Figure 3.1.2. Structure definition, double link node and empty list

struct dlinklist { struct dlinklist *left; int data; struct dlinklist *right; }; typedef struct dlinklist node; node * start = NULL;

Node: Left Data right

Empty list: start

NULL

www.Vidyarthiplus.com

www.Vidyarthiplus.com

88

Creating a node for Doubly Linked List Creating a doubly linked list starts with creating a node. Sufficient memory has to be allocated for for creating a node. The information is stored in the memory, allocated by using the malloc() function. The function getnode() is used for creating a node, After allocating memory for the structure of type node, The information for the item has to be read from the user and set left field to NULL and right field also set to NULL.

Figure 3.1.3. New node with a value of 10 Creating a Double Linked List with „n‟ number of nodes: The following steps are to be followed to create ‗n‘ number of nodes: Step 1: Get the new node using getnode(). newnode =getnode(); Step 2: If the list is empty then start = newnode. Step 3: If the list is not empty, follow the steps given below: The left field of the new node is made to point the previous node. The previous nodes right field must be assigned with address of the new node. Step 4: Repeat the above steps ‗n‘ times. The function createlist(), is used to create ‗n‘ number of nodes:

vo id c r e at e list( int n) { int i; no d e * n e w no d e; no d e * t e m p ; fo r( i = 0 ; i < n; i+ + ) { n e w no d e = g et no d e(); if(st a rt = = N U L L) { sta rt = n e w no d e; } e ls e {

te m p = st a rt; w h ile(t e m p - > r ig ht)

node* getnode() { node* new node; newnode = (node *) malloc(sizeo f(no de)); printf("\n Enter data: "); scanf("%d", &newnode -> data); newnode -> left = NULL; newnode ->right = NULL; return new node; }

newnode

X 10 X

www.Vidyarthiplus.com

www.Vidyarthiplus.com

89

te m p = t e m p - > r ig ht; te m p - > r ig ht = n e w no d e; n e w no d e - > left = t e m p ; } } }

Figure 3.1.4. Double Linked List with 3 nodes

Inserting a node at the beginning: The following steps are to be followed to insert a new node at the beginning of the list: Step1: Get the new node using getnode(). newnode=getnode(); Step 2: If the list is empty then start = newnode. Step 3 : If the list is not empty, follow the steps given below: newnode -> right = start; start -> left = newnode; start = newnode; The function dbl_insert_beg(), is used for inserting a node at the beginning. Figure 3.5 shows inserting a node into the double linked list at the beginning.

Figure 3.1.5. Inserting a node at the beginning ROUTINE TO INSERT AN ELEMENT IN THE BEGINNING OF A LIST

void dll_insert_beg() { node * newnode; newnode=getnode(); if (start==NULL)

www.Vidyarthiplus.com

www.Vidyarthiplus.com

90

start=newnode; else { newnode->right =start; start->left=newnode; start=newnode; } } Inserting a node at the end: The following steps are followed to insert a new node at the end of the list: Step 1: Get the new node using getnode() newnode=getnode(); Step2 : a) If the list is empty then start = newnode. b) If the list is not empty follow the steps given below:

temp = start; while(temp -> right != NULL)

temp = temp -> right; temp -> right = newnode; newnode -> left = temp;

The function dbl_insert_end(), is used for inserting a node at the end. Figure 3.6 shows inserting a node into the double linked list at the end.

Figure 3.1.6. Inserting a node at the end

ROUTINE TO INSERT AN ELEMENT AT THE END OF A LIST

void dll_insert_end() { node *newnode, *temp; newnode=getnode(); if(start==NULL) start=newnode; else

www.Vidyarthiplus.com

www.Vidyarthiplus.com

91

{ temp=start; while(temp->right!=NULL) temp=temp->right; temp->right=newnode; newnode->left=temp; } } Inserting a node at an intermediate position: The following steps are followed, to insert a new node in an intermediate position in the list: Get the new node using getnode(). newnode=getnode(); Ensure that the specified position is in between first node and last node. If not, specified position is invalid. This is done by countnode() function. Store the starting address (which is in start pointer) in temp and prev pointers. Then traverse the temp pointer upto the specified position followed by prev pointer. After reaching the specified position, follow the steps given below:

newnode -> left = temp; newnode -> right = temp -> right;

temp -> right -> left = newnode; temp -> right = newnode; The function dbl_insert_mid(), is used for inserting a node in the intermediate position. Figure 3.7 shows inserting a node into the double linked list at a specified intermediate position other than beginning and end.

Figure 3.1.7. Inserting a node at an intermediate position

www.Vidyarthiplus.com

www.Vidyarthiplus.com

92

ROUTINE TO INSERT AN ELEMENT IN THE INTERMEDIATE POSITION

void dll_insert_mid(int pos)

{ node*newnode,*temp;

int pos, nodectr, ctr=1; newnode=getnode(); nodectr=countnode(start);

if(pos-nodectr>=2) { printf(―\n position is out of range‖);

return; } if(pos>1 && pos<nodectr)\

{ temp=start; while(ctr<pos-1)

{ temp=temp->right; ctr++;

} newnode->left=temp; newnode->right =temp->right;

temp->right->left=newnode; temp->right=newnode; }

printf(―\n not in intermediate position‖) }

Deleting a node at the beginning: The following steps are followed, to delete a node at the beginning of the list: If list is empty then display ‗Empty List‘ message. If the list is not empty, follow the steps given below: temp = start; start = start -> right; start -> left = NULL; free(temp); The function dbl_delete_beg(), is used for deleting the first node in the list. Figure 3.8 shows deleting a node at the beginning of a double linked list.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

93

Figure 3.1.8 Deleting a node at beginning

ROUTINE TO DELETE AN ELEMENT IN THE BEGINNING

void dll_delete_beg() { node *temp; if(start==NULL) { printf(―\n empty list‖); getch(); return; } else

{ temp =start; start =start->right; start->left=NULL; free(temp); } }

Deleting a node at the end: The following steps are followed to delete a node at the end of the list: Step 1: If list is empty then display ‗Empty List‘ message Step 2: If the list is not empty, follow the steps given below: temp = start; while(temp -> right != NULL) { temp = temp -> right; } temp -> left -> right = NULL; free(temp); The function dbl_delete_last(), is used for deleting the last node in the list. Figure 3.4.7 shows deleting a node at the end of a double linked list.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

94

Figure 3.1.9 Deleting a node at the end

ROUTINE TO DELETE AN ELEMENT AT THE END

void dll_delete_last() {

node *temp; if(start ==NULL) {

printf(―\n empty list‖); getch(); return;

} else {

temp=start; while(temp->right != NULL) temp=temp->right;

temp -> left -> right = NULL; free(temp); temp=NULL;

} }

Deleting a node at Intermediate position: The following steps are followed, to delete a node from an intermediate position in the list (List must contain more than two nodes). Step 1: If list is empty then display ‗Empty List‘ message. Step 2: If the list is not empty, follow the steps given below: Step 3: Get the position of the node to delete. Step 4: If not, specified position is invalid. Step 5: Ensure that the specified position is in between first node and last node. Then perform the following steps: if(pos > 1 && pos < nodectr) { temp = start; i = 1; while(i < pos)

www.Vidyarthiplus.com

www.Vidyarthiplus.com

95

{ temp = temp -> right; i++; }

temp -> right -> left = temp -> left; temp -> left -> right = temp -> right; free(temp);

printf("\n node deleted.."); } The function delete_at_mid(), is used for deleting the intermediate node in the list. Figure 3.10 shows deleting a node at a specified intermediate position other than beginning and end from a double linked list.

Figure 3.1.10 Deleting a node at an intermediate position

ROUTINE TO DELETE AN ELEMENT IN THE INTERMEDIATE POSITION void dll_delete_mod(int pos) { int i=0,pos,nodectr; node *temp; if(start == NULL) { printf(―\n empty list‖); getch(); return; } else { nodectr = countnode(start); if(pos>nodectr) { printf( ―\n thisnode does not exist‖); getch(); return; } if (pos >1 && pos <nodectr) { temp=start; i=1; while(i<pos) { temp=temp->right;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

96

i++; } temp->right->left=temp->left; temp->left->right=temp->right; free(temp); printf(―\n node deleted‖); } else { printf(―\n not intermediate position‖); getch(); } } }

Traversal and displaying a list (Left to Right): To display the information, you have to traverse the list, node by node from the first node, until the end of the list is reached. The function traverse () is used for traversing and displaying the information stored in the list from left to right. The following steps are followed, to traverse a list from left to right: Step 1: If list is empty then display ‗Empty List‘ message. Step 2: If the list is not empty, follow the steps given below:

temp = start; while(temp != NULL) { print temp -> data; temp = temp -> right; } ROUTINE TO TRAVERSE THE LIST

void traverse() { node * temp; temp=start; printf(―\n the contents of list‖); if (start == NULL) printf(―\n empty list‖); else { while(temp!=NULL) {

www.Vidyarthiplus.com

www.Vidyarthiplus.com

97

printf(―\t%d‖,temp->data); temp=temp->right; } } }

ROUTINE TO COUNT THE NUMBER OF NODES:

if countnode(node * start) { if (start == NULL) return 0; else return 1+countnode(start->right) }

2. SINGLY LINKED LIST

Write algorithms for insertion and deletion of nodes in a linked list. (16) May / June 2006 A linked list allocates space for each element separately in its own block of memory called a "node". The list gets an overall structure by using pointers to connect all its nodes together like the links in a chain. Each node contains two fields; a "data" field to store whatever element, and a "next" field which is a pointer used to link to the next node

Fig 3.2.1 Singly Linked List Each node is allocated in the heap using malloc(), so the node memory continues to exist until it is explicitly de-allocated using free(). The front of the list is a pointer to the ―start‖ node. A single linked list is shown in figure 3.11

Implementation of Single Linked List: Before writing the code to build the above list, we need to create a start node, used to create and access other nodes in the linked list. Creating a structure with one data item and a next pointer, which will be

www.Vidyarthiplus.com

www.Vidyarthiplus.com

98

pointing to next node of the list. This is called as self-referential structure.

Initialise the start pointer to be NULL.

Fig 3.2.2 Structure of a node

The basic operations in a single linked list are:

• Creation. • Insertion. • Deletion. • Traversing. Creating a node for Single Linked List: Creating a singly linked list starts with creating a node. Sufficient memory has to be allocated for creating a node. The information is stored in the memory, allocated by using the malloc() function. The function getnode(), is used for creating a node, after allocating memory for the structure of type node, the information for the item (i.e., data) has to be read from the user, set next field to NULL and finally returns the address of the node. Figure 3.13 illustrates the creation of a node for single linked list.

Fig 3.2.3 Creation of a node

Creating a Singly Linked List with „n‟ number of nodes: The following steps are to be followed to create ‗n‘ number of nodes: • Get the new node using getnode(). newnode =

struct slinklist { int data; struct slinklist *next; }; typedef struct slinklist node; node * start = NULL;

Node: Data Next

Empty list: start

NULL

node* getnode() { node* new node; newnode = (node *) malloc(s izeof(no de)) printf("\n Enter data: "); scanf("%d", &new node -> data); newnode -> next = NULL; return new node;

}

www.Vidyarthiplus.com

www.Vidyarthiplus.com

99

getnode(); •If the list is empty, assign new node as start. start = newnode; •If the list is not empty, follow the steps given below: •The next field of the new node is made to point the first node (i.e. start node) in the list by assigning the address of the first node. •The start pointer is made to point the new node by assigning the address of the new node. •Repeat the above steps ‗n‘ times. Figure 3.14 shows 4 items in a single linked list stored at different locations in memory.

Figure 3.2.4. Single Linked List with 4 nodes

ROUTINE TO CREATE A LIST

void createlist(int n) { int i; node *newnode; node * temp; for(i=0; i<n; i++) { newnode=getnode(); if(start = = NULL) { start = newnode; } else { temp=start; while(temp->next!=NULL) temp=temp->next; temp->next=newnode; } } }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

100

Insertion of a Node:

One of the most primitive operations that can be done in a singly linked list is the insertion of a node. Memory is to be allocated for the new node (in a similar way that is done while creating a list) before reading the data. The new node will contain empty data field and empty next field. The data field of the new node is then stored with the information read from the user. The next field of the new node is assigned to NULL. The new node can then be inserted at three different places namely: • Inserting a node at the beginning. • Inserting a node at the end. • Inserting a node at intermediate position.

Inserting a node at the beginning: The following steps are to be followed to insert a new node at the beginning of the list: • Get the new node using getnode(). newnode = getnode(); • If the list is empty then start = newnode. • If the list is not empty, follow the steps given below:

newnode -> next = start; start = newnode;

Figure 3.15 shows inserting a node into the single linked list at the beginning.

Figure 3.2.5. Inserting a node at the beginning

The function insert_at_beg(), is used for inserting a node at the beginning

void insert_at_beg() { node *newnode; newnode =getnode(); if(start = = NULL) { start = newnode; }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

101

else { newnode->next = start; start=newnode; } }

Inserting a node at the end: The following steps are followed to insert a new node at the end of the list:

• Get the new node using getnode() newnode = getnode(); • If the list is empty then start = newnode. • If the list is not empty follow the steps given below: temp = start; while(temp -> next != NULL)

temp = temp -> next; temp -> next = newnode;

Figure 3.16 shows inserting a node into the single linked list at the end.

Figure 3.2.6. Inserting a node at the end.

The function insert_at_end(), is used for inserting a node at the end.

void insert_at_end()

{

node *newnode, *temp; newnode = getnode();

if(start=NULL)

{

start=newnode; }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

102

else

{

temp=start;

while(temp->next !=NULL) temp=temp->next;

temp->next=newnode;

}

}

Inserting a node at intermediate position: The following steps are followed, to insert a new node in an intermediate position in the list: 1) Get the new node using getnode(). newnode = getnode(); 2) Ensure that the specified position is in between first node and last node. If not, specified position is invalid. This is done by countnode() function. 3) Store the starting address (which is in start pointer) in temp and prev pointers. Then traverse the temp pointer upto the specified position followed by prev pointer. 4) After reaching the specified position, follow the steps given below: prev -> next = newnode; newnode -> next = temp; Let the intermediate position be 3. Figure 3.17 shows inserting a node into the single linked list at a specified intermediate position other than beginning and end.

Figure 3.2.7 Inserting a node at an intermediate position.

void insert_at_mid(int pos) { node *newnode, *temp, *prev; int pos, nodectr, ctr=1; newnode = getnode(); nodectr=countnode(start); if (pos>1 && pos <nodectr) { temp=prev=start;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

103

while(ctr < Pos) { prev=temp; temp=temp->next; ctr++; } prev->next = newnode; newnode->next=temp; } else { printf(―Not a intermediate position‖); } }

Deletion of a node: Another primitive operation that can be done in a singly linked list is the deletion of a node. Memory is to be released for the node to be deleted. A node can be deleted from the list from three different places namely. • Deleting a node at the beginning.

• Deleting a node at the end.

• Deleting a node at intermediate position. Deleting a node at the beginning: The following steps are followed, to delete a node at the beginning of the list: • If list is empty then display ‗Empty List‘ message. • If the list is not empty, follow the steps given below:

temp = start;

start = start -> next; free(temp);

Figure 3.18 shows deleting a node at the beginning of a single linked list.

Figure 3.2.8 Deleting a node at the beginning

The function delete_at_beg(), is used for deleting the first node in the list.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

104

void delete_at_beg() { node *temp; if(start = = NULL) { printf(―\n Node does not exist‖); return; } else { temp=start; start = temp - >next; free(temp); printf(―\n node deleted‖); } }

Deleting a node at the end: The following steps are followed to delete a node at the end of the list: • If list is empty then display ‗Empty List‘ message. • If the list is not empty, follow the steps given below: temp = prev = start; while(temp -> next != NULL) {

prev = temp; temp = temp -> next; }

prev -> next = NULL; free(temp); Figure 3.19 shows deleting a node at the end of a single linked list.

Figure 3.2.9 Deleting a node at the end

www.Vidyarthiplus.com

www.Vidyarthiplus.com

105

void delete_at_last() { node *temp, *prev; if(start == NULL) { printf(―\n Empty List‖); return; } else { temp=start; prev=start; while (temp->next !=NULL) { prev=temp; temp=temp->next; } prev->next=NULL; free(temp); printf(―\n deleted‖); } }

Deleting a node at Intermediate position:

The following steps are followed, to delete a node from an intermediate position in the list (List must contain more than two node).

If list is empty then display ‗Empty List‘ message If the list is not empty, follow the steps given below. if(pos > 1 && pos < nodectr) { temp = prev = start; ctr = 1;

while(ctr < pos) { prev = temp; temp = temp -> next; ctr++; } prev -> next = temp -> next; free(temp);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

106

printf("\n node deleted.."); }

Figure 3.28 shows deleting a node at a specified intermediate position other than beginning and end from a single linked list

Figure 3.2.10 Deleting a node at intermediate position

void delete_at_mod(int pos) { int ctr=1, pos,nodectr; node *temp, *prev; if(start = = NULL) { printf(―\n Empty List‖); return; } else { nodectr=countnode(start); if(pos > nodectr) { printf(―\n The node does not exist‖); } if(pos> 1 && pos < nodectr) { temp=prev=start; while(ctr < pos) { prev=temp; temp=temp - > next; ctr++; } prev->next = temp ->next; free(temp);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

107

printf(―\n Deleted‖); } else { printf(―\n Invalid position‖); getch(); } } }

Traversal and displaying a list (Left to Right):

To display the information, you have to traverse (move) a linked list, node by node from the first node, until the end of the list is reached. Traversing a list involves the following steps:

• Assign the address of start pointer to a temp pointer.

• Display the information from the data field of each node.

The function traverse() is used for traversing and displaying the information stored in the list from left to right.

void traverse() { node *temp; temp = start; printf("\n The contents of List (Left to Right): \n"); if(start == NULL ) printf(―\n Epty List‖); else { while(temp!=NULL) { printf(―%d‖, temp ->data); temp=temp->next; } } }

Counting the Number of Nodes: The following code will count the number of nodes exist in the list using recursion.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

108

int countnode(node *st) { if (st == NULL) return 0; else return(1+countnode(st->next)); }

Merging two sorted List:

SortedMerge() function that takes two lists, each of which is sorted in increasing order, and merges the two together into one list which is in increasing order. SortedMerge() should return the new list. The new list should be made by splicing together the nodes of the first two lists.

For example if the first linked list a is 5->10->15 and the other linked list b is 2->3->20, then SortedMerge() should return a pointer to the head node of the merged list 2->3->5->10->15->20

ROUTINE TO MERGE THE SORTED LINKED LISTS

node* MergeLists(node* list1, node* list2) { node* mergedList; if(list1 = = NULL && list2 = =NULL) //if both are NULL, return NULL return NULL; if(list1 = = NULL) //if list1 is NULL, simply return list2 return list2; if(list2 = = NULL) //if list2 is NULL, simply return list1 return list1; if(list1->data < list2.data) /*initialize mergedList pointer to list1 if list1's data is lesser*/ { mergedList = list1; } else{ //initialize mergedList pointer to list2 if list2's data is lesser or equal mergedList = list2; } while(list1!=NULL && list2!=NULL) { if(list1->data < list2->data){ mergedList->next = list1; list1 = list1->next; }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

109

else{ mergedList->next = list2; list2 = list2->next; } } if(list1 == NULL) { //remaining nodes of list2 appended to merged List when list1 ends. mergedList->next = list2; } else {//remaining nodes of list1 appended to mergedList when list2 has reached its end mergedList ->next=list1; } return mergedList; }

3. POLYNOMIAL MANIPULATION (a) Explain the following: (8 + 8) Nov / Dec 2014 (i) Applications of lists. (ii) Polynomial Manipulations - Addition (8) (Nov / Dec 2015) (b) Write a C program to perform addition, subtraction and multiplication operations on polynomial using linked list. (16) April / May 2015 Polynomials is represented as a list of pairs of coefficient and exponent. Each of these pairs will constitute a structure, so a polynomial will be represented as a list of structures. A

linked list structure that represents polynomials 5x4 – 8x3 + 2x2 + 4x1 + 9x0 illustrates in figure 3.10.1

Fig. 3.3.1 Linked list representation of polynomial Declaration of Linked list implementation of Polynomial:

struct poly{ { int coeff; int power;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

110

struct poly *next; } *list1, *list2, *list3;

Creation of Polynomial:

poly create(poly *head, poly *newnode) { poly*ptr; if(head==NULL) { head=newnode; return(head); } else { ptr=head; while(ptr-> next!=NULL) ptr=ptr->next; ptr->next=newnode; } return(head); }

Addition of Polynomials: To add two polynomials we need to scan them once. If we find terms with the same exponent in the two polynomials, then we add the coefficients; otherwise, we copy the term of larger exponent into the sum and go on. When we reach at the end of one of the polynomial, then remaining part of the other is copied into the sum. To add two polynomials follow the following steps: • Read two polynomials. • Add them. • Display the resultant polynomial. Addition of Polynomials:

void add() { poly *ptr1, *ptr2, *newnode; ptr1=list1; ptr2=list2;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

111

while(ptr1!=NULL && ptr2!= NULL) { newnode=malloc(sizeof(struct poly)); if(ptr1->power==ptr2->power) { newnode->coeff = ptr1->coeff + ptr2->coeff; newnode->power=ptr1->power; newnode->next=NULL; list3=create(list3,newnode); ptr1=ptr->next; ptr2=ptr2->next; } else { if(ptr1->power > ptr2->power) { newnode->coeff = ptr1->coeff newnode->power=ptr1->power; newnode->next=NULL; list3=create(list3,newnode); ptr1=ptr1->next; } else { newnode->coeff = ptr2->coeff newnode->power=ptr2->power; newnode->next=NULL; list3=create(list3,newnode); ptr2=ptr2->next; } } } FOR SUBTRACTION OF POLYNOMIALS , add this statement in the above program newnode->coeff = ptr1->coeff - ptr2->coeff MULTIPLICATION OF POLYNOMIALS:

Multiplication of two polynomials however requires manipulation of each node such that the exponents are added up and the coefficients are multiplied. After each term of first polynomial is operated upon with each term of the second polynomial, then the result has to

www.Vidyarthiplus.com

www.Vidyarthiplus.com

112

be added up by comparing the exponents and adding the coefficients for similar exponents and including terms as such with dissimilar exponents in the result

void Mul() { poly *ptr1, *ptr2, *newnode; ptr1=list1; ptr2=list2; if(ptr1 == NULL && ptr2 == NULL) return; if(ptr1 == NULL) // I polynomial does not exist list3 = list2; elsif(ptr2 ==NULL) // II polynomial does not exist list3 =list1; else // Both polynomial exist { if(ptr1!=NULL && ptr2!= NULL) { while(ptr1!=NULL) { newnode=malloc(sizeof(struct poly)); while(ptr2!=NULL) { newnode->coeff = ptr1->coeff * ptr2 ->coeff; newnode->power=ptr1->power + ptr2->power; list3=create(list3,newnode); ptr2=ptr2->next; } ptr2=list2; ptr1=ptr1->next; } } } }

4. CIRCULARLY LINKED LIST

1. Write a C code for Circular linked list with create, insert, delete, display operations using structure pointer. (16) April / May 2015 Circularly (Single) Linked List:

It is a single linked list in which the link field of the last node points back to the address of the first node. A circular linked list has no beginning and no end. It is necessary to establish a special pointer called start pointer always pointing to the first node of the list. Circular

www.Vidyarthiplus.com

www.Vidyarthiplus.com

113

linked lists are frequently used instead of ordinary linked list because many operations are much easier to implement. In circular linked list no NULL pointers are used, hence all pointers contain valid address.

A circular single linked list is shown in figure

Figure 3.4.1. C ircular Single Linked List

The basic operations in a circular single linked list are: • Creation. • Insertion. • Deletion. • Traversing.

Creating a circular single Linked List with „n‟ number of nodes: The following steps are to be followed to create ‗n‘ number of nodes:

Get the new node using getnode(). newnode = getnode();

If the list is empty, assign new node as start. start=newnode;

If the list is not empty, follow the steps given below: o temp = start; o while(temp -> next != NULL)

temp = temp-> next; o temp -> next = newnode;

Repeat the above steps ‗n‘ times. newnode -> next = start;

CREATING A NODE: struct cslinklist {

int data; struct cslinklist *next; };

typedef struct cslinklist node;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

114

node *start = NULL; int nodectr; node* getnode() {

node * newnode; newnode = (node *) malloc(sizeof(node)); printf("\n Enter data: ");

scanf("%d", &newnode -> data); newnode -> next = NULL; return newnode; } The function createlist(), is used to create ‗n‘ number of nodes: ROUTINE TO CREATE A LIST

void createlist(int n) { int i; node * newnode; node * temp; nodectr = n; for(i=0; i<n; i++) { newnode = getnode(); if (start == NULL) { start=newnode; } else { temp=start; while(temp->next!=NULL) temp=temp->next; temp->next = newnode; } } newnode->next = start; }

Inserting a node at the beginning: The following steps are to be followed to insert a new node at the beginning of the circular list: o Get the new node using getnode(). newnode = getnode(); o If the list is empty, assign new node as start.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

115

start = newnode; newnode -> next = start; o If the list is not empty, follow the steps given below: last = start;

while(last -> next != start) last = last -> next;

newnode -> next = start; start = newnode;

last -> next = start;

Figure 3.4.2. Insertion at the beginning

The function cll_insert_beg(), is used for inserting a node at the beginning.Figure shows inserting a node into the circular single linked list at the beginning.

ROUTINE TO INSERT A NODE AT THE BEGINNING OF THE LIST

void cll_insert_beg() { node *newnode, *last; newnode = getnode(); if (start == NULL) { start =newnode; newnode - > next = start; } else { last = start; while(last -> next != start) last = last - >next; start=newnode; last->next = start; } nodectr++; }

Inserting a node at the end:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

116

The following steps are followed to insert a new node at the end of the list:

Figure 3.4.3 Inserting a node at the end.

Figure 3.6.3 shows inserting a node into the circular single. linked list at the end

o Get the new node using getnode(). newnode = getnode(); o If the list is empty, assign new node as start. start = newnode; newnode -> next = start; o If the list is not empty follow the steps given below: temp = start; while(temp -> next != start) temp = temp -> next;

temp -> next = newnode; newnode -> next = start; The function cll_insert_end(), is used for inserting a node at the end. ROUTINE TO INSERT A NODE AT THE END OF THE LIST

void cll_insert_end() { node *newnode, *temp; newnode = getnode(); if (start == NULL) { start =newnode; newnode - > next = start; } else { temp = start; while(temp -> next != start) temp = temp - >next;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

117

temp->next = newnode; newnode - > next=start; } nodectr++; }

Deleting a node at the beginning: The following steps are followed, to delete a node at the beginning of the list: • If the list is empty, display a message ‗Empty List‘. • If the list is not empty, follow the steps given below: last = temp = start; while(last -> next != start) last = last -> next; start = start -> next;

last -> next = start; • After deleting the node, if the list is empty then start = NULL. The function cll_delete_beg(), is used for deleting the first node in the list. Figure 3.6.4 shows deleting a node at the beginning of a circular single linked list.

Figure 3.4.4. Deleting a node at the beginning

ROUTINE TO DELETE A NODE AT THE BEGINNING

void cll-delete-beg() { node * temp, *last; if (start == NULL) { getch(); return; } else { last=temp=start; while(last->next != start) last=last - >next;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

118

start=start->next; last->next=start; free (temp); nodectr--; if (nodectr==0) start=NULL; } }

Deleting a node at the end: The following steps are followed to delete a node at the end of the list If the list is empty, display a message ‗Empty List‘. If the list is not empty, follow the steps given below: temp = start; prev = start; while(temp -> next != start) { prev = temp; temp = temp -> next; } prev->next = start;

• After deleting the node, if the list is empty then start = NULL.

The function cll_delete_last(), is used for deleting the last node in the list.

Figure 3.6.5 shows deleting a node at the end of a circular single linked list.

Figure 3.4.5. Deleting a node at the end.

ROUTINE TO DELETE A NODE AT THE END OF THE LIST

void cll-delete-end() { node * temp, *prev; if (start == NULL)

www.Vidyarthiplus.com

www.Vidyarthiplus.com

119

{ getch(); return; } else { temp=start; prev=start; while(temp->next != start) { prev=temp; temp=temp - >next; } prev->next=start; free (temp); nodectr--; if (nodectr==0) start=NULL; } }

Traversing a circular single linked list from left to right:

The following steps are followed, to traverse a list from left to right:

• If list is empty then display ‗Empty List‘ message.

• If the list is not empty, follow the steps given below:

temp = start; do {

printf("%d ", temp -> data); temp = temp -> next; } while(temp != start); ROUTINE TO TRAVERSE THE LIST

void traverse() { node * temp; temp=start;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

120

If (start == NULL) printf(―\n empty‖); else { do { printf(―%d‖, temp->data); temp=temp->next; } while(temp!=start); }

5. ARRAY IMPLEMENTATION OF LIST

a. Discuss the implementation of list operations using array and write the C code for it. b.Consider an Array [1:n] Given a position, write an algorithm to insert an element in the array. If the position is empty, the element is inserted easily. If the position is already occupied, the element should be inserted with the minimum number of shifts. (Note: the elements can shift to the left or the right to make the minimum number of

moves) (16)(May / June 2014) Array is a container which can hold fix number of items and these items should be of same type. Most of the data structure makes use of array to implement their algorithms. Following are important terms to understand the concepts of Array. Element − Each item stored in an array is called an element. Index − Each location of an element in an array has a numerical index which is used

to identify the element.

Array Representation Arrays can be declared in various ways in different languages. For illustration, let's take C array declaration.

Arrays can be declared in various ways in different languages. For illustration, let's take C array declaration.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

121

As per above shown illustration, following are the important points to be considered. Index starts with 0. Array length is 8 which means it can store 8 elements. Each element can be accessed via its index. For example, we can fetch element at index 6 as 9.

Basic Operations Following are the basic operations supported by an array. Traverse − print all the array elements one by one. Insertion − add an element at given index. Deletion − delete an element at given index. Search − search an element using given index or by value. Update − update an element at given index. Sorting – arrange the elements in ascending and descending order Merging – combine the elements of the arrays Insertion: Inserting an element at the end of an array can be done easily if the memory space allocated for the array is large. If we need to insert an element in the middle of the array, then on an average, half of the elements must be moved downward to new locations to accommodate the new element and keep the order of the other elements. (downward – higher subscript) Insertion of an element into an array: (Inserting into a linear Array) INSERT (A, N , K , ITEM) A is a linear array with N elements and K is a Positive integer such that K<=N. This algorithm inserts an element ITEM into the Kth position in A 1. Initialise Counter. Set J=N 2. Repeat Steps 3 and 4 while J>=K 3. Move J th element downward. Set A[j+1] = A[j] 4. Decrease Counter. Set J= J – 1

End of Loop 5. Insert Element. Set A[K] = ITEM 6. Reset N. Set N := N+1; 7. Exit

www.Vidyarthiplus.com

www.Vidyarthiplus.com

122

Deletion of an element from an array: Deleting an element at the end of an array is not difficult. But deleting an element in the middle of an array would require that each subsequent element be moved one location upward in order to fill up the array. (Smaller subscript) (Deleting from a Array) DELETE (A, N,K.ITEM) Here A is a linear array with N elements and K is a positive integer such that K<=N. This algorithm deletes Kth element from A 1. Set ITEM=A[K] 2. Repeat for J=K to N-1 Move J+1 th element upward. Set A[J] = A[J+1] End of Loop 3. Reset the number N of elements in A. Set N=N-1; 4. Exit

Searching an element in an Array : To search for a given item in an array is to compare the item with each element of the array one by one. We test if arr[1] = ITEM , and then we test arr[2] =ITEM and so on. This method searches the element sequentially one after the other to locate ITEM. This search is called LINEAR search of BINARY search. Algorithm for Linear Search Let A be an Array of n elements, A[1], A[2],A[3] , .. A[n]. ITEM is the element to be searched. Then this algorithm will find the location ―loc‖ of data in A. set loc==-1 if the search is unsuccessful. 1. Input an array A of n elements and ITEM to be searched and initialize loc=-1 2. Initialise i=0 and repeat through step 3 if i<n by incrementing i by one 3. If (ITEM=A[i]) (a) loc=i (b) GOTO step 4

4. If(loc>0) (a) Display ―Data is found and searching is unsuccessful‖ 5. Else (a) Display ―Data is not found and searching is unsuccessful‖ 6. Exit

C program to implement list operations using array: #include <stdio.h> #include<stdlib.h> #include<conio.h>

www.Vidyarthiplus.com

www.Vidyarthiplus.com

123

void insert(int a[], int n) {

int i; printf("\nEnter the elements of the array!!"); for(i=0;i<n;i++) { printf("\nEnter element %d:",i+1); scanf("%d",&a[i]); }

} void print(int a[], int n) {

int i; printf("\nThe elements of the array are!!"); for(i=0;i<n;i++) {

printf("%d\t",a[i]); }

} void insertatpos(int a[],int *n, int loc) {

loc--; int t=*n; while(t>loc) { a[t]=a[t-1]; t--; } (*n)--; printf("\nNow enter the element:"); scanf("%d",&t); a[loc]=t;

} void del(int a[],int *n, int loc) { loc--; while(*n>loc) { a[loc]=a[loc+1]; loc++; } (*n)--;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

124

} void search(int a[],int n) { int i; int t,flag=0; printf("\nEnter the search element:"); scanf("%d",&t); for(i=0;i<n;i++) { if(a[i]==t) { flag=1; break; } } if(flag==0) printf("\nThe element not found!!!!"); else printf("\nThe element found at location %d", i+1); } int main() { int a[100],n; printf("\nEnter the array size:"); scanf("%d",&n); int o,loc; while(o!=0) { printf("\nENTER YOUR OPTION!!\n"); printf("\nEnter 1 for INSERTION"); printf("\nEnter 2 for DELETION"); printf("\nEnter 3 for ADDING ELEMENT"); printf("\nEnter 4 for PRINTING"); printf("\nEnter 5 for SEARCHING"); printf("\nEnter 0 for exit!!"); scanf("%d",&o); switch(o) { case 1:{ insert(a,n); break; } case 2:{ printf("\nEnter the location of the element to be deleted:");

www.Vidyarthiplus.com

www.Vidyarthiplus.com

125

scanf("%d",&loc); del(a,&n,loc); break; } case 3:{ printf("\nEnter the location of where u wanna insert:"); scanf("%d",&loc); insertatpos(a,&n,loc); break; } case 4:{print(a,n);break; } case 5:{search(a,n);break;} case 0:break; default:printf("\nU have entered the wrong choice!!!!!"); } } getche(); }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

126

UNIT – IV LINEAR DATA STRUCTURES – STACKS, QUEUES

Stack ADT – Evaluating arithmetic expressions- other applications- Queue ADT – circular queue implementation – Double ended Queues – applications of queues

PART A 1. Define Double ended Queue. May / June 2014 What is double ended Queue. Nov / Dec 2014 Define dequeue. May / June 2006 A double-ended queue is an abstract data type similar to an simple queue, it allows to insert and delete from both sides ie., items can be added or deleted from the front or rear end. In double ended queue we can make use of both the front as well as rear ends for insertion and deletion. That means it is possible to insert/delete elements by rear as well as front end. insertion by front end deletion by rear end 10 20 30 40 deletion by front end insertion by rear end 2. What is the role of stack in function call? Nov / Dec 2007 Stack is used to store and retrieve return addresses during function calls. It is good to use during nested function calls or recursive function calls. 3. What is a Stack? How it can be represented in C using arrays? Apr / May 2008 Stack or LIFO is an abstract data type which is a collection of items in which the data are inserted and remove from one end called the top of the stack. A stack is a linear data structure which follows Last In First Out (LIFO) principle, in which both insertion and deletion occur at only one end of the list called the Top. The operations performed on stack are PUSH and POP. top C POP(S) STACK(S) PUSH(X,S) A TOP(S) B 4. What are the various types of Queues? Apr / May 2008 1. Simple Queue 2. Circular Queue 3. Priority Queue 4. Dequeue (Double Ended queue)

www.Vidyarthiplus.com

www.Vidyarthiplus.com

127

5. Explain the representations of priority Queue. May / June 2006 A priority queue is an abstract data type which is like a regular queue data structure.In a priority queue, an element with high priority is served before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. but where additionally each element has a "priority" associated with it.

6. Differentiate Stack and Queue. Nov / Dec 2011

S.No Stack Queue

1 LIFO – Last In First Out FIFO – First in First Out

2 Push and Pop operation at the top of the stack

Insertion at the rear end and deletion at the front end.

3

Applications:

Balancing Symbols

Postfix expression evaluation

Applications:

Priority Queue

Simulation

7. Give the various applications of stack and Queue. Nov / Dec 2014,Nov/ Dec 2009 List the applications of a Queue. May / June 2014 Write any four applications of Queues. Nov /Dec 2008, Nov/Dec 2007 Applications of Stack: (i) Evaluating arithmetic operations (ii)Balancing the symbols (iii)Tower of Hanoi (iv) Function calls (v) 8 Queens Problem Applications of Queue: (i) Implementing priority queue (ii)Batch processing in OS (iii)Simulation (iv)Queuing theory 8. Justify Queue as ADT. Nov / Dec 2007 An Abstract Data Type (ADT) is defined as a mathematical model of the data objects that make up a data type as well as the functions that operate on these objects. The definition of ADT has the following two parts: (i) Description of the way in which components are related to each other. (ii) Statements of operations that can be performed on that data type. Since Queue is defined by a set of values and a set of operations (insert and delete) and therefore it represents the Logical behavior of ADT.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

128

A Queue is a linear data structure which follows First In First Out (FIFO) principle, inwhich insertion is performed at rear end and deletion is performed at front end. DEQUEUE(Q) QUEUE Q ENQUEUE(Q) 9. Mention the advantages of representing stacks using linked lists than arrays. Nov /Dec 2011 Members of array are aligned at equal distance and need contiguous memory while on the other side link list can provide non contiguous memory solution. Array can cause exceptions like index out of bound exceptions but you can increase the chain anytime in a linked list. 10. Given the prefix for an expression, write its postfix. Apr / May 2015 - * - + a b c / e f – g / h i postfix form: a b + c – e / f * g – h / i – What are the postfix and prefix forms of the expression? A+B*(C-D)/(P-R) Postfix form: ABCD-*PR-/+

Prefix form: +A/*B-CD-PR

11. What is a Circular queue? In Circular Queue, the insertion of a new element is performed at the very first location of the queue if the last location of the queue is full, in which the first element comes just after the last element. 12. Explain the usage of stack in recursive algorithm implementation? In recursive algorithms, stack data structures is used to store the return address when a recursive call is encountered and also to store the values of all the parameters essential to the current state of the procedure. 13. What are the different types of notations used to represent Arithmetic Expression? There are 3 different ways of representing the arithmetic expression. INFIX NOTATION POSTFIX NOTATION PREFIX NOTATION 14. What is INFIX notation, POSTFIX notation and PREFIX notation? In Infix notation, The arithmetic operator appears between the two operands to which it is being applied. For example : - A / B + C

www.Vidyarthiplus.com

www.Vidyarthiplus.com

129

The arithmetic operator appears directly after the two operands to which it applies. Also called reverse polish notation. ((A/B) + C) . For example : - AB / C + The arithmetic operator is placed before the two operands to which it applies. Also called as polish notation. ((A/B) + C) .For example : - +/ABC 15. Define overflow and underflow in queue? Attempt to insert an element into the queue, when the queue is full is said to be overflow. Attempt to delete an element from the queue, when the queue is empty is said to be underflow.

PART B

1.STACK ADT-IMPLEMENTATION

Explain the array and linked list implementation of stack. (OR) Explain STACK ADT in detail. (8) Nov/Dec 2014

STACK

A stack is a linear data structure which follows Last In First Out (LIFO) principle, in which both insertion and deletion occur at only one end of the list called the Top. Example: pile of coins. top C POP(S) STACK(S) PUSH(X,S) A TOP(S) B OPERATIONS ON STACK The fundamental operations performed on a stack are : Push and Pop.

PUSH :

The process of inserting a new element to the top of the stack. For every push operation the top is incremented by 1.

POP :

The process of deleting an element from the top of stack is called pop operation. After every pop operation the top pointer is decremented by 1.

EXCEPTIONAL CONDITIONS

OverFlow

Attempt to insert an element when the stack is full is said to be overflow.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

130

UnderFlow

Attempt to delete an element, when the stack is empty is said to be underflow.

IMPLEMENTATION OF STACK Stack can be implemented in 2 ways. 1. Array Implementation 2. Linked List Implementation

ARRAY IMPLEMENTATION In this implementation each stack is associated with a pop pointer, which is -1 for an empty stack. • To push an element X onto the stack, Top Pointer is incremented and set Stack [Top] = X. • To pop an element, the stack [Top] value is returned and the top pointer is decremented.

ROUTINE TO PUSH AN ELEMENT ONTO A STACK

void push (int x, Stack S) { if (IsFull (S)) Error ("Full Stack"); } else { Top = Top + 1; S[Top] = x;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

131

} } int IsFull (Stack S) { if (Top = = Arraysize) return (1); }

ROUTINE TO POP AN ELEMENT FROM THE STACK

void pop (Stack S) { if (IsEmpty (S)) Error ("Empty Stack"); else { x = S [Top]; Top = Top - 1; } } int IsEmpty (Stack S) { if (S[Top] = = -1) return (1); }

ROUTINE TO RETURN TOP ELEMENT OF THE STACK

int TopElement (Stack S) { if (! IsEmpty (s)) return S[Top]; else Error ("Empty Stack"); return 0; }

LINKED LIST IMPLEMENTATION OF STACK • Push operation is performed by inserting an element at the front of the list. • Pop operation is performed by deleting at the front of the list. • Top operation returns the element at the front of the list. DECLARATION FOR LINKED LIST IMPLEMENTATION

www.Vidyarthiplus.com

www.Vidyarthiplus.com

132

Struct Node; typedef Struct Node *Stack; int IsEmpty (Stack S); Stack CreateStack (void); void MakeEmpty (Stack S); void push (int X, Stack S); int Top (Stack S); void pop (Stack S);

/*Linked list declaration*/ Struct Node { int Element ; Struct Node *Next; };

ROUTINE TO CHECK WHETHER THE STACK IS EMPTY

/*Check whether the stack is empty or not */ int IsEmpty (Stack S) { if (S→Next = = NULL) return (1); }

ROUTINE TO CREATE AN EMPTY STACK

/*To create an empty stack*/ Stack CreateStack ( ) { Stack S; S = malloc (Sizeof (Struct Node)); if (S = = NULL) Error (" Outof Space"); MakeEmpty (s); return S; } /*To make the stack empty*/ void MakeEmpty (Stack S) { if (S = = NULL) Error (" Create Stack First"); else while (! IsEmpty (s)) pop (s);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

133

}

ROUTINE TO PUSH AN ELEMENT ONTO A STACK

/*Check whether enough memory space to insert*/ void push (int X, Stack S) { Struct Node * Temp; Temp = malloc (sizeof (Struct Node)); if (Temp= = NULL) Error ("Out of Space"); else { Temp Element = X; Temp Next = S Next; S→Next = Temp; } }

ROUTINE TO RETURN TOP ELEMENT IN A STACK

int Top (Stack S) { if (! IsEmpty (s)) return S→Next→Element; Error ("Empty Stack"); return 0; }

ROUTINE TO POP FROM A STACK void pop (Stack S) { Struct Node *Tempcell; If (IsEmpty (S)) Error ("Empty Stack"); Else { Tempcell=S→Next; S→Next=S→Next→Next; Free (Tempcell); } }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

134

2. EVALUATING ARITHMETIC EXPRESSIONS

Explain how stack is applied for evaluating an arithmetic expression. (16) [May2014]

To evaluate an arithmetic expressions, first convert the given infix expression to postfix expression and then evaluate the postfix expression using stack.

Conversion from infix to postfix: Procedure to convert from infix expression to postfix expression is as follows: 1. Scan the infix expression from left to right. 2. a) If the scanned symbol is left parenthesis, push it onto the stack. b) If the scanned symbol is an operand, then place directly in the postfix expression (output). c) If the symbol scanned is a right parenthesis, then go on popping all the items from the stack and place them in the postfix expression till we get the matching left parenthesis. d) If the scanned symbol is an operator, then go on removing all the operators from the stack and place them in the postfix expression, if and only if the precedence of the operator which is on the top of the stack is greater than (or greater than or equal) to the precedence of the scanned operator and push the scanned operator onto the stack otherwise, push the scanned operator onto the stack.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

135

EVALUATING POSTFIX EXPRESSION

The postfix expression is evaluated easily by the use of a stack. When a number is seen, it is pushed onto the stack; when an operator is seen, the operator is applied to the two numbers that are popped from the stack and the result is pushed onto the stack.

Read the postfix expression one character at a time until it reaches "#" symbol.

Step 1 : If the character is an operand, push its associated value onto the stack. Step 2 : If the character is an operator, POP two values from the stack, apply the operator to them and push the result onto the stack.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

136

3. APPLICATIONS OF STACK What are the applications of stack? Discuss in detail. (8) [Dec2014] 1. Stack is used by compilers to check for balancing of parentheses, brackets and braces 2. Stack is used to evaluate a postfix expression. 3. Stack is used to convert an infix expression into postfix/prefix form. 4. In recursion, all intermediate arguments and return values are stored on the processor‘s stack. 5. During a function call the return address and arguments are pushed onto a stack and

on return they are popped off. Different Types of Notations to Represent Arithmetic Expression There are 3 different ways of representing the algebraic expression. They are * INFIX NOTATION * POSTFIX NOTATION * PREFIX NOTATION

www.Vidyarthiplus.com

www.Vidyarthiplus.com

137

INFIX In Infix notation, The arithmetic operator appears between the two operands to which it is being applied. For example : - A / B + C POSTFIX The arithmetic operator appears directly after the two operands to which it applies. Also called as reverse polish notation. ((A/B) + C). For example : - AB / C + PREFIX The arithmetic operator is placed before the two operands to which it applies. Also called as polish notation. ((A/B) + C). For example : - +/ABC INFIX PREFIX (or) POLISH POSTFIX (or) REVERSE POLISH 1. (A + B) / (C - D) /+AB - CD AB + CD - / 2. A + B*(C - D) +A*B - CD ABCD - * + 3. X * A / B - D - / * XABD X A*B/D- 4. A * B/C + D +/ * ABCD AB * C / D + 1. Evaluating Arithmetic Expression To evaluate an arithmetic expressions, first convert the given infix expression to postfix expression and then evaluate the postfix expression using stack. Infix to Postfix Conversion Read the infix expression one character at a time until it encounters the delimiter. "#" Step 1 : If the character is an operand, place it on to the output. Step 2 : If the character is an operator, push it onto the stack. If the stack operator has a higher or equal priority than input operator then pop that operator from the stack and place it onto the output. Step 3 : If the character is a left paraenthesis, push it onto the stack. Step 4 : If the character is a right paraenthesis, pop all the operators from the stack till it encounters left parenthesis, discard both the parenthesis in the output. Evaluating Postfix Expression Read the postfix expression one character at a time until it encounters the delimiter `#'. Step 1 : - If the character is an operand, push its associated value onto the stack. Step 2 : - If the character is an operator, POP two values from the stack, apply the operator to them and push the result onto the stack. Infix Expression : A * B # Read Character Stack Output A A

www.Vidyarthiplus.com

www.Vidyarthiplus.com

138

* * A B * A B # A B * Example: Let us consider the symbols A,B, with values

Symbol Value A 4 B 5 EVALUATION OF A B * Read Character Stack A 4 - 5 B 4 * 20 result=20

2. Balancing the symbols

Read one character at a time until it encounters the delimiter. "#" Step 1 : If the character is an opening symbol, push it on to the stack. Step 2 : If the character is a closing symbol, and if the stack is empty, then report an error as missing opening symbol.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

139

Step 3 : If the character is a closing symbol and if it has a corresponding opening symbol in the stack, then pop it from the stack. Otherwise report an error as mismatched symbols. Step 4 : At the end of file, if the stack is not empty, report an error as missing closing symbol. Otherwise report as balanced symbols. Let us consider the expression (a+b)# Read Character Stack ( ( a ( + ( b ( ) # Balanced symbol. Stack is empty. 3. Towers of Hanoi The problem is moving a collection of N disks of decreasing size from one pillar to another pillar. The movement of the disk is restricted by the following rules. Rule 1: Only one disk could be moved at a time. Rule 2: No larger disk could ever reside on a pillar on top of a smaller disk. Rule 3: A 3rd pillar could be used as an intermediate to store one or more disks, while they werebeing moved from sourced to destination. Recursive Solution N - represents the number of disks. Step 1. If N = 1, move the disk from A to C. Step 2. If N = 2, move the 1st disk from A to B. Then move the 2nd disk from A to C, Then move the 1st disk from B to C. Step 3. If N = 3, Repeat the step (2) to more the first 2 disks from A to B using C as intermediate. Then the 3rd disk is moved from A to C. Then repeat the step (2) to move 2 disks from B to C using A as intermediate. In general, to move N disks. Apply the recursive technique to move N - 1 disks from A to B using C as an intermediate. Then move the Nth disk from A to C. Then again apply the recursive technique to move N - 1 disks from B to C using A as an intermediate.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

140

RECURSIVE ROUTINE FOR TOWERS OF HANOI void hanoi (int n, char s, char d, char i) { /* n no. of disks, s source, d destination i intermediate */ if (n = = 1) { print (s, d); return; } else { hanoi (n - 1, s, i, d); print (s, d) hanoi (n-1, i, d, s); return; }} 4.Function Calls When a call is made to a new function all the variables local to the calling routine need to be saved, otherwise the new function will overwrite the calling routine variables. Similarly the current location address in the routine must be saved so that the new function knows where to go after it is completed. Main( ) Balance ( ) Push ( ) Call Balance ( ) Call Push ( ) Return Return RECURSIVE FUNCTION TO FIND FACTORIAL: - int fact (int n) { int s;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

141

if (n = = 1) return (1); else s = n * fact (n - 1); return (s); }

4. QUEUE ADT IMPLEMENTATION

Explain the array and linked list implementation of queue. (OR) [May2015] Explain QUEUE ADT in detail. (8) [Dec2014] QUEUE A Queue is a Linear data structure which follows First In First Out (FIFO) principle, in which insertion is performed at rear end and deletion is performed at front end. DEQUEUE(Q) QUEUE Q ENQUEUE(Q) OPERATIONS ON QUEUE The fundamental operations performed on queue are: Enqueue and Dequeue. Enqueue : The process of inserting an element in the queue. Dequeue : The process of deleting an element from the queue. EXCEPTIONAL CONDITIONS

Oveflow: Attempt to insert an element into the queue, when the queue is full is said to be overflow.

Underflow: Attempt to delete an element from the queue, when the queue is empty is said to be underflow. IMPLEMENTATION OF QUEUE Queue can be implemented in 2 ways. 1. Array Implementation 2. Linked List Implementation ARRAY IMPLEMENTATION In order to create a queue we require a one dimensional array Q(1:n) and two variables front and rear. The conventions we shall adopt for these two variables are that front is always 1 less than the actual front of the queue and rear always points to the last element in the queue.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

142

Thus, front = rear if and only if there are no elements in the queue. The initial condition is front = rear = -1. The various queue operations to perform creation, deletion and display the elements in a queue are as follows: 1. insertQ(): inserts an element at the end of queue Q. 2. deleteQ(): deletes the first element of Q. 3. displayQ(): displays the elements in the queue. In this implementation queue Q is associated with two pointers namely rear pointer and front pointer. • To insert an element X onto the Queue Q, the rear pointer is incremented by 1 and then set Queue [Rear] = X • To delete an element, the Queue [Front] is returned and the Front Pointer is incremented by 1. ROUTINE TO ENQUEUE void Enqueue (int X) { if (rear = = max _ Arraysize-1) print (" Queue overflow"); else { rear = rear + 1; Queue [rear] = X; if(front==-1) front=0; } } ROUTINE FOR DEQUEUE void delete ( ) { if (front < 0) print (" Queue Underflow"); else { X = Queue [front]; if (front = = rear) { front = -1; rear = -1; }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

143

else front = front + 1 ; } } In Dequeue operation, if Front = Rear, then reset both the pointers to their initial values. (i.e. F = -1, R = -1) LINKED LIST IMPLEMENTATION OF QUEUE We can represent a queue as a linked list. In a queue data is deleted from the front end and inserted at the rear end. We can perform similar operations on the two ends of a list. We use two pointers front and rear for our linked queue implementation. Front rear

100 200 300 400 • Enqueue operation is performed at the end of the list. • Dequeue operation is performed at the front of the list. DECLARATION FOR LINKED LIST IMPLEMENTATION OF QUEUE ADT Struct Node; typedef Struct Node * Queue; int IsEmpty (Queue Q); Queue CreateQueue (void); void MakeEmpty (Queue Q); void Enqueue (int X, Queue Q); void Dequeue (Queue Q); Struct Node { int Element; Struct Node *Next; }* Front = NULL, *Rear = NULL; ROUTINE TO CHECK WHETHER THE QUEUE IS EMPTY int IsEmpty (Queue Q) // returns boolean value / { // if Q is empty

100 400

10

200

20

300

40 X

30 400

www.Vidyarthiplus.com

www.Vidyarthiplus.com

144

if (Q→Next = = NULL) // else returns 0 return (1); } ROUTINE TO CHECK AN EMPTY QUEUE Struct CreateQueue ( ) { Queue Q; Q = malloc (Sizeof (Struct Node)); if (Q = = NULL) printf ("Out of Space"); MakeEmpty (Q); return Q; } void MakeEmpty (Queue Q) { if (Q = = NULL) printf ("Create Queue First"); else while (! IsEmpty (Q) Dequeue (Q); } ROUTINE TO ENQUEUE AN ELEMENT IN QUEUE void Enqueue (int X) { Struct node *newnode; newnode = malloc (sizeof (Struct node)); if (Rear = = NULL) { newnode →data = X; newnode →Next = NULL; Front = newnode; Rear = newnode; } else { newnode → data = X; newnode → Next = NULL; Rear →next = newnode; Rear = newnode; } } ROUTINE TO DEQUEUE AN ELEMENT FROM THE QUEUE void Dequeue ( ) {

www.Vidyarthiplus.com

www.Vidyarthiplus.com

145

Struct node *temp; if (Front = = NULL) printf("Queue is underflow"); else { temp = Front; if (Front = = Rear) { Front = NULL; Rear = NULL; } else Front = Front →Next; printf("%d\n",temp→data); free (temp); } }

5. CIRCULAR QUEUE IMPLEMENTATION

Explain circular queue (or) circular buffer in detail.

CIRCULAR QUEUE A more efficient queue representation is obtained by regarding the array Q[MAX] as circular. Any number of items could be placed on the queue. This implementation of a queue is called a circular queue because it uses its storage array as if it were a circle instead of a linear list. In Circular Queue, the insertion of a new element is performed at the very first location of the queue if the last location of the queue is full, in which the first element comes just after the last element. To perform the insertion of an element to the queue, the position of the element is calculated by the relation as Rear = (Rear + 1) % Maxsize. and then set Queue [Rear] = value. ROUTINE TO INSERT AN ELEMENT IN CIRCULAR QUEUE void CEnqueue (int X) { if (Front = = (rear + 1) % Maxsize) print ("Queue is overflow"); else {

www.Vidyarthiplus.com

www.Vidyarthiplus.com

146

if (front = = -1) front = rear = 0; else rear = (rear + 1)% Maxsize; CQueue [rear] = X; } } To perform the deletion, the position of the Front printer is calculated by the relation Value = CQueue [Front] Front = (Front + 1) % maxsize. ROUTINE TO DELETE AN ELEMENT FROM CIRCULAR QUEUE int CDequeue ( ) { if (front = = -1) print ("Queue is underflow"); else { X = CQueue [Front]; if (Front = = Rear) Front = Rear = -1; else Front = (Front + 1)% maxsize; } return (X);

}

EXAMPLE Q[5] Q[0] Q[4] Q[1] Q[3] Q[2]

www.Vidyarthiplus.com

www.Vidyarthiplus.com

147

INSERTION ON CIRCULAR QUEUE

www.Vidyarthiplus.com

www.Vidyarthiplus.com

148

ADVANTAGES It is a structure that allows data to be passed from one process to another whilst making the most efficient use of memory.

6. DOUBLE ENDED QUEUES(DEQUE ADT)

Write an algorithm to perform the four operations in a double ended queue that is implemented as an array May/June 2014 What is a circular queue and double ended queue? Give suitable examples to diffferentiate them Nov/Dec 2015 ―Double-Ended Queue‖ is a queue-like linear data structure that supports insertion and deletion of items at both ends of the queue unlike circular queue where the insertion is done at the front end only and deletion is done at the rear end only. This differs from the queue abstract data type or First-In-First-Out List (FIFO), where elements can only be added to one end and removed from the other. This general data class has some possible sub-types:

An input-restricted deque is one where deletion can be made from both ends, but insertion can be made at one end only.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

149

An output-restricted deque is one where insertion can be made at both ends, but deletion can be made from one end only.

/* The following program in C, implements the logic of Double ended queue, in which the insertion & deletion from end as well as starting is allowed(circular array) */

#include<stdio.h> #include<stdlib.h> #include<conio.h> #define SIZE 100 int queue[SIZE]; int F = -1; int R = -1; /* To insert element in the rear of Double ended queue*/ void insert_r(int x) { if(F == (R+1)%SIZE) { printf("\nQueue Overflow"); } else if(R == -1) { F = 0; R = 0; queue[R] = x; } else

www.Vidyarthiplus.com

www.Vidyarthiplus.com

150

{ R = (R+1) %SIZE; queue[R] = x; } } /* To insert element in the front of Double ended queue*/ void insert_f(int x) { if(F == (R+1)%SIZE) { printf("\nQueue Overflow"); } else if(R == -1) { F = 0; R = 0; queue[R] = x; } else { F = (F+SIZE-1) %SIZE; queue[F] = x; } } /* To delete element in the rear of Double ended queue*/ int delete_r() { int x; if(F == -1) { printf("\nQueue Underflow"); } else if(F == R) { x = queue[F]; F = -1; R = -1; } else { x = queue[R]; R = (R+SIZE-1)%SIZE; } return x;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

151

} /* To delete element in the front of Double ended queue*/ int delete_f() { int x; if(F == -1) { printf("\nQueue Underflow"); } else if(F == R) { x = queue[F]; F = -1; R = -1; } else { x = queue[F]; F = (F+1)%SIZE; } return x; } void main() { char choice; int x; while(1) { printf("1: Insert From Front\n"); printf("2: Insert From Rear\n"); printf("3: Delete From Front\n"); printf("4: Delete From Rear\n"); printf("5: Exit Program\n"); printf("Enter Your Choice:"); choice = getche(); switch(choice) { case '1': printf("\nEnter Integer Data :"); scanf("%d",&x); insert_f(x); break;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

152

case '2': printf("\nEnter Integer Data :"); scanf("%d",&x); insert_r(x); break; case '3': printf("\nDeleted Data From Front End: %d",delete_f()); break; case '4': printf("\nDeleted Data From Back End: %d",delete_r()); break; case '5': exit(0); break; } } } Applications: A nice application of the deque is storing a web browser's history. Recently visited URLs are added to the front of the deque, and the URL at the back of the deque is removed after some specified number of insertions at the front. Another common application of the deque is storing a software application's list of undo operations.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

153

UNIT-V SORTING, SEARCHING AND HASH TECHNIQUES

PART A 1. What is meant by Sorting and searching? Sorting and searching are fundamentals operations in computer science. Sorting refers to the operation of arranging data in some given order, ascending or descending. Searching refers to the operation of searching the particular record from the existing information. 2. Differentiate Internal and External sorting Nov/Dec 2014 What is meant by internal and external sorting? Give examples April/May 2015 Internal Sorting External Sorting Internal Sorting takes place in the main memory of a computer.

This sorting requires auxiliary storage to store the data which is not fit into the main memory..

Internal sorting methods are applied to small collection of data.

External sorting methods are applied only when the number of data elements to be sorted is too large.

Internal sorting takes small input External sorting can take as much as large input

Example: Insertion sort,Bubble sort Example: Merge sort,Multiway merge 3. Define Bubble sort. Bubble sort is the one of the easiest sorting method. In this method each data item is compared with its neighbor and if it is an descending sorting , then the bigger number is moved to the top of all. The smaller numbers are slowly moved to the bottom position, hence it is also called as the exchange sort. Time complexity:O(n2) 4. Compare linear search and binary search? Nov/Dec 2015 State the applications of linear and binary search techniques. April/May 2015 What is the time complexity of binary search? May/June 2014

In Linear Search the list is searched sequentially and the position is returned if the key element to be searched is available in the list, otherwise -1 is returned. The search in Linear Search starts at the beginning of an array and move to the end, testing for a match at each

Sorting algorithms: Insertion sort - Selection sort - Shell sort - Bubble sort - Quick sort – Merge sort -Radix sort – Searching: Linear search –Binary Search Hashing: Hash Functions – Separate Chaining – Open Addressing – Rehashing – Extendible Hashing

www.Vidyarthiplus.com

www.Vidyarthiplus.com

154

item. It is useful in applications where the data is not sorted, the elements are searched one by one till the element is found. Time complexity:O(n) Binary search is simpler and faster than linear search. Binary search the array to be searched is divided into two parts, one of which is ignored as it will not contain the required element. One essential condition for the binary search is that the array which is to be searched, should be arranged in ascending order. It is efficient when compared to linear search and useful in applications where the data is sorted. Time complexity:O(logn) 5. Define merge sort. Merge sort is based on divide and conquer method. It takes the list to be stored and divide it in half to create two unsorted lists. The two unsorted lists are then sorted and merge to get a sorted list. Time complexity:O(nlogn) 6. Define insertion sort & selection sort. Insertion sort: Successive element in the array to be sorted and inserted into its proper place with respect to the other already sorted element. We start with second element and put it in its correct place, so that the first and second elements of the array are in order. Time complexity:O(n2) Selection sort: It basically determines the minimum or maximum of the lists and swaps it with the element at the index where it is supposed to be. The process is repeated such that the nth minimum or maximum element is swapped with the element at the n-1th index of the list. Time complexity:O(n2) 7. What is the basic idea of shell sort? Shell sort works by comparing elements that are distant rather than adjacent elements in an array or list where adjacent elements are compared. Shell sort uses an increment sequence. The increment size is reduced after each pass until increment size is 1. Time complexity:O(n3/2) 8. What is the purpose of quick sort and advantage? The purpose of the quick sort is to move a data item(pivot) in the correct direction, just enough for to reach its final place in the array. Quick sort reduces unnecessary swaps and moves an item to a greater distance, in one move. The quicksort algorithm is fastest when the median of the array is chosen as the pivot value. That is because the resulting partitions are of very similar size. Each partition splits itself in two and thus the base case is reached very quickly and it follows the divide and conquer strategy. Time complexity:O(nlogn)

Advantages: 1.This is faster sorting method among all.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

155

2. Its efficiency is also relatively good.

3. It requires relatively small amount of memory. 9. Define radix sort? Radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value. The elements are sorted by processing its individual digits either by least significant digit(LSD) method or by most significant digit(MSD) method. Time complexity:O(nk) where n is the k is the number of digits

10. List out the different types of hashing functions? The different types of hashing functions are, The division method The mid square method The folding method Digit analysis 11. Define hashing. Hashing is the transformation of a string of characters into a usually shorter fixed-length value or key that represents the original string. Hashing is used to index and retrieve items in a database because it is faster to find the item using the shorter hashed key than to find it using the original value. It is also used in many encryption algorithms. The hash function is used to index the original value or key and then used later each time the data associated with the value or key is to be retrieved. 12. Define Open addressing hashing. Nov/Dec 2012 In this technique a block of memory space is reserved for storing the hash keys. In case of a collision, alternative locations are accessed until an empty location is found. For example H1(x),H2(X,H3(X) etc. are computed one after the other until a vacant slot is found. 13. What are the types of hashing? Static Hashing

A bucket is a unit of storage containing one or more records

The file blocks are divided into M equal-sized buckets, numbered bucket0, bucket1... bucket M-1.Typically, a bucket corresponds to one (or a fixed number of) disk block. In a hash file organization we obtain the bucket of a record directly from its search- key value using a hash Function, h (K). The record with hash key value K is stored in bucket, where i=h(K). Hash function is used to locate records for access, insertion as well as deletion.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

156

Dynamic Hashing

Good for database that grows and shrinks in size Allows the hash function to be modified dynamically Extendable hashing – one form of dynamic hashing

14. What is Rehashing? Nov/Dec 2015 When the hash table becomes too full in open addressing hashing the successive insert operations may consume more time to complete. To overcome this situation, the rehashing technique is used. A bigger memory cluster approximately twice the size is reserved as soon as the original hash table becomes too full. 15. Define Extendible Hashing. Nov/Dec 2014 It is one of the methods of hashing in which it performs all the insertion, deletion and searching process in a fast manner on large databases. In this method, data can be stored as a binary format(0‘s and 1‘s) to the disk block. The entire block of data is divided into a number

of disk block and each block is limited to store only m records. The major problem with other hashing techniques is that collisions could cause several blocks to be examined during a find, even for a well distributed hash table. Expensive rehashing step has to be performed which requires O(n) disk accesses. But extendible hashing allows to find the data in two disk accesses. Insertion requires few disk accesses.

PART B

1. SHELL SORT AND INSERTION SORT

Sort the given integers and show the intermediate results using shell sort 35,12,14,9,15,45,32,95,40,5 Write C code to sort an integer array using shell sort April/May 2015 Shell sort: Shell sort, also known as the diminishing increment sort, is one of the oldest sorting algorithms, named after its inventor Donald. L. Shell (1959). • Shell sort works by comparing elements that are distant rather than adjacent elements in an array or list. • Shell sort uses a sequence h1, h2, …, ht called the increment sequence. It can assume values from a set (1,3,5,19,41…). The increment sequence is chosen within the following

range. ht=N/2, hk=hk+1/2, h1=1 35 12 14 9 15 45 32 95 40 5

Given the input the array has to be sorted using shell sort

www.Vidyarthiplus.com

www.Vidyarthiplus.com

157

Steps: 1. Sort with increment 5 35 12 14 9 15 45 32 95 40 5

5 and 15 are swapped 2. Sort with increment 3 35 12 14 9 5 45 32 95 40 15

Result after sorting: 9 5 14 15 12 40 32 95 45 35

3. Sort with increment 1 9 5 14 15 12 40 32 95 45 35

Result after sorting: 5 9 12 14 15 32 35 40 45 95

Code: #include<stdio.h> #include<conio.h> int main() { int arr[30]; int i,j,k,tmp,num; printf("Enter total no. of elements : "); scanf("%d", &num); for(k=0; k<num; k++) { printf("\nEnter %d number : ",k+1);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

158

scanf("%d",&arr[k]); } for(i=num/2; i>0; i=i/2) { for(j=i; j<num; j++) { tmp=arr[j]; for(k=j; k>=i; k=k-i) { if(tmp<arr[k- i]) { arr[k]=arr[k-i]; } else { break; } arr[k-i]=tmp; } } } printf("\t**** Shell Sorting ****\n"); for(k=0; k<num; k++) printf("%d\t",arr[k]); getch(); return 0; } b. Sort the given integers and show the intermediate results using insertion sort

35,12,14,9,15,45,32,95,40,5. Write C code to sort an integer array using insertion sort

Insertion sort: An insertion sort is one that sorts a set of records by inserting records into an existing sorted file. Based on the technique used by card players to arrange a hand of cards – Player keeps the cards that have been picked up so far in sorted order – When the player picks up a new card, he makes room for the new card and then inserts it in its proper place Given a list of numbers it divides the list into two parts- sorted part and unsorted part. It picks up one element from the front of the unsorted part and then inserts it at its proper position in the sorted part of the list It requires two steps:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

159

1. Scan the sorted part to find the place where the element from unsorted part can be inserted. While scanning shift the elements towards right to create space 2. Insert the element in the created space. 35 12 14 9 15 45 32 95 40 5

Given the input, the array has to be sorted using insertion sort Steps: 1. Take 12 and check with the previous element and insert it in a sorted manner 12 35 14 9 15 45 32 95 40 5

2. Take 14 and place it in the correct position 12 14 35 9 15 45 32 95 40 5

3. Take 9 and place it in the correct position 9 12 14 35 15 45 32 95 40 5

4. Take 15 and place it in the correct position 9 12 14 15 35 45 32 95 40 5

5. Take 45 and 32 & place it in the correct position 9 12 14 15 32 35 45 95 40 5

6. Take 95 and 40 & place it in the correct position 9 12 14 15 32 35 40 45 95 5

7. Remaining elements are in their position except 5. Take 5 & place it in the correct position 5 9 12 14 15 32 35 40 45 95

Finally array is sorted. Code: void main() { int n, arr[30], i, j, t; printf("Enter number of elements\n"); scanf("%d", &n);

www.Vidyarthiplus.com

www.Vidyarthiplus.com

160

printf("Enter %d integers\n", n); for (i = 0; i< n; i++) { scanf("%d", &arr[i]); } for (j = 1 ; j < n; j++) { k=j ; while ( k> 0 && arr[k] < arr[k-1]) { t = arr[k]; arr[k] = arr[k-1]; arr[k-1] = t; k--; } } printf("Sorted list in ascending order:\n"); for (i= 0; i< n; i++) { printf("%d\n", arr[i]); } getch(); }

2. SELECTION SORT AND BUBBLE SORT Sort the given integers and show the intermediate results using selection sort 35,12,14,9,15,45,32,95,40,5 Write C code to sort an integer array using selection sort Selection sort: Selection sort or push-down sort implements selection phase in which either largest or smallest element find from the list and it is swapped to the last or first position respectively. Algorithm: The algorithm works as follows: 1. Find the smallest value in the list 2. Swap it with the value in the first position 3. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time) 35 12 14 9 15 45 32 95 40 5

www.Vidyarthiplus.com

www.Vidyarthiplus.com

161

Given the input, the array has to be sorted using selection sort Steps: 1. Find the minimum and swap with the first position 5 12 14 9 15 45 32 95 40 35

2. Find the next minimum and swap with the second position. Similarly the remaining steps are proceeded. 5 9 14 12 15 45 32 95 40 35

3. 5 9 12 14 15 45 32 95 40 35

4. 5 9 12 14 15 45 32 95 40 35

5. 5 9 12 14 15 45 32 95 40 35

6. 5 9 12 14 15 32 45 95 40 35

7. 5 9 12 14 15 32 35 95 40 45

8. 5 9 12 14 15 32 35 40 95 45

9. 5 9 12 14 15 32 35 40 45 95

Code: void main() { int arr[30],n,i,j,t,small,pos;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

162

printf("Enter number of elements\n"); scanf("%d", &n); printf("Enter %d integers\n", n); for (i = 0; i< n; i++) { scanf("%d", &arr[i]); } for(i=0;i<n-1;i++) { small=arr[i]; pos=i; for(j=i+1;j<N;j++) { if(small>arr[j]) { small=arr[j]; pos=j; } } t=arr[i]; arr[i]=arr[pos]; arr[pos]=t; } printf("The sorted list is…"); for(i=0;i<n;i++) { printf("%d\t",arr[i]); } } b. Sort the given integers and show the intermediate results using bubble sort 35,12,14,9,15,45,32,95,40,5 Write C code to sort an integer array using bubble sort Bubble sort: Bubble sort is a simple sorting algorithm. The algorithm starts at the beginning of the data set. It compares the first two elements, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent elements to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass. Bubble sort can be used to sort a small number of items (where its inefficiency is not a high penalty). Bubble sort may also be efficiently used on a list that is already sorted except for a very small number of elements.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

163

35 12 14 9 15 45 32 95 40 5

Given the input the array has to be sorted using bubble sort Steps: Pass 1: Comparison 1: First two elements are compared and swapped if not in order 12 35 14 9 15 45 32 95 40 5

Comparison 2: Next two elements are compared and swapped if not in order. This proceeds for the remaining elements 12 14 35 9 15 45 32 95 40 5

Comparison 3: 12 14 9 35 15 45 32 95 40 5

Comparison 4: 12 14 9 15 35 45 32 95 40 5

Comparison 5: 12 14 9 15 35 45 32 95 40 5

Comparison 6: 12 14 9 15 35 32 45 95 40 5

Comparison 7: 12 14 9 15 35 32 45 95 40 5

Comparison 8: 12 14 9 15 35 32 45 40 95 5

Comparison 8: 12 14 9 15 35 32 45 40 5 95

Similarly after 2nd pass the result is: 12 9 14 15 32 35 40 5 45 95

www.Vidyarthiplus.com

www.Vidyarthiplus.com

164

After 3rd pass: 9 12 14 15 32 35 5 40 45 95

After 4th pass: 9 12 14 15 32 5 35 40 45 95

After 5th pass: 9 12 14 15 5 32 35 40 45 95

After 6th pass: 9 12 14 5 15 32 35 40 45 95

After 7th pass: 9 12 5 14 15 32 35 40 45 95

After 8th pass: 9 5 12 14 15 32 35 40 45 95

After 9th pass: 5 9 12 14 15 32 35 40 45 95

Code: #include<stdio.h> #include<conio.h> void main( ) { int a[100]; int i, j, temp, n ,flag=1; printf("how many numbers you want to sort : \n"); scanf("%d",&n); printf("Enter %d number values you want to sort\n", n); for(i=0; i<n; i++) scanf("%d",&a[j]); for(i=0;i<n-1&& flag=1 ;i++)//No of passes { flag=0;//It is set if swapping occurs in a pass for(j=0; j<n-1-i;ji++)// No of comparisons {

www.Vidyarthiplus.com

www.Vidyarthiplus.com

165

if(a[j]>a[j+1]) { flag=1; temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } printf ( "\n\nArray after sorting:\n") ; for ( i = 0 ; i <n ; i++ ) printf ( "%d\t", a[i] ) ; getch(); }

3. QUICK SORT, MERGE SORT AND RADIX SORT a. Write an algorithm to sort a set of 'N' numbers using quick sort. Trace the algorithm for the following set of numbers. 88,11,22,44,66,99,32,67,54,10 Nov/Dec 2014/Nov/Dec 2015/May/June 2014 A sorting technique that sequences a list by continuously dividing the list into two parts andmoving the lower items to one side and the higher items to the other. It starts by picking one item in the entire list to serve as a pivot point.The pivot could be the first item or a randomly chosen one. All items that compare lower than the pivot are moved to the left of the pivot; all equal or higher items are moved to the right. It then picks a pivot for the left side and moves those items to left and right of the pivot and continues the pivot picking and dividing until there is only one item left in the group. It then proceeds to the right side and performs the same operation again. Also known as Partition Exchange Sort. Quick sort algorithm applies a special designing technique called Divide and Conquer, The divide-and-conquer strategy solves a problem by: 1. Breaking it into sub problems that are themselves smaller instances of the same type of problem 2. Recursively solving these sub problems 3. Appropriately combining their answers Divide and Conquer in Quick sort 1) Divide: If the sequence S has 2 or more elements, select an element x from S to be your pivot. Any arbitrary element, like the last, will do. Remove all the elements of S and divide them into 3

www.Vidyarthiplus.com

www.Vidyarthiplus.com

166

sequences: L, holds S‘s elements less than x E, holds S‘s elements equal to x G, holds S‘s elements greater than x 2) Recurse: Recursively sort L and G 3) Conquer: Finally, to put elements back into S in order, first inserts the elements of L, then those of E, and those of G. 88 11 22 44 66 99 32 67 54 10

Given the input the array has to be sorted using quick sort Steps: 1. Increment i till the element in the position is greater than pivot

2. Decrement j till the element in j position is less than pivot

3. Swap elements in i and j position

4. Increment i till the element in the position is greater than pivot

5. Decrement j till the element in j position is less than pivot

88 11 22 44 66 99 32 67 54 10

Pivot i=1 i=2 i=3 i=4 i=5

11<88 22<88 44<88 66<88 99>88

88 11 22 44 66 99 32 67 54 10

Pivot i=1 i=2 i=3 i=4 i=5 j=9

10<88

88 11 22 44 66 10 32 67 54 99

Pivot i=1 i=2 i=3 i=4 i=5 j=9

88 11 22 44 66 10 32 67 54 99

Pivot i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 j=9,i=9

32<88 67<88 54<88 99>88

88 11 22 44 66 10 32 67 54 99 Pivot j=8 j=9,i=10

54<88 99>88

www.Vidyarthiplus.com

www.Vidyarthiplus.com

167

6. As i>j swap pivot element and element in j position

7. Now 88 is placed in its position and the same procedure is continued in the left and right sublists of 88. Left sublist of 88 8. Increment i till the element in the position is greater than pivot

9. Decrement j till the element in j position is less than pivot

10. As i < j swap elements in the i and j position

11. Increment i till the element in the position is greater than pivot

12. Decrement j till the element in j position is less than pivot

13. As i>j swap pivot element and element in j position

54 11 22 44 66 10 32 67 88 99

Pivot j=8 i=10

54 11 22 44 66 10 32 67

Pivot i=1 i=2 i=3 i=4 11<54 22<54 44<54 66>54

54 11 22 44 66 10 32 67

Pivot i=1 i=2 i=3 i=4 j=6 j=7

11<54 22<54 44<54 66>54 32<54 67>54

54 11 22 44 32 10 66 67

Pivot i=1 i=2 i=3 i=4 j=6 j=7

54 11 22 44 32 10 66 67

Pivot i=4 i=5 i=6,j=6

32<54 10<54 66>54

54 11 22 44 32 10 66 67

Pivot j=5 i=6,j=6

10<54 66>54

www.Vidyarthiplus.com

www.Vidyarthiplus.com

168

14. Left sublist of 54

Pivot 15. As 10 is in its position the right sublist of 10 is chosen

Pivot 16. As 11 is in its position the right sublist of 11 is chosen

17. As 22 is in its position the right sublist of 22 is chosen

18. i cannot be incremented as there are no further elements in the sublist.

19. As i=j, swap pivot and element in j position

Finally the sorted list is as follows: 10 11 22 32 44 54 66 67 88 99

10 11 22 44 32 54 66 67

Pivot j=5 i=6

10 11 22 44 32

11 22 44 32

22 44 32

44 32

Pivot i=4

32<44

44 32

Pivot i=4

j=4 32<44

32 44

www.Vidyarthiplus.com

www.Vidyarthiplus.com

169

Code: #include<stdio.h> #include<conio.h> void qsort(int arr[20], int left, int right); int main() { int arr[30]; int i,n; printf("Enter total no. of the elements : "); scanf("%d",&n); printf("Enter total %d elements : \n",size); for(i=0; i<n; i++) scanf("%d",&arr[i]); qsort(arr,0,n-1); printf("Quick sorted elements are as : \n"); for(i=0; i<n; i++) printf("%d\t",arr[i]); getch(); return 0; } void qsort(int arr[20], int left, int right) { int i,j,pivot,tmp; if(left<right) { pivot=left; i=left+1; j=right; while(i<j) { while(arr[i]<=arr[pivot] && i<right) i++; while(arr[j]>arr[pivot]) j--; if(i<j) { tmp=arr[i]; arr[i]=arr[j]; arr[j]=tmp; } } tmp=arr[pivot]; arr[pivot]=arr[j]; arr[j]=tmp;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

170

qsort(arr,left,j-1); qsort(arr,j+1,right); } } b. Write an algorithm to sort a set of 'N' numbers using Merge sort. Trace the algorithm for the following set of numbers. 88,11,22,44,66,99,32,67,54,10 Nov/Dec 2015 The Merge sort algorithm is based on divide and conquers strategy. First, the sequence to be sorted is decomposed into two halves ( Divide ). Each half is sorted independently ( Conquer ). Then the two sorted halves are merged to a sorted sequence ( Combine ).

88 11 22 44 66 99 32 67 54 10

Given the input, the array has to be sorted using quick sort Steps: 1. Divide Step

88 11 22 44 66

99 32 67 54 10

88 11 22 44 66 99 32 67 54 10

44 66 88 11 22 99 32 67 54 10

99 32 88 11

www.Vidyarthiplus.com

www.Vidyarthiplus.com

171

2. Conquer Step: (Elements are merged in a sorted manner)

Code: #include<conio.h> void merge(int [],int ,int ,int ); void part(int [],int ,int ); int main() { int arr[30]; int i,size; printf("\n\t------- Merge sorting method -------\n\n"); printf("Enter total no. of elements : "); scanf("%d",&size); for(i=0; i<size; i++) { printf("Enter %d element : ",i+1); scanf("%d",&arr[i]); } part(arr,0,size-1); printf("\n\t------- Merge sorted elements -------\n\n"); for(i=0; i<size; i++) printf("%d ",arr[i]); getch(); return 0; } void part(int arr[],int min,int max) {

88 11 99 32

11 88 22 44 66 32 99 54 10 67

11 22 88 44 66 10 54 32 67 99

11 22 44 66 88 10 32 54 67 99

10 11 22 32 44 54 66 67 88 99

www.Vidyarthiplus.com

www.Vidyarthiplus.com

172

int mid; if(min<max) { mid=(min+max)/2; part(arr,min,mid); part(arr,mid+1,max); merge(arr,min,mid,max); } } void merge(int arr[],int min,int mid,int max) { int tmp[30]; int i,j,k,m; j=min; m=mid+1; for(i=min; j<=mid && m<=max ; i++) { if(arr[j]<=arr[m]) { tmp[i]=arr[j]; j++; } else { tmp[i]=arr[m]; m++; } } if(j>mid) { for(k=m; k<=max; k++) { tmp[i]=arr[k]; i++; } } else { for(k=j; k<=mid; k++) { tmp[i]=arr[k]; i++; } }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

173

for(k=min; k<=max; k++) arr[k]=tmp[k]; } c. Write an algorithm to sort a set of 'N' numbers using Radix sort. Trace the algorithm for the following set of numbers. 88,11,22,44,66,99,32,67,54,10 Radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value Sort by the least significant digit first (counting sort)

Numbers with the same digit go to same bin Reorder all the numbers: the numbers in bin 0 precede the numbers in bin 1, which precede the numbers in bin 2, and so on

Sort by the next least significant digit Continue this process until the numbers have been sorted on all k digits 88 11 22 44 66 99 32 67 54 10

Given the input the array has to be sorted using radix sort Steps: Code: #include<stdio.h> #include<conio.h> radix_sort(int array[], int n); void main() { int array[100],n,i; clrscr(); printf("Enter the number of elements to be sorted: "); scanf("%d",&n); printf("\nEnter the elements to be sorted: \n"); for(i = 0 ; i < n ; i++ ) { printf("\tArray[%d] = ",i); scanf("%d",&array[i]); } printf("\nArray Before Radix Sort:"); //Array Before Radix Sort for(i = 0; i < n; i++) { printf("%d ", array[i]); }

www.Vidyarthiplus.com

www.Vidyarthiplus.com

174

printf("\n"); radix_sort(array,n); printf("\nArray After Radix Sort: "); //Array After Radix Sort for(i = 0; i < n; i++) { printf("%d ", array[i]); } printf("\n"); getch(); } void radix_sort(int arr[], int n) { int bucket[10][5],buck[10],b[10]; int i,j,k,l,num,div,large,passes; div=1; num=0; large=arr[0]; for(i=0 ; i<n ; i++)// Find the largest no { if(arr[i] > large) { large = arr[i]; } while(large > 0)// Get the number of digits of the largest no { num++; large = large/10; } for(passes=0 ; passes<num ; passes++)//For all the digits do the following { for(k=0 ; k<10 ; k++) { buck[k] = 0; } for(i=0 ; i<n ;i++) { l = ((arr[i]/div)%10);//Find the position of the element and insert

www.Vidyarthiplus.com

www.Vidyarthiplus.com

175

bucket[l][buck[l]++] = arr[i]; } i=0; for(k=0 ; k<10 ; k++) { for(j=0 ; j<buck[k] ; j++)// Rearrange the elements in the array { arr[i++] = bucket[k][j]; } } div*=10; } } } Sort by comparing and ordering the one‟s digits:

Digit Sub list 0 10 1 11 2 22 32 3 4 44 54 5 6 66 7 67 8 88 9 99

Combine the numbers in order 10 11 22 32 44 54 66 67 88 99. It is already sorted. Therefore it is not necessary to go for the next significant digit.

4. HASHING & COLLISION RESOLUTION TECHNIQUES What are the different types of hashing techniques and collision resolution techniques? Explain them in detail with example. Nov/Dec 2014/Nov/Dec 2015/May/june 2014 Hash Table: A hash table or hash map is a data structure that uses a hash function to efficiently map certain identifiers or keys (e.g., person names) to associated values (e.g., their telephone

www.Vidyarthiplus.com

www.Vidyarthiplus.com

176

numbers). The hash function is used to transform the key into the index (the hash) of a array element (the slot or bucket) where the corresponding value is to be sought. Hash Function: The hash function will take any item in the collection and return an integer in the range of slot names, between 0 and m-1. Assume that we have the set of integer items 54, 26, 93, 17, 77, and 31. Our first hash function, sometimes referred to as the ―remainder method,‖ simply

takes an item and divides it by the table size, returning the remainder as its hash value (h(item)=item%11) gives all of the hash values for our example items. Note that this remainder method (modulo arithmetic) will typically be present in some form in all hash functions, since the result must be in the range of slot names.

Item Hash Value

54 10

26 4

93 5

17 6

77 0

31 9

Methods of Hashing Function: i) Mid Square Method A key is multiplied by itself and the hash value is obtained by selecting an appropriate number of digits from the middle of the square. The method works best if the table size is a power of two. The same positions in the square must be used for all keys. ii) Module Division (or) Division Remainder Address = Key MOD Table size. While this algorithm works with any table size, a list size that is a prime number produces fewer collisions than other list sizes. iii) Folding Method There are two folding methods that are used, fold shift and fold boundary. In fold shift, the key value is divided into parts whose size matches the size of the required address. Then the left and right parts are shifted and added with the middle part. In fold boundary, the left and right numbers are folded on a fixed boundary between them and the center number.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

177

a. Fold Shift Key: 123456789 123 456 789 --- 1368 ( 1 is discarded) b. Fold Boundary Key: 123456789 321 (digit reversed) 456 987 (digit reversed) --- 1764 ( 1 is discarded) iii) Radix Transformation. In the radix transformation method, the key is transformed into another numeric base. For example, if our key is 23 in base 10, we might convert it to 32 in base 7. We then use the division method and divide the converted key by the table soze and use the remainder as our index. Types of Hashing:

Static Hashing: The hash function maps search key value to a fixed set of locations.

Dynamic Hashing: The hash table can grow to handle more items. The associated hash function must change as the table grows.

Load factor: The load factor of a hash table is the ratio of the number of keys in the table to the size of the hash table. The higher the load factor, the slower the retrieval. COLLISION:

When a memory location filled if another value of the same memory location comes then there occurs collision. When an element is inserted it hashes to the same value as an already inserted element, then it produces collision and need to be resolved. collision resolution becomes a very important part of hashing.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

178

Collision resolution methods: SEPARATE CHAINING (OPEN HASHING) (OR) EXTERNAL HASHING: Separate chaining is a collision resolution technique, in which we can keep the list of all elements that hash to same value. This is called as separate chaining because each hash table element is a separate chain (linked list). Each link list contains the entire element whose keys hash to the same index. All keys that map to the same hash value are kept in a list (or ―bucket‖). For example, The elements are inserted using hash function key%tablesize as shown below i) Insert: 1. Get the element to be inserted into the hash table 2. Define hash function 3. Apply hash function to the element that should be inserted and find the hash value 4. Check whether the list of the hash value is empty or not 5. If the list is empty, then insert an item at the beginning of the list and mark the address field as NULL 6. Otherwise insert the item in the beginning of the list Algorithm for insertion: void insert(element_type key,HASH_TABLE H) { struct list_node * new_cell; LIST L; new_cell=( struct list_node *) malloc(sizeof(struct list_node)); new_cell->element=key; L=H->the _lists[hash(key,H->table size)] L->next=new_cell; new_cell->next = L->next; } ii) Delete: 1. Get the item to be deleted 2. Apply hash function to the item and find out the hash value 3. Choose the corresponding linked list and identify the position of that item in the linked list by traversing it 4. Delete the particular item from the linked list by changing the address field of the previous item to the next item

www.Vidyarthiplus.com

www.Vidyarthiplus.com

179

void delete (element_type key, HASH_TABLE H) { struct list_node * p, new_cell; LIST L; L=H->the _lists[hash(key,H->table size)] P=L->next; while(P!=NULL) { if(p->next->element!=key) p=p->next; p->next=p->next->next; free(p); } } iii) Find 1. Get the search element 2. Apply hash function to the search element and find the hash value 3. Search the element in the corresponding linked list until the end 4. If the element is found, then return the address of the element 5. Otherwise return NULL value. struct list_node* find (element_type key, HASH_TABLE H) { struct list_node * p; LIST L;

www.Vidyarthiplus.com

www.Vidyarthiplus.com

180

L=H->the _lists[hash(key,H->table size)] p=L->next; while(p!=NULL && p->element!=key) { p=p->next; } return p; } Advantages:

Unlimited number of elements Unlimited number of collisions Disadvantages:

Overhead of multiple linked lists The elements are not evenly distributed. Some hash index may have more elements and some may not have anything. It requires pointers which require more memory space. This leads to slow the algorithm down a bit because of the time required to allocate the new cells, and also essentially requires the implementation of second data structure. OPEN ADDRESSING (CLOSED HASHING): Open addressing hashing is an alternating technique for resolving collisions with linked list. In this system if a collision occurs, alternative cells are tried until an empty cell is found. The cell h0(x), h1(x), h2(x)……. are tried in succession, where hi(x) = (Hash (X) + F(i)) mod

Table_Size with F(0) = 0 and F(i)=i. The function F is the collision resolution strategy. This technique is generally used where storage space is large. Arrays are used here as hash tables. The technique of finding the availability of another suitable empty location in the hash table when the calculated hash address is already occupied is known as open Addressing. There are three common collisions resolving strategies 1. Linear probing 2. Quadratic Probing 3. Double hashing Linear probing (using neighboring slots): Probing is the process of a placing in next available empty position in the hash table. The Linear probing method searches for next suitable position in a linear manner(next by next). Since this method searches for the empty position in a linear way, this method is referred as

www.Vidyarthiplus.com

www.Vidyarthiplus.com

181

linear probing. In linear probing for the ith probe, the position to be tried is, (h(k) + i) mod Table_Size, where ‗f‘ is a linear function of i, F(i)=i. This amounts to trying cells sequentially

in search of an empty cell.

Algorithm for linear probing: 1. Apply hash function on the key value and get the address of the location. 2. If the location is free, then i) Store the key value at this location, else ii) Check the remaining locations of the table one after the other till an empty location is reached. Wrap around on the table can be used. When we reach the end of the table, start looking again from the beginning. iii) Store the key in this empty location. 3.End Advantages of linear probing: 1. It does not require pointers. 2. It is very simpler to implement. Disadvantages of linear probing: 1. It forms clusters, which degrades the performance of the hash table for sorting and retrieving data. It is known as primary clustering meaning that any key that hashes into the cluster will require several attempts to resolve the collision and then it will add to the cluster. 2. If any collision occur when the hash table becomes half full, it is difficult to find an

www.Vidyarthiplus.com

www.Vidyarthiplus.com

182

empty location in the hash table and hence the insertion process takes a longer time. As shown in the above figure, the elements are inserted in the next adjacent possible position if not able to insert elements in the index calculated. Quadratic probing: Better behavior is usually obtained with quadratic probing, where the secondary hash function depends on the re-hash index. In this technique, F(i) is a quadratic function of i. That means, alternative locations are searched as a quadratic function. Thus F(i)=i2 or hi(x)=(hash(x) + i2) % n • Probe sequence: h0(k) = h(k) mod TableSize h1(k) = (h(k) + 1) mod TableSize h2(k) = (h(k) + 4) mod TableSize h3(k) = (h(k) + 9) mod TableSize hi(k) = (h(k) + i2) mod TableSize Quadratic probing does not suffer from primary clustering but it shows secondary clustering. However, secondary clustering is not nearly as severe as the clustering shown by linear probes. However, the collision elements are stored in slots to which other key values map direct ly, thus the potential for multiple collisions increases as the table becomes full. To insert 18,89,21,58,68 using Quadratic probing the following steps are followed:

www.Vidyarthiplus.com

www.Vidyarthiplus.com

183

Double hashing: To overcome the situation of secondary clustering of quadratic probing, Double hashing is used. Double hashing uses the idea of applying a second hash function will be the number of positions from the point of collision to insert. F(i)=i*hash2(k) Or hi(k)= (hash(k) +i *hash2(k))%TableSize. h0(k) = h(k) mod TableSize h1(k) = (h(k) + 1*h2(k)) mod TableSize h2(k) = (h(k) + 2*h2(k)) mod TableSize h3(k) = (h(k) + 3*h2(k)) mod TableSize hi(k) = (h(k) + i* h2(k)) mod TableSize A popular second hash function is Hash2(X)=R-(X mod R) where R is a prime number that is smaller than the size of the table. To insert 18,89,21,58,68 using Double hashing the following steps are followed: To insert 18, 18%10=8 To insert 89, 89%10=9 To insert 21, 21%10=1 To insert 58, 58%10=8 Collision occurs. Therefore (8+1*(7-58%7) )%10=3 Hash2(58)=7-58%7=5 To insert 68, 68%10=8 Collision occurs. Therefore (8+1*(7-68%7))%10=0

5. LINEAR SEARCH AND BINARY SEARCH

Write C code to perform a. Linear Search Linear search or sequential search is a method for finding a particular value in a list that consists of checking every one of its elements, one at a time and in sequence, until the desired one is found. Linear search is the simplest search algorithm; it is a special case of brute-force search. Code: #include<stdio.h> main() {

0 68 1 21 2 3 58 4 5 6 7 8 18 9 89

www.Vidyarthiplus.com

www.Vidyarthiplus.com

184

int array[100], search, c, number; printf("Enter the number of elements in array\n"); scanf("%d",&number); printf("Enter %d numbers\n", number); for ( c = 0 ; c < number ; c++ ) scanf("%d",&array[c]); printf("Enter the number to search\n"); scanf("%d",&search); for ( c = 0 ; c < number ; c++ ) { if ( array[c] == search ) /* if required element found */ { printf("%d is present at location %d.\n", search, c+1); break; } } if ( c == number ) printf("%d is not present in array.\n", search); return 0; } Output: Enter the number of elements in the array 5 Enter 5 numbers 20 32 12 15 34 Enter the number to search 12 12 is present at location 3

20 32 12 15 34 0 1 2 3 4

For searching 12 in the array, search begins from index 0 sequentially and as the element is found in index 2 search is completed successfully b. Binary search April/May 2015 A dichotomizing search in which the set of items to be searched is divided at each step into two equal, or nearly equal, parts, Also known as binary chop. The most efficient method used for searching a sequential table is binary search. It doesn‘t need any primary or secondary index.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

185

A binary search or half-interval search algorithm finds the position of a specified value (the input "key") within a sorted array. At each stage, the algorithm compares the input key value with the key value of the middle element of the array. If the keys match, then a matching element has been found so its index, or position, is returned. Otherwise, if the sought key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right. If the remaining array to be searched is reduced to zero, then the key cannot be found in the array and a special "Not found" indication is returned. Suppose we have an array of 7 elements

9 10 25 30 40 45 70

0 1 2 3 4 5 6

Following steps are generated if we binary search a data =45 from the above array Step 1: LB UB

9 10 25 30 40 45 70

0 1 2 3 4 5 6

LB=0; UB=6 Mid=(0+6)/2 = 3 A[3] = 30 Step 2: Since A[3] < ITEM ie., 30 <45 reinitalise LB, UB and mid LB UB

9 10 25 30 40 45 70

0 1 2 3 4 5 6

LB=3; UB=6 Mid=(3+6)/2 = 4 A[3] = 40 Step3: Since A[4] < ITEM ie., 40 <45 reinitalise LB, UB and mid LB UB

9 10 25 30 40 45 70

0 1 2 3 4 5 6

LB=4; UB=6 Mid=(4+6)/2 = 5 A[5] = 45 Step 4: Since A[5] == ITEM 45 = 45 , search is successful. Code: #include<stdio.h> #include<conio.h> void main()

www.Vidyarthiplus.com

www.Vidyarthiplus.com

186

{ int a[10],i,n,m,c=0,l,u,mid; printf("Enter the size of an array: "); scanf("%d",&n); printf("Enter the elements in ascending order: "); for(i=0;i<n;i++){ scanf("%d",&a[i]); } printf("Enter the number to search: "); scanf("%d",&m); l=0,u=n-1; while(l<=u) { mid=(l+u)/2; if(m==a[mid]) { c=1; break; } else if(m<a[mid]) { u=mid-1; } else l=mid+1; } if(c==0) printf("The number is not found."); else printf("The number is present in location %d\n.",mid+1); getch(); } Output: Enter the size of an array 5 Enter the elements in ascending order 12 13 16 20 32 Enter the number to search 20 The number is present in location 4

www.Vidyarthiplus.com

www.Vidyarthiplus.com

187

6.REHASHING AND EXTENDIBLE HASHING Write notes on i. Rehashing April/May 2015 When the hash table becomes too full in open addressing hashing, the successive insert operations may consume more time to complete. To overcome this situation the rehashing technique is used. In the rehashing technique a bigger memory cluster approximately twice the size is reserved as soon as the original hash table becomes too full. Then the elements are rehashed into a new cluster. Thus h1(k) rehashes to h2(k). If h1(k)=k mod n where n is a prime number. Then h2(k)=k mod m where m is a prime number approximately twice as large as n. Rehashing is implemented whenever: 1. Insert operation fails 2. Cluster becomes half full 3. When the table reaches a certain load factor Example: The elements to be inserted in the table of size 7 are 13, 15, 24 and 6. They are inserted by applying h(k)= k mod 7 using linear probing as follows: 13%7=6 15%7=1 24%7=3 6%7=6(Using linear probing it is inserted in 0) Now 23 is inserted into the table, as the table is more than half full, a new table is created which is double the size. The new table size is 17 as it is the first prime which is twice as large as the old table size. The elements are reinserted using the hash function h(k)=k mod 17. 23 and 24 are inserted using linear probing.

0 6 1 15 2 3 24 4 5 6 13

www.Vidyarthiplus.com

www.Vidyarthiplus.com

188

ii. Extendible hashing It is one of the methods of hashing in which it performs all the insertion, deletion and searching process in a fast manner on large databases. In this method, data can be stored as a binary format(0‘s and 1‘s) to the disk block. The entire block of data is divided into a number of disk blocks and each block is limited to store only m records. The major problem with other hashing techniques is that collisions could cause several blocks to be examined during a find, even for a well distributed hash table. Expensive rehashing step has to be performed which requires O(n) disk accesses. But extendible hashing allows to find the data in two disk accesses. Insertion requires few disk accesses. Example: Let us consider each data that consists of several six bit integers. The root of the tree contains four pointers determined by the leading two bits of data. Each leaf has up to M=4 elements and the elements are identified with the first two bits. For example all the elements which have the first two bits 00 are kept into first block, the elements 01 is kept into second block and so on. Local Depth(LD): Value associated with the leaves indicating the number of bits used to identify their group

0 1

2 3 4 5 6 6 7

23 8 24 9 10

11

12

13

13 14

15

15 16

Linear Probing is used

www.Vidyarthiplus.com

www.Vidyarthiplus.com

189

Global depth(GD): Value associated with the root indicating the number of bits to determine the leaf The directory is extended for the following reasons: 1. If the insertion of the new element is causing overflow situation in a bucket then compare its local depth with the global depth 2. If the local depth is less than the global depth then add a new bucket, adjust the pointers and redistribute the elements 3. If the local depth is equal to the global depth then expand the directory GD:2 Insertion: Assume that we want to insert the key 100100 into the table which is given in figure above. This would go into the third leaf, because the the first two bits are 10. But the third leaf leaf is already full there is no room. We thus split this leaf into two leaves, the elements that starts with 100 are placed into one block and 101 is placed into another block. Now all the elements are determined by the first three bits. This requires increasing the directory size to 3. These changes are reflected in the following figure. GD: 3

00 01 10 11

000 001 010 011 100 101 110 111

LD:2 000100 001000 001010 001011

LD:2 010100 011000

LD:2 100000 101000 101100 101110

LD:2 111000 111001

LD:2 000100 001000 001010 001011

LD:3 101000 101100 101110

LD:3 100000 100100

LD:2 010100 011000

LD:2 111000 111001

www.Vidyarthiplus.com

www.Vidyarthiplus.com

190

If the key 000000 is now inserted then the first leaf is split generating two leaves. The result is as follows: GD:3

Advantages: It provides quick access times for insert and find operations

There is possibility of duplicate keys

7. PROBLEM IN HASHING Given input {4371, 1323, 6173, 4199, 4344, 9679, 1989} and a hash function h(x)=x mod 10. Show the result in: May/June 2012 1. Separate Chaining hash table: 2. Open addressing hash table using linear probing 3. Open addressing hash table using quadratic probing 4 Open addressing hash table with second hash function h2(x)=7-{x mod 7} 1. Separate Chaining hash table: h(4371)=4371 mod 10=1 h(1323)=1323 mod 10=3 h(6173)=6173 mod 10=3 h(4199)=4199 mod 10=9 h(4344)=4344 mod 10=4 h(9679)=9679 mod 10=9 h(1989)=1989 mod 10=9

000 001 010 011 100 101 110 111

LD:3 000000 000100

LD:3 101000 101100 101110

LD:3 100000 100100

LD:2 010100 011000

LD:2 111000 111001

LD:3 001000 001010 001011

www.Vidyarthiplus.com

www.Vidyarthiplus.com

191

2. Open addressing hash table using linear probing: h(4371)=4371 mod 10=1 h(1323)=1323 mod 10=3 h(6173)=6173 mod 10=3 Collision occurs and so h(6173)=(3+1) mod 10=4 h(4199)=4199 mod 10=9 h(4344)=4344 mod 10=4 Collision occurs and so h(4344)=(4+1) mod 10=5 h(9679)=9679 mod 10=9 Collision occurs and so h(9679)=(9+1) mod 10=0 h(1989)=1989 mod 10=9 Collision occurs and so h(1989)=(9+1) mod 10=0. Again Collision occurs and so h(1989)=(9+2)mod 10=1. Again collision occurs and so h(1989)=(9+3)mod 10=2

0 9679 1 4371 2 1989 3 1323 4 6173 5 4344 6 7 8 9 4199

0

1

2

3

4

5

6

7

8

9

4371

1323

4199 1989 9679

4344

6173

www.Vidyarthiplus.com

www.Vidyarthiplus.com

192

3. Open addressing hash table using quadratic probing: h(4371)=4371 mod 10=1 h(1323)=1323 mod 10=3 h(6173)=6173 mod 10=3 Collision occurs and so h(6173)=(3+1*1) mod 10=4 h(4199)=4199 mod 10=9 h(4344)=4344 mod 10=4 Collision occurs and so h(4344)=(4+1*1) mod 10=5 h(9679)=9679 mod 10=9 Collision occurs and so h(9679)=(9+1*1) mod 10=0 h(1989)=1989 mod 10=9 Collision occurs and so h(1989)=(9+1*1) mod 10=0. Again Collision occurs and so h(1989)=(9+2*2)mod 10=3. Again collision occurs and so h(1989)=(9+3*3)mod 10=8

0 9679 1 4371 2 3 1323 4 6173 5 4344 6 7 8 1989 9 4199

4. Open addressing hash table with second hash function h2(x)=7-{x mod 7} h(4371)=4371 mod 10=1 h(1323)=1323 mod 10=3 h(6173)=6173 mod 10=3 Collision occurs and so h(6173)=(3+1*(7-(6173 mod 7))) mod 10=4 h(4199)=4199 mod 10=9 h(4344)=4344 mod 10=4 Collision occurs and so h(4344)=(4+1*(7-(4344 mod 7))) mod 10=7 h(9679)=9679 mod 10=9 Collision occurs and so h(9679)=(9+1*(7-(9679 mod 7))) mod 10=1. Again collision occurs and so h(9679) )=(9+2*(7-(9679 mod 7))) mod 10=3. Again collision occurs and so h(9679) )=(9+3*(7-(9679 mod 7))) mod 10=5. h(1989)=1989 mod 10=9 Collision occurs and so h(1989)=(9+1*(7-(1989 mod 7))) mod 10=5. Again Collision occurs and so h(1989)=(9+2*(7-(1989 mod 7)))mod 10=1. Again collision occurs and so h(1989)=(9+3*(7-(1989 mod 7)))mod 10=7.Again collision occurs and so h(1989)=(9+4*(7-

www.Vidyarthiplus.com

www.Vidyarthiplus.com

193

(1989 mod 7)))mod 10=3. Again collision occurs and so h(1989)=(9+5*(7-(1989 mod 7)))mod 10=9. Again collision occurs and so h(1989)=(9+6*(7-(1989 mod 7)))mod 10=5. Again collision occurs and so h(1989)=(9+7*(7-(1989 mod 7)))mod 10=5. The Cycle continues. It cannot be assigned.

0 1 4371 2 3 1323 4 6173 5 9679 6 7 4344 8 9 4199

www.Vidyarthiplus.com

www.Vidyarthiplus.com

194

INDUSTRIAL /PRACTICAL CONNECTIVITY OF THE SUBJECT

In networking, the following are the applications of data structures Stacks -

E.g., Conversion of recursive routines to non-recursion

Queues - Managing IDs

Linked lists are more common than arrays to maintain stacks or queues- To have flexibility in the number of entries and for memory efficiency

Hashing- Used when order is not important but Lookup needs to be fast and it is used for MAC table

Sorting- E.g., to display list of users in a show command E.g., to show the forwarding table used for switching

In Operating systems also data structures are used to maintain pagetable, process control block,inode etc.. To debug the code involving the algorithm one should know the Data structure &

Algorithm. Data structures & Algorithms is a basic building block for a software engineer‘s

career in industry

www.Vidyarthiplus.com

www.Vidyarthiplus.com

195

B.E / B.Tech DEGREE EXAMINATION MAY / JUNE 2014.

Second Semester

Computer Science and Engineering

CS6202 – PROGRAMMING AND DATA STRUCTURES – I

(Common to Computer and Communication Engineering and Information Technology)

(Regulation 2013)

Time : Three Hours Maximum : 100 marks

Answer ALL Questions

PART A – (10 x 2 = 20 marks)

1. With the help of the printf function show how c handles functions with variable number of

arguments.

2. Define macro with an example.

3. Give applications in which unions rather than structures can be used.

4. Will the following declaration work. Justify your answer.

struct Student

{

int roll no=12;

float marks[]={55,60,56};

char gender;

};

5. Should arrays or linked list be used for the following types of applications. Justify your

answer.

(a) Many search operations in the sorted list.

(b) Many search operations in the unsorted list.

6. What is the advantage of an ADT?

7. Define double ended Queue.

8. List the applications of a Queue.

9. What is the time complexity of binary search?

10. List sorting algorithm which uses logarithmic time complexity.

PART B – (5 x 16 = 80 marks)

11. (a) (i) Write a C program to find unique elements in an array using a function‖Unique‖.

The function takes the array as parameter and prints the unique elements.

(ii)Write a C program to print fibonocci numbers.

Or

www.Vidyarthiplus.com

www.Vidyarthiplus.com

196

(b) Write a C program to multiply two matrices that are represented as pointers. Use a

function pointer to the function ‗Multiply‘ which takes the two matrices as parameter and

prints the result of the multiplication.

12. (a)(i)Write a C program to read the contents of a file ―in.txt‖ from last to first and write

the contents to ―out.txt‖ (8)

(ii)Write the function prototype and explain how files are manipulated in C. (8)

Or

(b) (i)Create a structure to store a complex number and write function (for addition) that

handle this new structure. (8)

(ii)Write a program to perform the following operations for the customers of a bank using

the concept of structures. (8)

(1) Input the customer details like name, account number and balance.

(2) When a withdrawal transaction is made the balance must change to reflect it.

(3) When a deposit is made the balance must change to reflect it.

13. (a)Write an algorithm to perform insertion and deletion on a doubly linked list.

Or

(b)Consider an array A[1..n]. Given a position, write an algorithm to insert an element in

the array. If the position is empty, the element is inserted easily. If the position is already

occupied the element should be inserted with the minimum number of shifts. (Note: the

elements can shift to the left or right to make the minimum number of moves.)

14. (a)Write an algorithm to convert infix expression to a postfix expression. Trace the

algorithm to convert the infix expression ― (a+b)*c/d+e/f‖ to a postfix expression. Explain

the need for infix and postfix expression.

Or

(b)Write an algorithm to perform the four operations in a double ended queue that is

implemented as an array.

15. (a)Write short notes on hashing and the various collision resolution techniques.

Or

(b)Write an algorithm to sort n numbers using quick sort. Show how the following

numbers are sorted using quick sort: 45, 28, 90, 1, 46, 39, 33, 87.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

197

B.E / B.Tech DEGREE EXAMINATION NOVEMBER / DECEMBER 2014.

Second Semester

Computer Science and Engineering

CS6202 – PROGRAMMING AND DATA STRUCTURES – I

(Common to Computer and Communication Engineering and Information Technology)

(Regulation 2013)

Time : Three Hours Maximum : 100 marks

Answer ALL Questions

PART A – (10 x 2 = 20 marks) 1. Define an Array. Give an Example.

2. Give example on Call by reference.

3. What are the statements used for reading a file?

4. Define the need for union in C.

5. What are abstract data type?

6. What is a circular linked list?

7. Give the application of Stack.

8. What is doubly ended Queue?

9. Define extendible hashing.

10. Differentiate internal and external sorting.

PART B – (5 x 16 = 80 marks)

11. (a) Explain the various control statements in C language with example in detail. (16)

Or

(b) Briefly discuss about

(i)Function with number of arguments.

(ii)Function Pointers (8 + 8)

12. (a) Explain the difference between structure and union with examples. (16)

Or

(b) Explain about file manipulations in detail with suitable program. (16)

13. (a) Describe the creation of a doubly linked list and appending the list. give relevant

coding in C. (16)

Or

(b) Explain the following:

(i) Application of Lists

(ii) Polynomial manipulation (8 + 8 )

www.Vidyarthiplus.com

www.Vidyarthiplus.com

198

14. (a) Discuss about Stack ADT in detail. Explain any one application of Stack. (16)

Or

(b) Explain about Queue ADT in detail. Explain any one application of Queue with

suitable examples. (16)

15. (a) What are the different types of hashing techniques? Explain them in detail with

example. (8 + 8)

Or

(b) Write an algorithm to sort a set of numbers using quick sort. Trace the algorithm for

the following set of numbers. 88, 11, 22, 44, 66, 99, 32, 67, 54, 10 (16)

www.Vidyarthiplus.com

www.Vidyarthiplus.com

199

B.E / B.Tech DEGREE EXAMINATION APRIL / MAY 2015.

Second Semester

Computer Science and Engineering

CS6202 – PROGRAMMING AND DATA STRUCTURES – I

(Common to Information Technology)

(Regulation 2013)

Time : Three Hours Maximum : 100 marks

Answer ALL Questions

PART A – (10 x 2 = 20 marks)

1. Give two examples of C preprocessors with syntax.

2. What are the function pointers in C? Give example.

3. What is the difference between getc() and getchar()? Explain.

4. Explain the syntax as given below:

fread(&my_record,sizeof(struct rec),1,ptr_myfile);

5. Define ADT.

6. What is static linked list? state any two applications of it.

7. Write the syntax of Calloc( ) and Realloc() and mention its application in linked list.

8. Given the prefix for an expression, write its postfix.

-*-+a b c / e f – g / h i

9. What is meant by internal and external sorting? Give four examples of each type.

10. State the applications of linear and binary search techniques.

PART B – (5 x 16 = 80 marks)

11. Write a function theta returns a pointer to the maximum value of an araray of doubles. If

the array is empty, return NULL. (8)

double *maximum(double *a, int size);

(ii) Write a C program to find all the roots of a quadratic equation. (8)

Or

(b) (i) Write a C program using function to check if the given input number is palindrome or

not. (8)

(ii) Explain the C preprocessor operators, each with neat example that is used to create

macros. (8)

12. (a)(i)Write a C program that uses functions to perform the following operations using

structure: (12)

(1) Reading a complex number

www.Vidyarthiplus.com

www.Vidyarthiplus.com

200

(2) Writing a complex number

(3) Addition of two complex numbers

(4) Multiplication of two complex numbers

(ii) State the advantages and disadvantages of structures and unions in C programming. (4)

Or

(b) (i)Perform the following to manipulate file handling using C. (12)

(1) Define an input file handle called input_file, which is a pointer to a type FILE.

(2) Using input_file, open the file results.dat for read mode.

(3) Write C statements which tests to see if input_file has opened the data file successfully. if

not, print an error message and exit the program.

(4) Write a C code which will read a line of characters( terminated by a \n) from input_file

into an character array called buffer. NULL terminate the buffer upon reading a \n.

(5) Close the file associated with input_file.

(ii) Using C programming display the contents of a file on Screen. (4)

13. (a)Write a C Program to perform addition, subtraction and multiplication operations on

polynomial using linked list. (16)

Or

(b)Write C code for circular linked list with create, insert, delete, display operations using

structure pointer. (16)

14.(a) (i) Write C program that checks if expression is correctly parenthesized using stack.

(12)

(ii) Write the function to check for status as Full() or Empty(). (4)

Or

(b) Write C program to implement Queue functions using arrays and Macros. (16)

15.(a)(i)Sort the given integers and show the intermediate results using shell sort. (8)

(ii)Write C Code to sort an integer array using shell sort. (8)

35, 12, 14, 9, 15, 45, 32, 95, 40, 5

Or

(b) (i) Write a C code to perform binary search. (10)

(ii) Explain the rehashing techniques. (6)

www.Vidyarthiplus.com

www.Vidyarthiplus.com

201

B.E / B.Tech DEGREE EXAMINATION NOVEMBER / DECEMBER 2015.

Second Semester

Computer Science and Engineering

CS6202 – PROGRAMMING AND DATA STRUCTURES – I

(Common to Information Technology)

(Regulation 2013)

Time : Three Hours Maximum : 100 marks

Answer ALL Questions

PART A – (10 x 2 = 20 marks)

1. What is recursion? Give example.

2. What will be the output of the following program?

#include<stdio.h>

int main()

{

int i=3;

int *j;

int **k;

j=&i;

k=&j;

printf(―%u%u%d‖,k,*k,**k);

return 0;

}

3. Write a simple program to read the numbers from the file and display the numbers.

4. Compare structure and union.

5. What is Abstract data type? Give example.

6. What is doubly circularly linked list?

7. What is Stack and Queue?

8. Evaluate the following expression using stack.

5 6 2 + * 8 4 / -

9. What is rehashing?

10. Compare linear and binary search.

www.Vidyarthiplus.com

www.Vidyarthiplus.com

202

PART B – (5 x 16 = 80 marks)

11. (a) (i)Explain the various conditional and Control statements in C. (10)

(ii) Write a function which will take an array as an argument along with another

argument – size and based on the passed arguments, it will return average of the

numbers passed through the array. (6)

Or

(b) (i) Write a C program to find the sum of two matrix of the order 2 x 2 using

arrays. Get the elements of the matrix from the user. (10)

(ii) What is function pointer? With example explain how to use function pointer. (6)

12. (a) (i) Create a structure Complex(data members real and imag). Write a function to

add two complex numbers, which will take 2 complex numbers as arguments and

return the complex number. (8)

(ii) Create a structure employee (data members – Name and Salary). Write a function

using array of objects get 5 employees details and display them. (8)

Or

(b)(i) Write a program to read a file and count the number of characters and lines in

it. (8)

(ii) Give the format and use of the following File Handling operations in C: fopen,

fread, fwrite and fseek. (8)

13. (a)(i)Write a function to add two polynomials using linked list. (8)

(ii) Write a routine to merge given two sorted linked lists. (8)

Or

(b) What is meant by doubly linked list? Write the functions to perform the following

operations in a doubly linked list.

(i) Insert after a specified node (6)

(ii) Delete the node at a given position (5)

(iii) Display – from the beginning to end. (5)

14. (a) (i)What is circular queue and double-ended queue? Give suitable examples to

differentiate them. (6)

(ii) Write a routine to implement the circular queue using array. (10)

Or

www.Vidyarthiplus.com

www.Vidyarthiplus.com

203

(b) Discuss any two applications of stack with relevant examples. (16)

15. (a) (i) Sort the following sequence using Quick sort algorithm. Choose the pivot as

median. (8)

38, 81, 22, 48, 13 ,69, 93, 14 ,45, 58 ,79 ,72

(ii) Write a routine for Merge Sort. (8)

Or

(b) Explain the following collision resolution strategies with example.

(i) Separate Chaining (5)

(ii) Linear Probing (5)

(iii) Quadratic Probing (6)

www.Vidyarthiplus.com

www.Vidyarthiplus.com