0% found this document useful (0 votes)
28 views24 pages

DS-1 Removed

The document provides an overview of data structures, including definitions, classifications, and operations. It covers various topics such as dynamic memory allocation in C, string handling functions, and sparse matrices, along with examples and C programs demonstrating basic operations. Additionally, it explains structures, unions, and provides algorithms for converting and evaluating expressions.

Uploaded by

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

DS-1 Removed

The document provides an overview of data structures, including definitions, classifications, and operations. It covers various topics such as dynamic memory allocation in C, string handling functions, and sparse matrices, along with examples and C programs demonstrating basic operations. Additionally, it explains structures, unions, and provides algorithms for converting and evaluating expressions.

Uploaded by

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

DATA STRUCTURE AND APPLICATIONS

MODULE I

1. Define data structure. Explain various operations on data structure (6)


2. Define data structure. Explain the classification of data structure with examples (6)
3. What is structure? Explain the different types of structure with example and give
difference between union and structure (10)
4. List and explain the functions supported in C for dynamic memory allocation (7)
5. Write a c program to demonstrate the basic operations on arrays (8)
6. Explain any four string handling functions supported by c with syntax and example(6)
7. What is Sparse matrix? Write the ADT of Sparse matrix. Give the triplet form of a given
matrix and also find its transpose.(8)

7 0 0 0 0
0 0 9 0 0
3 0 2 0 0
0 0 0 0 5

8. Define Pointers. How to declare and initialize pointers, explain with example(5)
9. Define stack. List and explain the various operations on stacks using arrays with stack
overflow and stack underflow conditions (10)
10. Write a c program to perform push(), pop(), display operations on STACK (10)
11. Develop a C recursive program for Tower of Hanoi problem. Trace it for 3 disks with
schematic call tree diagram (8)
12. Write an algorithm to convert an infix expression to postfix expression and also trace the
same for the expression (a+b)*d+e/f+c
13. Write an algorithm to evaluate postfix expression and apply the same for the given
postfix expression. ABC-D*+E$F+ and assume A=6 B=3 C=2 D=5 E=1 F=7
14. Convert the following infix expression into postfix expression using stack (5)
A + (B*C-(D/E^F)*G)*H
1. Define data structure. Explain various operations on data structure (6)

Definition
“Data structure is defined as the way of storing and organizing data elements by referring its
relationship to each other for efficient usage”

OPERATIONS ON DATA STRUCTURES


The data stored in the data structure can be processed by certain operations.
There are Five basic Operations:
1. Create
 To create a new data structure and allocate memory
2. Insert
 To add a new node into the data structure
 Ex: to add the details of a new student who has recently joined
3. Delete
 To remove an existing node from the data structure
 Ex: to delete the name of a student who has left the course
4. Traverse
 To access each node exactly once so that the nodes of a data structure can be
processed
 Also called as visiting
 Ex: to print the names of all the students in a class
5. Search
 To find the location of a node for a given key value
 The key data may or may not be present in the data structure
 Ex: to find the names of all the students who secured 100 marks in mathematics
Other Operations
1. Sorting
 arranging the data in a particular order i.e Ascending or Descending Order
 Ex: arranging the names of students in a class in an alphabetical order
2. Merging
 two sorted data items can be combined to form a single list of sorted data items.
 Joining two lists

2. Define data structure. Explain the classification of data structure with examples (6)

Definition
“Data structure is defined as the way of storing and organizing data elements by referring its
relationship to each other for efficient usage”
Classification Of Data Structures
Data structures are generally categorized into two classes:
 Primitive data structures
 Non-primitive data structures
Primitive data structure
 The basic data types supported by all programming languages are called Primitive Data
Structure.
 These data structures are directly operated upon by machine level instructions
 Used to represent single values
 Example: integer, float, double, character, String and Boolean.
Non-primitive data structure
 The data structures which are derived by primitive data structures are called Non-
Primitive Data structures.
 It is used to store group of values
 Example: Arrays, Structure, Union, linked lists, stacks, Queue, trees, and graphs.
 Non-primitive data structures can further be classified into two categories:
