DS Lab Manual July 2019 PDF
DS Lab Manual July 2019 PDF
CERTIFICATE
satisfactorily completed the lab exercises prescribed for Data Structures Lab [CSE
2161] of Second Year B. Tech. Degree at MIT, Manipal, in the academic year 2019-20
Date: ……...................................
Signature
Faculty in Charge
CONTENTS
LAB PAGE
TITLE REMARKS
NO. NO.
REFERENCES 92
Course Outcomes
At the end of this course, students will have the
Ability to write code along the lines of the algorithm
Apply the structured approach to solve problems of the type stacks, queues,
trees
Design and develop applications based on studied approaches
Evaluation plan
Internal Assessment Marks : 60%
Page 1 of 105
INSTRUCTIONS TO THE STUDENTS
Pre- Lab Session Instructions
1. Students should carry the Lab Manual Book to every lab session
2. Be in time and adhere to the institution rules and maintain the decorum
3. Must Sign in the log register provided
4. Make sure to occupy the allotted system and answer the attendance
Page 2 of 105
Questions for lab tests and examination are not necessarily limited to the
questions in the manual, but may involve some variations and / or combinations
of the questions.
Page 3 of 105
LAB NO: 1 Date:
Objectives:
Page 4 of 105
Building C programs using sublime:
(i) Click Tools -> Build System -> New Build System and copy paste
the following into curly braces:
{
"cmd" : ["gcc $file_name -o $file_base_name -lm -Wall"],
"selector" : "source.c",
"shell" : true,
"working_dir" : "$file_path"
}
Page 5 of 105
Executing the Program:
1. Open terminal and locate your C program.
Ex: user@user:~$ cd Desktop
2. Run build file by typing:
user@user:~$ ./SN
Page 6 of 105
current directory, alternatively we can specify the absolute or relative
path of the executable file).
cc factorial.c
In this case the executable file is created as a.out by default.
Remember this executable file will be over written when you run the
same command again.
To run the executable go to terminal and type ./a.out
Open the terminal and run the ddd commands (refer ddd video)
Page 7 of 105
Algorithm: Selection Sort
Step 1: Using Pass index variable repeat the steps from first record to last – 1
records and perform all the steps 1to 4.
Step 2: Initialize the minimum index as
min_index = pass.
Step3: Obtain the element with the smallest value.
for(i= pass+1; i < N; i++)
{
if( A[i] < A [min_index])
min_index = i;
}
Step4: Exchange the elements
if(min_index != pass)
{
temp = A[pass];
A[pass] = A[min_index];
A[min_index] = temp;
}
Step5: Stop
0 42 11 11 11 11
1 23 23 23 23 23
2 74 74 74 42 42
3 11 42 42 74 65
4 65 65 65 65 74
Page 8 of 105
File Name: selection_sort_fun.h
#include <stdio.h>
#include "selection_sort_fun.h"
void main()
{
int array[10];
int i, j, n, temp;
printf("Enter the value of n \n");
scanf("%d", &n);
printf("Enter the elements \n");
for (i = 0; i < n; i++)
Page 9 of 105
scanf("%d", &array[i]);
/* Selection sorting begins */
SelectionSort(array, n);
printf("The sorted list is (using selection sort): \n");
for (i = 0; i < n; i++)
printf("%d\t", array[i]);
}
Sample Input and output:
Enter the total no of elements: 5
Enter the elements: 99 20 -12 43 34
The sorted list is (using selection sort): -12 20 34 43 99
3) Implement a C program to read, display and to find the product of two matrices
using functions with suitable parameters. Check for the compatibility of the input
matrices before multiplication. Use dynamic memory allocation and deallocation
functions to allocate memory for the matrices.
4) Find the 2nd largest in a list of numbers using a function (do not sort the list).
Page 10 of 105
unknown size (hint: user will decide at run time). The purpose is to realize the
advantages and disadvantages of using array.
2) Addition of polynomials with two terms: To perform different operations on
polynomial with two terms x, y using 2-D array representations. Operations like
addition and multiplication have to be implemented [ref: J.P Trembly]. If the 2D
array representation is sparse then optimize the memory usage by using suitable
alternative representation.
--------------------------------------------------------------------------------------------------------------------------
Page 11 of 105
LAB NO: 2 Date:
I. SOLVED EXERCISE:
1) Write a C program to implement a ragged array dynamically.
Description: In a ragged array the table pointer points to the first pointer in an array
of pointers. Each array pointer points to a second array of integers, the first element of
which is the number of elements in the list. A sample ragged array structure is shown
below.
[0] [colNum]
table
table [0] -----
colNum
table [1]
colNum+1 elements
- rowNum+1
- elements
-
-
-
table [rowNum]
Page 12 of 105
Algorithm: Construct a ragged array
Step 2: Ask the user for row size and set a variable – rowNum
Step 3: Allocate space for (rowNum+1) pointers as row pointers. The last row pointer
will hold NULL
Step 4: Ask the user for column size and set a variable – colNum
Step 5: Allocate space for (colNum+1) data elements. The first element will hold
value contained in colNum itself.
Step 8: Stop
Program:
#include<stdio.h>
#include<stdlib.h>
int main(){
int rowNum, colNum, i, j;
int **table;
printf("\n enter the number of rows \n");
scanf("%d", &rowNum);
table = (int **) calloc(rowNum+1, sizeof(int *));
for (i = 0; i < rowNum; i++) /* this will tell which row we are in */
{
printf("enter size of %d row", i+1);
Page 13 of 105
scanf("%d", &colNum);
table[i] = (int *) calloc(colNum+1, sizeof(int));
printf("\n enter %d row elements ", i+1);
for (j = 1; j <= colNum; j++)
{
scanf("%d", &table[i][j]);
}
table[i][0] = colNum;
printf("size of row number [%d] = %d", i+1, table[i][0]);
}
table[i] = NULL;
for (i = 0; i < rowNum; i++) /* this will tell which row we are in */
{
printf("displaying %d row elements\n", i+1);
for (j = 0; j <= *table[i]; j++)
{
printf("%5d", table[i][j]);
}
printf("\n");
}
//freeup the memory
for (i = 0; i < rowNum; i++) {
free(table[i]);
}
free(table);
return 0;
}
Page 14 of 105
Sample input and output:
enter the number of rows: 3
enter size of row 1: 4
enter row 1 elements: 10 11 12 13
enter size of row 2: 5
enter row 2 elements: 20 21 22 23 24
enter size of row 3
enter row 3 elements: 30 31 32
displaying
10 11 12 13
20 21 22 23 24
30 31 32
II. LAB EXERCISES :
Note: Pass parameters using pointer to all the following functions and implement
menu-driven program.
1) Write a C program to reverse the elements of an integer array using pointers.
Access the elements of the array using dereference operator.
2) Write a C program to
a) Demonstrate passing pointers to a function.
b) Demonstrate Returning pointer from a function.
c) Using pointer to pointer.
Page 15 of 105
3) Write a C program to find roots of quadratic equation by defining the following
functions.
i. getData(…) to read coefficients.
ii. findRoots(…) to compute roots
iii. printRoots to print the roots
iv. main function to invoke all the above functions.
4) Write a C program to implement the following functions. Use pointers and
dynamic memory management functions.
i. To read one Student object where Student is a structure with name, roll
number and CGPA as the data members
ii. To display one Student object
iii. To sort an array of Student structures according to the roll number.
Page 16 of 105
LAB NO: 3 Date:
SOLVING PROBLEMS USING RECURSION
Objectives:
I. SOLVED EXERCISE:
1) Write a C program to implement binary search
Title: IMPLEMENT BINARY SEARCH
Aim: To understand the working recursive function call and also binary search
technique.
Description Binary search method employs the process of searching for a record
only in half of the list, depending on the comparison between the element to be
searched and the central element in the list. It requires the list to be sorted to perform
such a comparison. It reduces the size of the portion to be searched by half after each
iteration.
Page 17 of 105
Else If key is greater than the mid element, then key can only lie in right half
sub-array after the mid element. So we recur for right half.
Else (x is smaller) recur for the left half until there are no more elements left in
the array.
Step4: stop
Program:
#include <stdio.h>
#include "binary_search_function.h"
void main()
{
int i, pos, a[30],n, item;
printf("Enter number of items:");
scanf("%d",&n);
printf("Enter the elements in ascending order:\n");
for(i=0;i<n;i++)
Page 18 of 105
scanf("%d",&a[i]);
printf("Enter element to be searched:");
scanf("%d",&item);
pos=bin_search(0,n-1,item,a);
if(pos!=-1)
printf("Item found at location %d",pos+1);
else
printf("Item not found");
}
12 23 54 65 88 99
Write a C (menu-driven) program using recursion. Also, write the call tree
indicating call order.
1) To generate Fibonacci series with n terms.
2) To copy one string to another using Recursion.
3) To check whether a given String is Palindrome or not, using Recursion
4) Simulate the working of Tower of Hanoi for n disks. Print the number of moves.
--------------------------------------------------------------------------------------------------------------------------
Page 19 of 105
LAB NO:4 Date:
STACK CONCEPTS
Objectives:
I. SOLVED EXERCISE:
1) Write a c program to check if the given parenthesized expression has properly
matching open and closing parenthesis.
Description: We use a stack to check the expression for matching opening and closing
parenthesis. Here, the expression is scanned from start to end if an opening brace is
encountered then it is pushed on to the stack. When a closing parenthesis is
encountered a pop operation is performed. Ideally, if the number of opening and
closing braces matches, then the stack will be empty after checking the entire
expression.
Algorithm:
Step1: Set balanced to true
Step2: Set symbol to the first character in current expression
Step3: while (there are still more characters AND expression is still balanced)
if (symbol is an opening symbol)
Push symbol onto the stack
else if (symbol is a closing symbol)
if the stack is empty
Page 20 of 105
Set balanced to false
Else
Set openSymbol to the character at the top of the stack
Pop the stack
Set balanced to (symbol matches openSymbol)
Set symbol to next character in current expression
Step4: if (balanced)
Write "Expression is well formed."
else
Write "Expression is not well formed."
Step5: stop
Program:
File name: stack_operations.h
# define MAX 10
# define true 1
# define false 0
/* Structure definition */
typedef struct
{
char item[MAX];
int top;
}stack;
void push(stack *ps,char x);
char pop(stack *ps);
int empty(stack *ps);
/* Push operation */
Page 21 of 105
void push(stack *ps,char x)
{
if (ps->top!=MAX-1)
{
ps->top++;
ps->item[ps->top]=x;
}
}
/* Pop operation */
char pop(stack *ps)
{
if(!empty(ps))
return(ps->item[ps->top--]);
}
Page 22 of 105
#include <stdio.h>
#include <stdlib.h>
#include "stack_operations.h"
void main()
{
char expn[25],c,d;
int i=0;
stack s;
s.top=-1;
printf("\n Enter the expression: ");
gets(expn);
while((c=expn[i++])!='\0')
{
if(c=='(')
push(&s,c);
else
if(c==')')
{
d=pop(&s);
if(d!='(')
{
printf("\n Invalid Expression");
break;
}
}
}
if(empty(&s))
Page 23 of 105
printf("\n Balanced Expression");
else
printf("\n Not a Balanced Expression");
}
Page 24 of 105
2) Convert a given decimal number to binary using stack.
4) Given an array arr with n elements and a number k, k<n. The task is to delete k
elements which are smaller than next element (i.e., we delete arr[i] if arr[i] <
arr[i+1]) or become smaller than next because next element is deleted. Example:
Output: 25 30 40
Explanation: First we delete 10 because it follows arr[i] < arr[i+1]. Then we delete 20
because 25 is moved next to it and it also starts following the condition.
2) Given an array, print the Next Greater Element (NGE) for every element using
stack. The Next Greater Element for an element x is the first greater element on the
right side of x in array. Elements for which no greater element exist, consider next
greater element as -1. For the input array [13, 7, 6, 12}, the next greater elements
for each element are as follows.
Element NGE
13 -1
7 12
6 12
12 -1
---------------------------------------------------------------------------------------------------------------
Page 25 of 105
LAB NO: 5 Date:
STACK APPLICATIONS
Objectives:
I. SOLVED EXERCISE:
Create an empty stack and start scanning the postfix expression from left to right.
When the expression is ended, the value in the stack is the final answer.
Evaluation of a postfix expression using a stack is explained in below example (fig. 2):
Page 26 of 105
File name: eval_postfix_fun.h
#define MAX 20
Page 27 of 105
return(0);
}
return(0);
}
File name:eval_postfix_expr.c
#include<stdio.h>
#include "eval_postfix_fun.h"
int main()
{
stack s;
char x;
int op1,op2,val;
init(&s);
printf("Enter the expression(eg: 59+3*)\nsingle digit operand and operators
only:");
while((x=getchar())!='\n')
{
Page 28 of 105
if(isdigit(x))
push(&s,x-‘0’); /*x-‘0’ for removing the effect of ascii */
else
{
op2=pop(&s);
op1=pop(&s);
val=evaluate(x,op1,op2);
push(&s,val);
}
}
val=pop(&s);
printf("\nvalue of expression=%d",val);
return 0;
}
---------------------------------------------------------------------------------------------------------------
Page 29 of 105
LAB NO: 6 Date:
QUEUE CONCEPTS
Objectives:
I. SOLVED EXERCISE:
1) Implement a queue of integers. Include functions insertq, deleteq and displayq.
Description:
Whenever we perform an insertion the rear pointer is incremented by 1 and front
remains the same. Whenever a deletion is performed the front is incremented by one.
But in real life problem the front pointer will be in the same position the object which
is in the queue shifts to the front. But when we implement a queue in computer the
front moves, this is because if we shift the elements to the front the time complexity
increases. To implement a linear queue we consider two pointers or markers front and
rear. Initial value of front and rear is assumed to be -1
If R== N-1
Return
Page 30 of 105
R= R +1
Q[R ] = val
Step4: If F = -1
then F = 0
Return.
If F = = -1
Return
val = Q[F]
if F > R
else F= F +1
Return(val)
Step5: Stop
Page 31 of 105
Program:
File name: queue_fun.h
#define MAX 20
typedef struct {
int x[MAX];
int front;
int rear;
} queue;
Page 32 of 105
}
int deleteq(queue * q)
{
int x;
if(q->front==-1)
{
printf("\nUnderflow!!!\n");
}
else if(q->front==q->rear)
{
x=q->x[q->front];
q->front=q->rear=-1;
return x;
}
else
{
return q->x[q->front++];
}
}
void displayq(queue q)
{
int i;
if(q.front==-1&&q.rear==-1)
{
printf("\nQueue is Empty!!!");
Page 33 of 105
}
else
{
printf("\nQueue is:\n");
for(i=q.front;i<=q.rear;i++)
{
printf("%d\n",q.x[i]);
}
}
}
int main()
{
queue q;
q.front=-1;
q.rear=-1;
int ch,x,flag=1;
while(flag)
{
printf("\n\n1. Insert Queue\n2. Delete Queue\n3. Display Queue\n4. Exit\n\n");
printf("Enter your choice: ");
Page 34 of 105
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the Element:");
scanf("%d",&x);
insertq(&q,x);
break;
case 2:
x=deleteq(&q);
printf("\nRemoved %d from the Queue\n",x);
break;
case 3:
displayq(q);
break;
case 4:
flag=0;
break;
default:
printf("\nWrong choice!!! Try Again.\n");
}
}
return 0;
}
Page 35 of 105
II. LAB EXERCISES:
1) Implement a circular queue of Strings using structures. Include functions insertcq,
deletecq and displaycq.
2) Implement two circular queues of integers in a single array where first queue will
run from 0 to N/2 and second queue will run from N/2+1 to N-1 where N is the size
of the array.
3) Write a function that takes a Queue and an element and returns true if the Queue
contains this element or false if not. The elements in the Queue must remain in their
original order once this method is complete. (use only queue operations)
4) Implement a queue with two stacks without transferring the elements of the second
stack back to stack one. (use stack1 as an input stack and stack2 as an output stack)
---------------------------------------------------------------------------------------------------------------
Page 36 of 105
LAB NO: 7 Date:
QUEUE APPLICATIONS
Objectives:
I. SOLVED EXERCISE:
1) Implement a dequeue of integers with following functions.
Insertion Insertion
A B
Deletion Deletion
Page 37 of 105
one end of the list but allows deletions at both ends of the list; and an output-restricted
Dequeue is a Dequeue which allows deletions at only one end of the list allows
insertion at both ends of the list.
Page 38 of 105
front=front-1;
t=queue[front+1];
return t;
Program:
File name: deque_fun.h
#define MAX 30
typedef struct dequeue
{
int data[MAX];
int rear,front;
}dequeue;
Page 39 of 105
void enqueueR(dequeue *p,int x);
void enqueueF(dequeue *p,int x);
int dequeueF(dequeue *p);
int dequeueR(dequeue *p);
void print(dequeue *p);
return(0);
}
void enqueueR(dequeue *P,int x)
Page 40 of 105
{
if(empty(P))
{
P->rear=0;
P->front=0;
P->data[0]=x;
}
else
{
P->rear=(P->rear+1)%MAX;
P->data[P->rear]=x;
}
}
Page 41 of 105
}
Page 42 of 105
{
printf("\nQueue is empty!!");
exit(0);
}
int i;
i=P->front;
while(i!=P->rear)
{
printf("\n%d",P->data[i]);
i=(i+1)%MAX;
}
printf("\n%d\n",P->data[P->rear]);
}
Page 43 of 105
printf("\n1.Create\n2.Insert(rear)\n3.Insert(front)\n4.Delete(rear)\n5.Delete(front)");
printf("\n6.Print\n7.Exit\n\nEnter your choice:");
scanf("%d",&op);
switch(op)
{
case 1: printf("\nEnter number of elements:");
scanf("%d",&n);
initialize(&q);
printf("\nEnter the data:");
for(i=0;i<n;i++)
{
scanf("%d",&x);
if(full(&q))
{
printf("\nQueue is full!!");
exit(0);
}
enqueueR(&q,x);
}
break;
if(full(&q))
Page 44 of 105
{
printf("\nQueue is full!!");
exit(0);
}
enqueueR(&q,x);
break;
case 4: if(empty(&q))
{
printf("\nQueue is empty!!");
exit(0);
}
x=dequeueR(&q);
printf("\nElement deleted is %d\n",x);
break;
case 5: if(empty(&q))
Page 45 of 105
{
printf("\nQueue is empty!!");
exit(0);
}
x=dequeueF(&q);
printf("\nElement deleted is %d\n",x);
break;
case 6: print(&q);
break;
default: break;
}
}while(op!=7);
return 0;
}
Note: An ascending priority queue is a collection of items into which items can be
inserted arbitrarily and from which only the smallest item can be removed. If apq is
an ascending priority queue, the operation pqinsert(apq,x) inserts element x into apq
and pqmindelete(apq) removes the minimum element from apq and returns its value.
Page 46 of 105
one where deletion can be made from both ends, but insertion can be made at one
end only.
3) Write a program to check whether given string is a palindrome using a dequeue.
4) Given a queue of integers, write a program to reverse the queue, using only the
following operations:
i. enqueue(x): Add an item x to rear of queue.
ii. dequeue() : Remove an item from front of queue.
iii. empty() : Checks if a queue is empty or not.
2) Write a program to simulate airport traffic control for a small but busy airport
assuming the following specifications.
In each unit time, only one plane can land or take off but not both.
Planes arrive and take off at random time, so that at any given unit, the
runway may be idle or a plane may be landing or taking off.
Number of planes waiting to take off or land should not exceed a certain
fixed limit.
After running for some period, the program should print statistics such as:
number of planes processed, landed, and took off, refused; average landing
and take-off waiting times, and average run-way idle time.
------------------------------------------------------------------------------------------------------------------
Page 47 of 105
LAB NO: 8 Date:
LINKED LIST CONCEPTS
Objectives:
I. SOLVED EXERCISE:
1) Implement stack using singly linked list.
Algorithm: Push
Step1: Create a new node say
newnode =(struct node *)malloc(sizeof(struct node));
Step2: Check whether a node has been created or not if newnode is
NULL node is not created
i.e. if(newnode= =NULL)
{ printf(“Out of memory”);
exit(0);
}
else
Step3: Insert the data in data field
Page 48 of 105
newnode->data = element;
Step4: Check whether the list is empty, if so then hold the
address of newnode top.
i.e if(top= =NULL)
{ top =newnode;
top->link=NULL;
}
else
Step5: add the new node to the top end
newnode->link=top;
And update the top i.e top=newnode;
Step6: Stop.
Algorithm: POP
Step1: Make temp to point to the top element
temp=top;
Step2: make the node next to the list pointer as the beginning of
list
top = top->link; //equivalent to top=top-1 in array
implementation
Step3: separate temp from chain
temp->link=NULL
delete the first node pointed by temp
free (temp);
Step4: stop
Page 49 of 105
Program:
File name: stack_sll_fun.h
typedef struct node
{ int info;
struct node *link;
}NODE;
Page 50 of 105
}
printf("\n\n**********************************************");
return;
}
temp=list;
while(temp!=NULL)
{
printf("%5d",temp->info);
temp=temp->link;
}
printf(" <- TOP");
printf("\n\n**********************************************");
}
int getchoice()
{
int ch;
printf("**********************************************\n\n");
Page 51 of 105
printf("--------------------Menu--------------------\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
return(ch);
}
Page 52 of 105
break;
case 3: display(list);
getch();
break;
case 4: exit(1);
default: printf("\nInvalid choice");
printf("\n\n**********************************************");
}
}
return 0;
}
********************************************
--------------------Menu--------------------
1. Push
Page 53 of 105
2. Pop
3. Display
4. Exit
Enter your choice:
1
Enter the element to be pushed:34
*************************************************
--------------------Menu--------------------
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
2
Popped element is 34
STACK: 23 <- TOP
**********************************************
Page 54 of 105
3) Create a circular singly linked LIST by merging two sorted singly circular linked
lists containing char data, such that the final LIST is sorted
4) You're given the pointer to the head node of a sorted singly linked list, where the
data in the nodes is in ascending order. Delete as few nodes as possible so that the
list does not contain any value more than once (deleting duplicates). The given head
pointer may be null indicating that the list is empty.
Page 55 of 105
LAB NO: 9 Date:
LINKED LIST APPLICATIONS
Objectives:
I. SOLVED EXERCISE:
1) Given two polynomials, write a program to perform the addition of two polynomials
represented using doubly circular linked list with header and display the result.
Page 56 of 105
Step3: If the exponents of botht the lists are equals, add the coefficients and insert
added coefficient and the exponent to a resultant list i.e
if((one->ex)==(two->ex))
{ h3=add(h3,((one->info)+(two->info)),one->ex);
one=one->rlink;
two=two->rlink;
}
Step4: Else if exponent of first list pointer is greater, then insert first list pointer
exponent and coefficient to result list. Update the first lists pointer only to the
next node and continue with step2.
h3=add(h3,one->info,one->ex);
one=one->rlink;
Step5: Else insert second list pointer exponent and coefficient to result list. Update
the second lists pointer only to the next node and continue with step2.
h3=add(h3,two->info,two->ex);
two=two->rlink;
Step6: If there are any terms left in second list copy it to the resultant list i.e
while(two!=h2)
{ h3=add(h3,two->info,two->ex);
two=two->rlink;
}
Step7: If there are any terms left in first list copy it to the resultant list i.e
while(one!=h1)
{ h3=add(h3,one->info,one->ex);
Page 57 of 105
one=one->rlink;
}
Step8: return a pointer to the resultant list h3
Program:
File name: poly_add_dll_fun.h
struct node
{ int info;
int ex;
struct node *llink;
struct node *rlink;
};
typedef struct node *NODE;
NODE add(NODE head,int n,int e)
{
NODE temp,last;
temp=(NODE)malloc(sizeof(struct node));
temp->info=n;
temp->ex=e;
last=head->llink;
temp->llink=last;
last->rlink=temp;
temp->rlink=head;
Page 58 of 105
head->llink=temp;
return head;
}
NODE sum(NODE h1,NODE h2,NODE h3)
{
NODE one,two;
one=h1->rlink;
two=h2->rlink;
while(one!=h1 && two!=h2)
{ if((one->ex)==(two->ex))
{ h3=add(h3,((one->info)+(two->info)),one->ex);
one=one->rlink;
two=two->rlink;
}
else if(one->ex>two->ex)
{ h3=add(h3,one->info,one->ex);
one=one->rlink;
}
else
{ h3=add(h3,two->info,two->ex);
two=two->rlink;
}
}
while(two!=h2)
{ h3=add(h3,two->info,two->ex);
two=two->rlink;
}
Page 59 of 105
while(one!=h1)
{ h3=add(h3,one->info,one->ex);
one=one->rlink;
}
return h3;
}
Page 60 of 105
NODE h1,h2,h3,h4;
h1=(NODE)malloc(sizeof(struct node));
h2=(NODE)malloc(sizeof(struct node));
h3=(NODE)malloc(sizeof(struct node));
h4=(NODE)malloc(sizeof(struct node));
h1->rlink=h1;
h1->llink=h1;
h2->rlink=h2;
h2->llink=h2;
h3->rlink=h3;
h3->llink=h3;
h4->rlink=h4;
h4->llink=h4;
printf("\nnumber of nodes in list1\n");
scanf("%d",&n);
while(n>0)
{ scanf("%d",&m);
scanf("%d",&e);
h1=add(h1,m,e);
n--;
}
display(h1);
printf("\nnumber of nodes in list2\n");
scanf("%d",&k);
while(k>0)
{ scanf("%d",&m);
scanf("%d",&e);
Page 61 of 105
h2=add(h2,m,e);
k--;
}
display(h2);
printf("\nthe sum is\n");
h3=sum(h1,h2,h3);
display(h3);
return 1;
}
Page 62 of 105
II. LAB EXERCISES:
1) Write a menu driven program to implement doubly linked list without header node
to insert into and delete from both the sides.
2) Add two long positive integers represented using circular doubly linked list with
header node.
3) Reverse a doubly linked list containing words in the data field.
2) Write a ‘C’ program to represent a sparse matrix using doubly linked lists. A
Matrix with most of its elements being zero is called a sparse matrix. Example
----------------------------------------------------------------------------------------------------------
Page 63 of 105
LAB NO: 10 Date:
TREE CONCEPTS
Objectives:
I. SOLVED EXERCISE:
1) Create a binary tree using recursion and display its elements using all the traversal
methods.
Description: To create and maintain the information stored in a binary tree, we need
an operation that inserts new nodes into the tree. We use the following insertion
approach. A new node is made root for the first time and there after a new node is
inserted either to the left or right of the node. -1 one is entered to terminate the
insertion process. This is recursively done for left subtree and the right subtree
respectively.
Program:
File name: binary_tree_recursion_fun_1.h
typedef struct node
{
int data;
struct node *lchild;
struct node *rchild; } *NODE;
NODE Create_Binary_Tree()
Page 64 of 105
{
NODE temp;
int ele;
printf("Enter the element to inserted (-1 for no data):");
scanf("%d",&ele);
if(ele==-1)
return NULL;
temp=(NODE*)malloc(sizeof(struct node));
temp->data=ele;
printf("Enter lchild child of %d:\n",ele);
temp->lchild=create();
Page 65 of 105
{
if(ptr!=NULL)
{
postorder(ptr->lchild);
postorder(ptr->rchild);
printf("%5d",ptr->info);
}
}
Page 66 of 105
{
printf("********************Output********************\n\n");
printf("-----------Menu-----------\n");
printf(" 1. Insert\n 2. All traversals\n 3. Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter node :\n");
scanf("%d",&x);
root=Create_Binary_Tree();
break;
case 2: printf("\nInorder traversal:\n");
inorder(root);
printf("\nPreorder traversal:\n");
preorder(root);
printf("\nPostorder traversal:\n");
postorder(root);
printf("\n\n*********************************************");
break;
case 3: exit(0);
}
}
return 0;
}
Page 67 of 105
Sample Input and Output
********************Output********************
-----------Menu-----------
1. Insert
2. All traversals
3. Exit
Enter your choice:1
Enter node:
20 25 -1 30 40 -1 -1 -1
********************Output********************
Inorder traversal: 25 30 20 40 28
Preorder traversal: 20 25 30 28 40
Postorder traversal: 30 25 40 28 20
*********************************************
2) Display the elements of Binary Tree created using iterative preorder, post-order
(Use single stack), in-order and level-order traversals.
3) Create an expression tree for the given postfix expression and evaluate it.
Page 68 of 105
4) Implement recursive functions to do the following:
2) Create an expression tree for the given prefix expression and evaluate it.
------------------------------------------------------------------------------------------------------------------------------
Page 69 of 105
LAB NO: 11 Date:
TREE APPLICATIONS
Objectives:
I. SOLVED EXERCISE:
1) Write program to find the depth, height, number of leaves, nodes in a BST
Description: We can determine the number of nodes in the tree if we know the number
of nodes in the left subtree and the number of nodes in the right subtree. That is, the
number of nodes in a tree is
This is easy. Given a function CountNodes and a pointer to a tree node, we know how
to calculate the number of nodes in a subtree; we call CountNodes recursively with the
pointer to the subtree as the argument. Similarly we can find the height by taking the
maximum of the depth of recursion on left subtree and right subtree. Here every time
each recursive call increments the depth of recursion by 1. T find the leaf nodes we
need to check the nodes which do not have any children. This can also be don
recursively by exploring left and right subtree if it exists.
Page 70 of 105
Step2: else
return CountNodes(Left(tree)) + CountNodes(Right(tree)) + 1
Algorithm: height
Step1: if tree is NULL
return 0
Step2: else
return 1+ max(height(Left(tree)), height(Right(tree)));
(where max is the maximum of two values)
Algorithm: CountLeaf
Step1: if tree==NULL return;
Step2: CountLeaf(Left(tree));
Step3: if(Left(tree)==NULL && Right(tree)==NULL) leaf++;
Step4: countleaf(Right(tree));
Program:
File name: binary_search_tree_recursion_fun_2.h
int c_node = 0, leaf = 0;
Page 71 of 105
int height(NODE *ptr)
{
if(ptr==NULL) return -1;
return 1+max(height(ptr->lchild),height(ptr->rchild));
}
Page 72 of 105
#include "binary_search_tree_recursion_fun_1.h"
#include "binary_search_tree_recursion_fun_2.h"
int main()
{
int h,x,ch,i;
NODE *root;
root=NULL;
while(1)
{
printf("********************Output********************\n\n");
printf("-----------Menu-----------\n");
printf(" 1. Create\n 2. Height,Count the nodes and leaves\n 3.
Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter node (do not enter duplicate nodes):\n");
scanf("%d",&x);
root=create(root,x);
break;
case 2: printf("\nTree Generated!\nPrinting Now in
indorder - ");
inorder(root);
Page 73 of 105
int h = height(root);
count_node(root);
count_leaf(root);
printf("\nHeight - %d",h);
printf("\nNo of Nodes - %d",c_node);
printf("\nNo of Leaves - %d",leaf);
printf("\n\n***************************");
break;
case 3: exit(0);
}
}
return 0;
}
Note: Replace the element to be deleted with the largest element in the LST (Left
Sub Tree) ) when the node to be deleted has both LST (Left Sub Tree) and RST
(Right Sub Tree).
3) Given a Binary Tree and a key, write a function that prints all the ancestors of the
key in the given binary tree.
Page 74 of 105
4) Write a program to construct a BT for given pre-order and the post- order traversal
sequences.
1) Phone book application for student records using roll number as key: Implement a
menu driven program to create a phone book for student records where in each
student record will contain roll-no, name, section, CGPA and phone number. The
phone book must have an option to search for a record based on roll no of the
student. Search is done using a Binary Search Tree
2) Repeat by reading student records from a file. Implement a menu driven program to
create a phone book for student records which are read from a file. The application
must have an option to search for a record based on roll no of the student. Search is
done using a Binary Search Tree
--------------------------------------------------------------------------------------------------------------------------
Page 75 of 105
LAB NO: 12 Date:
PROBLEM SOLVING USING DATA STRUCTURES
Objectives:
I. SOLVED EXERCISE:
1) Implement hashing for dictionary
Concept: A hash table (hash map) is a data structure that implements an abstract data
type, a structure that can map keys to values. A hash table uses a hash function to
compute an index into an array of buckets or slots, from which the desired value can be
found.
Ideally, the hash function will assign each key to a unique bucket, but most hash table
designs employ an imperfect hash function, which might cause hash collisions where
the hash function generates the same index for more than one key. Such collisions must
be accommodated in some way. One technique called chaining, "Chains" the item that
collided to a location outside the "Table" to another block of memory.
In a well-dimensioned hash table, the average cost for each lookup is independent of
the number of elements stored in the table
Description: The idea is to maintain a hash table with chaining. Each node in the chain
contains a word and its synonym (maximum of 10 synonyms of 20 characters). The
node structure is as follows:
typedef struct node
{
int count; /* count field is to count the number of meanings of a word*/
char data[81];
char means[10][20];
Page 76 of 105
struct node *link;
};
The size of the hash table is 26 slots, one for each alphabet. Whenever a word has to be
added to the hash table, we apply the hash function to the word. The hash function
given here maps alphabets to its corresponding order, example ‘a’ will be mapped to 0
b or ‘B’ will be mapped to ‘1’ and so on, which is called the hash value. In the solved
exercise given, the hash function checks only the first character of the word for finding
a hash value. However this hash function can be modified for a better hashing.
Similarly, all permutation of word and its synonym are added to the hash table with a
chaining in case of collision ex: ht[0] with two nodes chained. While searching for a
word’s synonym, same has function is applied. The list in that slot of the hash table is
searched.
Page 77 of 105
Page 78 of 105
Algorithm: Insert
Step1: Perform hash_function on key, to get the hash value, of a record to be inserted
Step2: Use the hash value to map it on to a slot in the hash table.
Step3: If collision occurs resolve using chaining
Ste4: Insert the record
Algorithm: Search
Step1: Apply hash_function on key to be searched, to get the hash value.
Step2: Use the hash value to map it on to a slot in the hash table.
Step3: Search in the chain of the corresponding for the key.
Ste4: If found return the record
Else return Failure Status
Program:
File name: hash_fun.h
typedef struct node
{
int count; /* count field is to count the number of meanings of a word*/
char data[81];
char means[10][20]; /*this is the field which stores the meaning upto ten
words of 20 characters*/
struct node *link;
};
Page 79 of 105
void init_hashtable();
void display();
void addtomeanlist(char str[],int key,int cnt);
void search_hash_table(char key[]);
/* Hash function which returns a hash value */
int getHashVal(char str[]);
Page 80 of 105
for(t=ht[val];t!=NULL;t=t->link)
{
if(strcmpi(t->data,key)==0)
{
found=1; position++;
break;
}
}
if(!found)
printf("Key word not found in the hash table:\n");
else
{
printf("Found in the hash location %d, at position %d",val, position);
for(i=0;i< t->count;i++)
printf(" %s ",t->means[i]);
}
void init_hashtable()
{
int i;
for(i=0;i<26;i++)
ht[i]=NULL;
}
Page 81 of 105
/* Hash Function: Modify this with a better hashing technique*/
int getHashVal(char str[])
{
char ch;
int key;
struct node *newN;
ch=tolower(str[0]);
key=ch-97;
return key;
}
void insert_htable(char str[], int hval)
{
int key=hval;
struct node *t;
struct node *newN=(struct node *)malloc(sizeof(struct node));
strcpy(newN->data,str);
newN->link=NULL;
if(ht[key]==NULL)
ht[key]=newN;
else
{
t=ht[key];
while(t->link!=NULL)
t=t->link;
t->link=newN;
t=newN;
}
Page 82 of 105
}
void display()
{
struct node *temp;
int i;
for(i=0;i<26;i++)
{
printf("ht[%d]",i);
for(temp=ht[i];temp!=NULL;temp=temp->link)
printf("->%s", temp->data);
printf("\n");
}
}
void display_meanings_hashtable()
{
struct node *newN;
int i,k;
for(i=0;i<26;i++)
{
printf("ht[%d]",i);
for(newN=ht[i];newN!=NULL;newN=newN->link)
{
printf("->%s",newN->data);
for(k=0;k< newN->count;k++)
Page 83 of 105
printf(" %s ",newN->means[k]);
}
printf("\n");
}
}
File name: hash.c
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#include "hash_fun.h"
int main()
{
int i,j,t;
char inbuffer[81];
char searchkey[81];
char dict[10][20];
int hval,cnt=0;
init_hashtable();
printf("Dictionary Creation Starts now: Enter the word and its meaning list\n");
while(1)
{
cnt=0;
Page 84 of 105
printf("Enter the word: type \"end\" to terminate\n");
scanf("%s",inbuffer);
if(strcmp(inbuffer,"end")==0)
break;
printf("Enter the synonyms: To terminate the list type \"#\" \n");
while(strcmpi(inbuffer,"#")!=0)
{
strcpy(dict[cnt],inbuffer);
scanf("%s",inbuffer);
cnt++;
}
i=0;
while(i < cnt)
{
hval = getHashVal(dict[i]);
insert_htable(dict[i],hval);
j=0;
t=0;
while(j <= cnt)
{
if(i!=j)
addtomeanlist(dict[j],hval,t++);
j++;
}
i++;
}
Page 85 of 105
}
display();
display_meanings_hashtable();
printf("Enter the key to be searched\n");
scanf("%s",searchkey);
search_hash_table(searchkey);
return 0;
}
king
ruler
emperor
school
college
university
Page 86 of 105
Enter the word: type "end" to terminate
appreciate
praise
acknowledge
end
king
a) Write a function to read a list of students from a user, and create a linked list.
Each entry in the linked list is to have the student’s name, a pointer to the next
student, and a pointer to a linked list of registration number, as well as list of
marks. You may have up to N subjects score for each student. A picture or
structure is shown in figure 1.
Page 87 of 105
Students
Ganga 178908767 48 67 76 54 86 X
09 09 09 09 09
05 05 05 05 05
Yamuna 176543212 84
67 88
67 78
67 76
67 X 67
309 309 09
3 09
3 3
05 05 05 05
Godavari 170112233 67
67 87
67 89 X
67 67
09 09 09
3 3 3 3
05 05 05
67 67 67
3 3 3
Godavari 170112233 88 87 89 X
09
Figure 1 Data structure for students’ 09
record
05 05
The function program initializes the student list 67
by reading67the students’ names
3 3
from the user and creating null scores lists. After building the student list, it
loops through the list, prompting the user to enter the scores for each student.
The scores prompt is to include the name of the student as well as registration
number and marks.
b) Write a function to find out the duplicate entry in the student record while
considering registration number. If so remove the duplicate with less total
(as in the example Godavari’s first record is removed), and list the students’
record without duplicate. the scores for each student along with the score
total and average score. The average includes only the entered score. The
program also prints highest in each subject.
c) Write a function to read student name and registration number, and prints the
scores for each student along with the score total and average score. The
Page 88 of 105
average includes only the entered score. Finally prints all the students’
record according to their highest total score in the order.
3) When a number of vehicles are queued on a Highway during a traffic jam, certain
vehicles are given priority over other to give way. The possible types of vehicles on
road and their associated priority are given below.
4) MAHE Parking Garage contains a single lane which can hold up to 5 cars. There is
only a single entrance/exit to the garage at one end of the lane. If a customer arrives to
pick up a car that is not nearest the exit, all cars {car no, owner name, and the license
number} blocking its path are moved out to the temporary parking slot whose one end is
locked, the customer car is driven out, and the other cars are restored in the order they
Page 89 of 105
were in originally. If a confused customer requests his car that is not in the garage, the
unorganized garage attendant must remove all the cars to determine that the car is not
there.
Write a text menu driven ‘C’ program that processes arrivals and departures by the
license plate number using suitable data structure. Cars are assumed to arrive and depart
in the order specified by the input. The program should print a message whenever a car
arrives or departs. When a car arrives, the garage attendant should specify whether or
not there is room for the car in the garage. If there is no room, the car leaves without
entering the garage. Lanes are created as and when required.
Include a function to calculate the parking payment depending on total amount of time
the car was parked in the garage based on 30 rupees per hour. When a car departs, the
garage attendant should indicate the number of times that the car was moved out of the
garage to allow other cars to depart. Also have an option to display the contents of the
garage - this option does not affect the number of moves a car has. Display the owner
name of the car made highest pay when the garage is empty.
1) Design an application using suitable data structure to automate the process of class
representative election. The application should take the inputs – No of students(voters)
present in the class and No of Candidates and their name(s). During the voting process,
the faculty on duty of conduction of election, need to initiate the voting (say by pressing
a particular key during which a beep sound is heard). Then, a student can come and cast
his/her vote against the candidate by entering the candidate’s serial number. After
casting a vote, a beep sound is given to confirm that the voting is done. This process is
repeated until all students cast their vote. At the end, the total votes obtained by each
Page 90 of 105
candidate should be displayed along with number of foul votes. the candidate who has
won the maximum number of votes should be declared as class representative.
2) Design a suitable data structure for TEXT editor which includes operations such as
inserting a line after the enter key is pressed and delete a line, search for a word in a
line. When the key F2 is pressed, the content of the buffer should be saved in a file and
displayed on the screen (Hint: Array of pointers to linked lists can be used as Data
structure).
----------------------------------------------------------------------------------------------------------------------------
Page 91 of 105
REFERENCES
1. Behrouz A. Forouzan, Richard F. Gilberg “A Structured Programming
Approach Using C”, 3rd Edition, Cengage Learning India Private Limited, India,
2007.
2. Ellis Horowitz, Sartaj Sahni , Susan Anderson and Freed, “ Fundamentals of
Data Structures in C”, 2nd Edition, Universities Press, India, Reprint 2011.
3. Richard F. Gilberg, Behrouz A. Forouzan, “Data structures, A Pseudocode
Approach with C”, 2nd Edition, Cengage Learning India Pvt. Ltd, India, 2009.
4. Robert Kruc & Bruce Lening, “Data structures & Program Design in C”, 2nd
Edition, Pearson, 2007.
5. Debasis Samanta, “Classic Data Structures”, 2nd Edition, PHI Learning Pvt.
Ltd., India, 2010
Page 92 of 105
Appendix
1 # include <stdio.h>
2 int main()
3 {
4 int i, num, j;
5 printf ("Enter the number: ");
6 scanf ("%d", &num );
7 for (i=1; i<num; i++)
8 j=j*i;
9 printf("The factorial of %d is %d\n",num,j);
10 }
$ cc factorial.c
$ ./a.out
Enter the number: 3
The factorial of 3 is 12548672
$ cc -g factorial.c
Note: The above command creates a.out file which will be used for debugging as shown
below.
$ gdb a.out
Syntax:
Page 93 of 105
Appendix
break line_number
Other formats:
break [file_name]:line_number
break [file_name]:func_name
Places break point in the C program, where you suspect errors. While executing the
program, the debugger will stop at the break point, and gives you the prompt to debug.
So before starting up the program, let us place the following break point in our program.
break 8
Breakpoint 1 at 0x804846f: file factorial.c, line 8.
run [args]
You can start running the program using the run command in the gdb debugger. You
can also give command line arguments to the program via run args. The example
program we used here does not requires any command line arguments so let us give run,
and start the program execution.
run
Starting program: /home/student/Debugging/c/a.out
Once you executed the C program, it would execute until the first break point, and give
you the prompt for debugging.
You can use various gdb commands to debug the C program as explained in the sections
below.
Step 5: Printing the variable values inside gdb debugger
Page 94 of 105
Appendix
Examples:
print i
print j
print num
(gdb) p i
$1 = 1
(gdb) p j
$2 = 3042592
(gdb) p num
$3 = 3
(gdb)
As you see above, in the factorial.c, we have not initialized the variable j. So, it gets
garbage value resulting in a big numbers as factorial values.
Fix this issue by initializing variable j with 1, compile the C program and execute it
again.
Even after this fix there seems to be some problem in the factorial.c program, as it still
gives wrong factorial value.
So, place the break point in 8th line, and continue as explained in the next section.
There are three kind of gdb operations you can choose when the program stops at a
break point. They are continuing until the next break point, stepping in, or stepping over
the next program lines.
c or continue: Debugger will continue executing until the next break point.
n or next: Debugger will execute the next line as single instruction.
s or step: Same as next, but does not treats function as a single instruction,
instead goes into the function and executes it line by line.
By continuing or stepping through you could have found that the issue is because we
have not used the <= in the ‘for loop’ condition checking. So changing that from < to
<= will solve the issue.
gdb command shortcuts
Use following shortcuts for most of the frequent gdb operations.
l – list
p – print
Page 95 of 105
Appendix
c – continue
s – step
ENTER: pressing enter key would execute the previously executed command
again.
C QUICK REFERENCE
PREPROCESSOR
Page 96 of 105
Appendix
LITERALS
255, 0377, 0xff // Integers (decimal, octal, hex)
2147463647L, 0x7fffffffl // Long (32-bit) integers
123.0, 1.23e2 // double (real) numbers
‘a’, ‘\141’, ‘\x61’ // Character (literal, octal, hex)
‘\n’, ‘\\’, ‘\’’, ‘\”’, // Newline, backslash, single quote, double quote
“string\n” // Array of characters ending with newline and \0
“hello” “world” // Concatenated strings
DECLARATIONS
int x; // Declare x to be an integer (value undefined)
int x=255; // Declare and initialize x to 255
short s; long 1; // Usually 16 or 32 bit integer (int may be either)
char c= ‘a’; // Usually 8 bit character
unsigned char u=255; signed char m=-1; // char might be either
unsigned long x=0xffffffffL; // short, int, long are signed
float f; double d; // Single or double precision real (never unsigned)
int a, b, c; // Multiple declarations
int a[10]; // Array of 10 ints (a[0] through a[9])
int a[]={0,1,2}; // Initialized array (or a[3]={0,1,2}; )
int a[2][3]={{1,2,3},{4,5,6}; // Array of array of ints
char s[]= “hello”; // String (6 elements including ‘\0’)
int* p; // p is a pointer to (address of) int
char* s= “hello”; // s points to unnamed array containing "hello"
void* p=NULL; // Address of untyped memory (NULL is 0)
Page 97 of 105
Appendix
STORAGE CLASSES
int x; // Auto (memory exists only while in scope)
static int x; // Global lifetime even if local scope
extern int x; // Information only, declared elsewhere
STATEMENTS
x=y; // Every expression is a statement
int x; // Declarations are statements
; // Empty statement
{ // A block is a single statement
int x; // Scope of x is from declaration to end of
//block
a; // In C, declarations must precede statements
}
if (x) a; // If x is true (not 0), evaluate a
else if (y) b; // If not x and y (optional, may be repeated)
else c; // If not x and not y (optional)
while (x) a; // Repeat 0 or more times while x is true
for (x; y; z) a; // Equivalent to: x; while(y) {a; z;}
do a; while (x); // Equivalent to: a; while(x) a;
switch (x) { // x must be int
case X1: a; // If x == X1 (must be a const), jump here
case X2: b; // Else if x == X2, jump here
default: c; // Else jump here (optional)
}
break; // Jump out of while, do, for loop, or switch
continue; // Jump to bottom of while, do, or for loop
return x; // Return x from function to caller
Page 98 of 105
Appendix
FUNCTIONS
int f(int x, int); // f is a function taking 2 ints and returning int
void f(); // f is a procedure taking no arguments
void f(int a=0); // f() is equivalent to f(0)
f(); // Default return type is int
inline f(); // Optimize for speed
f( ) { statements; } // Function definition (must be global)
Function parameters and return values may be of any type. A function must either be
declared or defined before it is used. It may be declared first and defined later. Every
program consists of a set of global variable declarations and a set of function definitions
(possibly in separate files), one of which must be:
EXPRESSIONS
Operators are grouped by precedence, highest first.
Unary operators and assignment evaluate right to left.
All others are left to right.
Precedence does not affect order of evaluation which is undefined. There are no runtime
checks for arrays out of bounds, invalid pointers etc.
Page 99 of 105
Appendix
&x // Address of x
*p // Contents of address p (*&x equals x)
x*y // Multiply
x/y // Divide (integers round toward 0)
x%y // Modulo (result has sign of x)
x+y // Add, or &x[y]
x–y // Subtract, or number of elements from *x to *y
x << y // x shifted y bits to left (x * pow(2, y))
x >> y // x shifted y bits to right (x / pow(2, y))
x<y // Less than
x <= y // Less than or equal to
x>y // Greater than
x >= y // Greater than or equal to
x == y // Equals
x != y // Not equals
x&y // Bitwise and (3 & 6 is 2)
x^y // Bitwise exclusive or (3 ^ 6 is 5)
x|y // Bitwise or (3 | 6 is 7)
x && y // x and then y (evaluates y only if x (not 0))
x || r // x or else y (evaluates y only if x is false(0))
x=y // Assign y to x, returns new value of x
x += y // x = x + y, also -= *= /= <<= >>= &= |= ^=
x?y:z // y if x is true (nonzero), else z
x, y // evaluates x and y, returns y (seldom used)
STDIO.H
prinf("Format specifers",value1,value2,..);
printf("user defined message");
scanf("Format specifiers",&value1,&value2,.....);
Format specifier:
%d Integer
%f Float
%lf Double
%c Single character
%s String
%u Unsigned int
Other functions
asin(x); acos(x); atan(x); // Inverses
atan2(y, x); // atan(y/x)
sinh(x); cosh(x); tanh(x); // Hyperbolic
exp(x); log(x); log10(x); // e to the x, log base e, log base 10
pow(x, y); sqrt(x); // x to the y, square root
ceil(x); floor(x); // Round up or down (as a double)
fabs(x); fmod(x, y); // Absolute value, x mod y
FILE HANDLING IN C
Before we read (or write) information from (to file) on a disk, we must open a file in
particular mode. To open a file we use fopen() function. fopen() is a high level IO
function. There are many high level IO function we use in file handling.
Syntax:
FILE *fp;
fp= fopen(“filename”,”mode”);
I. Binary Files: To read, write contents of a binary file we use fread and fwrite
respectively. Examples of binary files are .exe files .bmp or image files. More
generally, any file which cannot be read using any normal text editor.
Syntax: size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
The functions fread/fwrite are used for reading/writing data from/to the file opened
by fopen function. These functions accept three arguments. The first argument is a
pointer to buffer used for reading/writing the data. The data read/written is in the
form of ‘nmemb’ elements each ‘size’ bytes long.
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 fclose() function first flushes the stream opened by fopen() and then closes the
underlying descriptor. Upon successful completion this function returns 0 else end
of file (eof) is returned. In case of failure, if the stream is accessed further then the
behavior remains undefined.
Example: To write an employ’s record to a file. Record has three fields name age
and basic salary.
struct emp{
char name[20];
int age;
float bs;
};
struct emp e;
void main(){
fp = fopen("EMP.DAT","wb");
if(fp == NULL){
printf("Cannot open file");
}
printf("Enter name, age and basic salary");
scanf("%s%d%f",e.name,&e.age,&e.bs);
fwrite(&e,sizeof(e),1,fp);
fclose(fp);
}
The following code segment illustrates how to read data from file in binary format.
struct emp{
char name[20];
int age;
float bs;
};
struct emp e;
void main(){
fp = fopen("EMP.DAT","rb");
/* read all the records one by one */
while(fread(&e,sizeof(e),1,fp)==1){
printf("%s %d %f\n",e.name,e.age,e.bs);
}
fclose(fp);
}
II. Text File: File contents are written in ascii or unicode format. Generally, these files
can be read using a text editor.
Syntax: fprintf(FILE*,format,variable_list);
The fprintf statement should look very familiar to you. It can be almost used in the
same way as printf. The only new thing is that it uses the file pointer as its first
parameter.
#include<stdio.h>
int main()
{
FILE *ptr_file;
int x;
if (ptr_file == NULL)
return -1;
fclose(ptr_file);
}
Similar to fprintf, fscanf, we can use fputc, fgetc to handle character data.