o Linear data structure
o Non-linear data structure
Linear data structure
 If the elements of a data structure are stored in a linear or sequential order, then it is a
linear data structure.
 It establishes the adjacency relationship between the elements
 Two different Representations
o Sequential Memory Representation
Represents linear relationship between elements by means of sequential
memory locations
Example: Arrays, Queue, Stack
o Linked or Pointer Representation
Represents linear relationship between elements by means of links or
pointer.
Example: Linked List
 Example: Arrays, linked lists, stacks, and queues.
Non-Linear data structure
 If the elements of a data structure are stored based on the Hierarchical relationship
between the data, then it is called non-linear data structure.
 Here adjacency relationship is not maintained between the elements.
 Example: trees and graphs

3. Define structure. Explain the types of structures with examples for each and give
difference between union and structure (10)
Structure
Structure is a user defined data type used to represent a group of data items of different types
using a single name
Structure Declaration
 A structure is declared using the keyword struct followed by the structure name
 All the variables of the structure are declared within the structure
 Each variable name declared within a structure is called a member of the structure
struct structure_name
{
type element 1;
type element 2;
……………..
type element n;
};
Declaration of Structure Variable
struct structure_name var1,var2,…..,var n;

Example
struct student
{
int rollno;
char name[25];
float totalmark;
};
struct student std1;
Declaration of structure with structure variable
It is possible to combine the declaration of structure combination with that of the structure
variables, as shown below.
struct structure_name
{
type element 1;
type element 2;
……………..
type element n;
} var1,var2,…,varn;
Example
struct student
{
int rollno;
char name[25];
float totalmark;
} std1, std2;
Types of Structure
i) Array of structures:
 It is possible to store a structure has an array element. i.e., an array in which each element
is a structure. Just as arrays of any basic type of variable are allowed, so are arrays of a
given type of structure
 Syntax
struct struct_name
{
type element 1;
type element 2;
……………..
type element n;
}array name[size];
 Example:
struct student
{
int rollno;
char name[25];
float totalmark;
} stud[100];
ii) Structure within a structure or Nested Structure
 Nested structure in C is nothing but structure within structure
 One structure can be declared inside other structure as we declare structure members
inside a structure
 Also called Embedded structure
Example
struct dob
{
int day;
int month;
int year;
};
struct student
{
struct dob d;
int rollno;
char name[25];
int totalmark;
}stud[25];
To access the data member
stud[i].d.day
stud[i].d.month
stud[i].d.year

iii) Self Referential structure


A member of structure is pointer to structure itself. It will be represented as a chained or
linked list structure
Example
struct list
{
int data;
struct list *next;
};
Here next is the pointer pointing to the same structure itself. So it is called self-referential
structure.

Compare structure and union


S.No. Structure Union
1. Structure allocates storage space Union allocates one common storage
for all its members separately. space for all its members. Union finds that
which of its member needs high storage
space over other members and allocates
2. Structure occupies higher that much space
memory space Union occupies lower memory space over
3. All members of structure can be structure
accessed at a time Only one member of union can be
4. Example accessed at a time
struct student Example
{ union student
int mark; {
char name[6]; int mark;
double average; char name[6];
}; double average;
Total memory allocation = };
2+6+8=16 Bytes Total memory allocation = 8 Bytes

4. List and explain the functions supported in C for dynamic memory allocation (7)

Dynamic Memory Allocation in C


o Dynamic Memory Allocation refers to the process of allocating or deallocating
memory blocks during a program’s runtime
o This is achieved through the use of four functions
Method Description
malloc() Allocates a single block of requested memory.
calloc() Allocates multiple blocks of requested memory.
realloc() Reallocates the memory occupied by malloc() or calloc() functions.
free() Frees the dynamically allocated memory.
o These functions are declared with <stdlib.h> header file
Malloc()
o malloc() is a function in C that dynamically allocates a block of memory of a
specified size in the heap section during the runtime
o Defined in <stdlib.h> header file
o Syntax
ptr = (cast_type*)malloc(bytesize);
bytesize - size in bytes of the memory block to be allocated.
malloc() - returns a pointer to the first byte of the allocated memory block
If the memory allocation fails, it returns a NULL pointer
o Example
o ptr = (int*)malloc(sizeof(int);
Calloc()
o The calloc() function in C is used to dynamically allocate a contiguous block of
memory in the heap section
o Unlike malloc(), calloc() is used to allocate multiple blocks of memory, typically to
store an array of elements
o Syntax
ptr = (cast_type*)calloc(n,bytesize);
o cast-type is the type of allocated memory
o n is the number of blocks to be allocated
o bytesize is the size of each block in bytes
o Example
o ptr = (float*)calloc(25,sizeof(float);
Realloc()
o Function used to modify/increase/decrease the size of previously allocated memory
block
o If enough size doesn’t exist in memory of current block, new block is allocated for
the full size of reallocation, then copies the existing data to new block and frees the
old block
o Syntax
ptr = realloc(ptr,newsize);
o Example
ptr = reaaloc(ptr,50);
free()
o Function used to free the memory block that are allocated by malloc() and calloc()
and realloc()
o If allocated memory block is no more required then memory can be released using
free() function
o Syntax
free(ptrvariable);
o Example
free(ptr);
5. Write a c program to demonstrate the basic operations on arrays (8)

There are a number of operations that can be performed on arrays. These operations include:
 Inserting an element in an array
 Searching an element in an array
 Deleting an element from an array
 Traversing an array
 Merging two arrays
 Sorting an array in ascending or descending order
C Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[100],key;
int element,i,loc,size,n=0,j=0;
printf("Enter the size of an array\n");
scanf("%d",&size);
printf("Enter %d array elements\n",size);
for(i=0;i<size;i++)
{
scanf("%d",&a[i]);
}
printf("List before Insertion: ");
for(i=0;i<size;i++)
{
printf("%d ",a[i]);
}
printf("\nEnter an element to insert\n");
scanf("%d",&element);
printf("Enter a position to insert an element %d\n",element);
scanf("%d",&loc);
loc--;
for(i=size-1;i>=loc;i--)
{
a[i+1]=a[i];
}
a[loc]=element;
printf("\nDisplay: List after Insertion: ");
for(i=0;i<size+1;i++)
{
printf("%d ",a[i]);
}
printf("\nEnter an element to delete\n");
scanf("%d",&n);
i=0;
for(i=0;i<size;i++)
{
if(a[i]==n)
{
for(j=i;j<(size-1);j++)
{
a[j]=a[j+1];
}
break;
}
}
printf("Disply: List after deletion\n");
for(i=0;i<(size-1);i++)
{
printf("%d",a[i]);
}
printf("\nSearch");
printf("\nEnter the element to search\n");
scanf("%d",&key);
for(i=0;i<size;i++)
{
if(a[i]==key)
printf("key found");

}
return 0;
}

6. Explain any four string handling functions supported by c with syntax and example (6)

1) int strlen(char array)


This function accepts string as parameter and return integer i.e the length of String passed
to it. Example
#include<stdio.h>
#include<string.h>
void main(void)
{
char string[]="welcome";
int len;
len=strlen(string);
printf("length of %s is %d\t", string, len);
}
Output:length of welcome is 7

2) strcpy (Destination string,source string)


Strcpy function accepts 2 strings as parameter,1st one is destination string and 2nd is source
string. This function copies source string to destination string
Example
#include <stdio.h>
#include <string.h>
void main(void)
{
char src[]="goal",dest[15];
strcpy(dest,src);
printf("%s is copied to dest string\t",dest);
}
Output: goal is copied to dest string

3) strcat (Destination string,source string)


 strcat function accepts two strings
 source string is appended to the destination string
Example
#include <stdio.h>
#include <string.h>
void main(void)
{
char src[]="goal",dest[]="achieved";
strcat(src,dest);
printf("concatenated string is %s",src);
}
Output: concatenated string is goalacheived

4) strrev (string)
 strrev function accepts single string as parameter and reverse that string
Example
#include <stdio.h>
#include <string.h>
void main(void)
{
char string[]="goal";
strrev(string);
printf("reverse string is %s",string);
}
Output: reverse string is laog

7. What is a Sparse matrix? Write the ADT of sparse matrix. Give the triple form of a
given matrix and also find its transpose. (8)

7 0 0 0 0
0 0 9 0 0
3 0 2 0 0
0 0 0 0 5

Sparse matrices are those matrices that have the majority of their elements equal to zero. In other
words, the sparse matrix can be defined as the matrix that has a greater number of zero elements than
the non-zero elements.

ADT of Sparse Matrix


Sparse Matrix Triplet form
Total rows: 4
Total Columns: 5
Total non-zero elements: 5
7 0 0 0 0 4 5 5
0 0 9 0 0 0 0 7
1 2 9
3 0 2 0 0
2 0 3
0 0 0 0 5 2 2 2
3 4 5

Transpose of a Matrix
7 0 3 0 5 4 5
0 0 0 0 0 0 7
0 2 3
0 9 2 0 2 1 9
0 0 0 0 2 2 2
4 3 5
0 0 0 5
8. Define Pointers. How to declare and initialize pointers, explain with example(5)

Pointer
o The pointer in C language is a variable which stores the address of another variable
o This variable can be of type int, char, array, function, or any other pointer
Pointer variable Declaration
 Pointers must be declared before they can be used, just like a normal variable
 The syntax of declaring a pointer is to place a * in front of the name
 A pointer variable is associated with data type too
 Synatx
data_type *ptr;
 Example
int *p;
char *pch;
float *psal;
Pointer Variable Initialization
 Initialization of a pointer variable refers to the process of assigning an address to the
pointer variable
 Variable should be declared before initialization
 Syntax
datatype *ptrvar = exp;
 Example
int n;
int *v = &n;
 * symbol indicates the pointer variable
 Example Program
#include<stdio.h>
void main()
{
int a =30, *ptr1;
ptr1 = &a;
printf(“Value of a is %d\n”,*ptr1);
*ptr1 = 100;
printf(“Value of a after initialization is %d\n”,*ptr1);
return;

}
Output
Value of a is 30
Value of a after initialization is 100
9. Define stack. List and explain the various operations on stacks using arrays with
stack overflow and stack underflow conditions (10)
DEFINITION
 A stack is a linear data structure with the restriction that insertions or deletions are limited
at one end called the top of the stack.
 Example
Stack of coins
Bread arranged on a pile
Stack of plates
 Stack Implementation

Array Representation
 Stack can be represented as a linear array where elements are stored in sequential
memory location
 Array representation of the stack is also called Static Implementation
 It needs prior knowledge of maximum number of elements required to be processed
 The integer variable Top which will keep track of the top of the stack as more and more
elements are inserted and deleted from the stack
 Two variables associated with array implementation of stack
o Top
 Retrieves topmost element of the stack
 Top position is where the elements can be pushed or popped
 If top=null, then stack is empty
 If Top=Max-1, then stack is full
o Max
 Maximum size of the stack
 Operations
 The primitive operations performed on the stack are
o PUSH
o POP
o STACK TOP
 PUSH
o Push operation is used to insert a new element into the stack
o Push always inserts new element at the top of the stack
o After insertion the top is incremented by one and the new element becomes the top
of the stack
o Always check whether the stack is full before insertion, otherwise push operation
results in overflow state and the element cannot be added.

o Algorithm
Step 1: IF TOP = MAX-1
PRINT OVERFLOW
Go to step 4
[END OF IF]
Step 2: SET TOP = TOP + 1
Step 3: SET STACK[TOP] = VALUE
Step 4: END
o POP
o Pop operation delete an element from the top of the stack
o After every pop operation the top of the stack is decremented by one.
o Always check whether the stack is empty, otherwise pop operation results in stack
underflow state.
o Algorithm
Step 1: IF TOP = NULL
PRINT UNDERFLOW
Go to step 4
[END OF IF]
Step 2: SET VAL = STACK[TOP]
Step 3: SET TOP = TOP - 1
Step 4: END

o STACK TOP
o Stack top returns the value of the element at the top of the stack
o It does not delete the top element from the stack
o Stack top also results in underflow if the stack is empty

o Algorithm
Step 1: IF TOP = NULL
PRINT STACK IS EMPTY
Goto Step 3
Step 2: RETURN STACK[TOP]
Step 3: END

10. Write a c program to perform push(), pop(), display operations on STACK (10)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define MAX 3 // Altering this value changes size of stack created
int st[MAX], top=-1;
void push(int st[], int val);
int pop(int st[]);
int peek(int st[]);
void display(int st[]);
int main(int argc, char *argv[]) {
int val, option;
do
{
printf("\n *****MAIN MENU*****");
printf("\n 1. PUSH");
printf("\n 2. POP");
printf("\n 3. PEEK");
printf("\n 4. DISPLAY");
printf("\n 5. EXIT");
printf("\n Enter your option: ");
scanf("%d", &option);
switch(option)
{
case 1:
printf("\n Enter the number to be pushed on stack: ");
scanf("%d", &val);
push(st, val);
break;
case 2:
val = pop(st);
if(val != -1)
printf("\n The value deleted from stack is: %d", val);
break;
case 3:
val = peek(st);
if(val != -1)
printf("\n The value stored at top of stack is: %d", val);
break;
case 4:
display(st);
break;
}
}while(option != 5);
return 0;
}
void push(int st[], int val)
{
if(top == MAX-1)
{
printf("\n STACK OVERFLOW");
}
else
{
top++;
st[top] = val;
}
}
int pop(int st[])
{
int val;
if(top == -1)
{
printf("\n STACK UNDERFLOW");
return -1;
}
else
{
val = st[top];
top--;
return val;
}
}
void display(int st[])
{
int i;
if(top == -1)
printf("\n STACK IS EMPTY");
else
{
for(i=top;i>=0;i--)
printf("\n %d",st[i]);
printf("\n"); // Added for formatting purposes
}
}
int peek(int st[])
{
if(top == -1)
{
printf("\n STACK IS EMPTY");
return -1;
}
else
return (st[top]);
}
Output
*****MAIN MENU*****
1. PUSH
2. POP
3. PEEK
4. DISPLAY
5. EXIT
Enter your option : 1
Enter the number to be pushed on stack : 500

11. Develop a C recursive program for Tower of Hanoi problem. Trace it for 3 disks
with schematic call tree diagram (8)

Tower of Hanoi puzzle


 In this puzzle, There are n disks of different sizes that can slide onto any of three pegs
 Initially, all the disks are on the first peg in order of size, the largest on the bottom and the
smallest on top
 The goal is to move all the disks to the third peg, using the second one as an auxiliary, if
necessary. We can move only one disk at a time, and it is forbidden to place a larger disk on
top of a smaller one. The problem has an elegant recursive solution, which is illustrated in
Figure.
1. If n = 1, we move the single disk directly from the source peg to the destination peg.
2. To move n>1 disks from peg 1 to peg 3 (with peg 2 as auxiliary),
o First move recursively n-1 disks from peg 1 to peg 2 (with peg 3 as auxiliary),
o then move the largest disk directly from peg 1 to peg 3, and,
o finally, move recursively n-1 disks from peg 2 to peg 3 (using peg 1 as auxiliary).

C recursive program for Tower of Hanoi problem


#include <stdio.h>
void towerOfHanoi(int n, char src, char dest, char aux)
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c", src, dest);
return;
}
towerOfHanoi(n-1, A, C, B);
printf("\n Move disk %d from rod %c to rod %c", n, A, C);
towerOfHanoi(n-1, B, A, C);
}

int main()
{
int n = 3; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}

Trace it for 3 disks with schematic call tree diagram

12. Write an algorithm to convert an infix expression to postfix expression and also
trace the same for the expression (a+b)*d+e/f+c

INFIX TO POSTFIX CONVERSION


 The main disadvantage of infix notation is that parentheses are used to control the
evaluation of the operators.
 Usually the algebric expressions will be in Infix form. To convert the infix expression into
postfix form, need to know operator precedence and rules for conversion
 Operator Precedence
o Brackets or Parentheses
o Exponentation
o Multiplication/Division
o Addition/Subtraction
Algorithm
Step 1: Add “)” to the end of the infix expression
Step 2: Push “(“ on to the stack
Step 3: Repeat until each character in the infix notation is scanned
 IF a “(“ is encountered, push it on the stack
 IF an operand (whether a digit or a character) is encountered, add it postfix expression.
 IF a “)” is encountered, then
o Repeatedly pop from stack and add it to the postfix expression until a “(“ is
encountered.
o Discard the “(“ . That is, remove the “(“ from stack and do not add it to the
postfix expression
 IF an operator is encountered, then
o Repeatedly pop from stack, the instack operators and add each operator
(popped from the stack) to the postfix expression which has the same
precedence or a higher precedence than incoming operator.
o If instack operator is having lower precedence than the incoming opererator,
keep the instack operator in stack only and push the incoming operator also
into the stack
 [END OF IF]
Step 4: Repeatedly pop from the stack and add it to the postfix expression until the stack is
empty
Step 5: EXIT

(a+b)*d+e/f+c ab+d*ef/+c+

Infix Stack Postfix


(
( ((
a (( a
+ ((+ a
b ((+ ab
) ( ab+
* (* ab+
d (* ab+d
+ (+ ab+d*
e (+ ab+d*e
/ (+/ ab+d*e
f (+/ ab+d*ef
+ (+ ab+d*ef/+
c (+ ab+d*ef/+c
) ab+d*ef/+c+

13. Write an algorithm to evaluate postfix expression and apply the same for the given
postfix expression. ABC-D*+E$F+ and assume A=6 B=3 C=2 D=5 E=1 F=7
Evaluation of a Postfix Expression
 The ease of evaluation acts as the driving force for computers to translate an infix notation
into a postfix notation.
 That is, given an algebraic expression written in infix notation, the computer first converts
the expression into the equivalent postfix notation and then evaluates the postfix
expression.
 Both these tasks—converting the infix notation into postfix notation and evaluating the
postfix expression—make extensive use of stacks as the primary tool.
 Using stacks, any postfix expression can be evaluated very easily.
 Every character of the postfix expression is scanned from left to right.
o If the character encountered is an operand, it is pushed on to the stack.
o If an operator is encountered, then the top two values are popped from the stack
and the operator is applied on these values.
o The result is then pushed on to the stack.
Algorithm

ABC-D*+E$F+ and assume A=6 B=3 C=2 D=5 E=1 F=7


Sub the values
632-5*+1$7+
Symbol Stack Postfix Evaluation
632-5*+1$7+ Push 6
32-5*+1$7+ 6 Push 3
2-5*+1$7+ 63 Push 2
-5*+1$7+ 632 Pop 3 & 2 and subtract and push the
result 1 into stack
5*+1$7+ 61 Push 5
*+1$7+ 615 Pop 5 & 1 and multiply(*) and push
the result into stack
+1$7+ 65 Pop 6 & 5 and perform addition and
push the result into stack
1$7+ 11 Push 1
$7+ 111 Pop 11 and 1 and do exponentiation
And push the result into stack
7+ 11 Push 7
+ 117 Pop 11 and 7 and add and push the
result into stack
18 Output

14. Convert the following infix expression into postfix expression using stack (5)
A + (B*C-(D/E^F)*G)*H

S.No Symbol Stack Postfix Exp


1. A ( A
2. + (+ A
3. ( (+( A
4. B (+( AB
5. * (+(* AB
6. C (+(* ABC
7. - (+(- ABC*
8. ( (+(-( ABC*
9. D (+(-( ABC*D
10. / (+(-(/ ABC*D
11. E (+(-(/ ABC*DE
12. ^ (+(-(/^ ABC*DE
13 F (+(-(/^ ABC*DEF
14. ) (+(-(/^ ABC*DEF
15. * (+(- ABC*DE^/
16 G (+(-* ABC*DEF^/G
17. ) (+ ABC*DEF^/G*-
18. * (+* ABC*DEF^/G*-
19. H (+* ABC*DEF^/G*-H
20 ) ABC*DEF^/G*-H*+

You might also like