0% found this document useful (0 votes)
88 views

Fundamental of Computer Science Practical File

The document discusses recursion and provides examples of recursive programs. Recursion involves a function calling itself, with each call simplifying the original problem. Examples of recursive programs provided include calculating factorials, Tower of Hanoi, Fibonacci series, quicksort, and calculating powers. Pseudocode and C code are given for implementing these examples recursively, along with analysis of their time complexities which are generally O(n).

Uploaded by

Gaurav Thakur
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views

Fundamental of Computer Science Practical File

The document discusses recursion and provides examples of recursive programs. Recursion involves a function calling itself, with each call simplifying the original problem. Examples of recursive programs provided include calculating factorials, Tower of Hanoi, Fibonacci series, quicksort, and calculating powers. Pseudocode and C code are given for implementing these examples recursively, along with analysis of their time complexities which are generally O(n).

Uploaded by

Gaurav Thakur
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Recursion Programs

Function Calling itself is called Recursion. In Recursion when each time the function call itself
with a slightly Simpler Version of the original Problem

BASIC CONCEPT OF RECURSION


In this program, A big problem is broken into subproblem such
Let us take an example:-
that each subproblem was the same set of well defined instruction
Main()
to find its Solution.like:-
{
int k;
Sum( 10)=10+sum(9); //Sum of 9 natural numbers
k=sum(10); //FUNCTION CALLING
Sum(9)=9+Sum(8);
printf(“\d”,k);
Sum(8)=8+Sum(7);
}
Here,At each iteration, the complexity of the program is reducing
int Sum(int a )
As the function is calling itself again and again,so we have to
{
defined a certain condition where it’s end(terminating Condition)
int s;
like in this program that condition is:-
if(a==1)
If(a==1)
return(1);
return(1)
s=a+sum(a-1);
return(s);
}

Let us now solved some examples through the recursive approach:-

1) Factorial of a number
2) Tower of Hanoi
3) Fibonacci series
4) Quick sort
5) To calculate the power of a number
Practical – 1

Ques)=Write a Program on Factorial of a number using Recursion

Theory- Factorial of a number is the product of that number with their all below integers.It is
represented by !.It uses recursion technique where Specifying that factorial of 0 and 1 is 1 itself
work as termination condition where the in every recursive call n is decreased by 1 until it
become equal to 1 or 0 and Once this condition is achieved backtracking take place till the base
or starting condition and the output is evaluated. The factorial function is defined for non-
negative integers only, that is, for the numbers 0,1,2,3,….n

Example:

5!= 5*4*3*2*1=120
4!=4*3*2*1=24
3!=3*2*1=6
2!=2*1=2
1!=1

Time complexity of the program

T(n) = T(n-1) + c and


T(0) = T(1) = 1
Therefore the runtime of above algorithm is O(n)
Pseudo Code: -
INSIDE THE MAIN FUNCTION
Print Prompt “Enter a Positive Value” Take Input From user
F=factorial(n) //Function calling
Print Prompt “Factorial of n Number is = F” //for displaying factorial of input number
END

Factorial(n)
IF n<=0 Then
Return 1
ELSE
F= n*factorial(n-1)
Return F

Program Code:-

#include<stdio.h>
#include<conio.h>
Void main()
{
clrscr()
int factorial(int) ;
int n,f ;
printf(“Enter the number :-“) ;
scanf(“%d”,&n);
f=factorial(n);
printf(“factorial of the number is %d” f) ;
getch() ;
}
int factorial(int n)
{
int f;
if(n<=0)
return 1;
else
f=n*factorial(n-1);
return f ;
}
Practical – 2
Ques)= Write a Program on Tower of Hanoi using recursion.

Theory- Tower of Hanoi consists of three towers and n number of disks placed over one
another in ascending order of size on one rod, the smallest at the top.
There are some rules of Tower of Hanoi:-
=) Only a single disc is allowed to be transferred at a time.
=) Each transfer or move should consists of taking the upper disk from one of the stack and
then placing it on the top of another stack i.e. only a top most disk on the stack can be moved.
=) Larger disk cannot be placed over smaller disk; placing of disk should be in increasing order

The minimum number of moves required to solve a Tower of Hanoi puzzle is 2n-1, where n is
the number of disks.For example for three disks 7 moves is required.

Time complexity:-
T(n) = 2T(n-1) + 1
it solution can be given by Muster theorem
1. If a<1 then T(n) = O(nk)
2. If a=1 then T(n) = O(nk+1)
3. if a>1 then T(n) = O(nkan/b)

So a=2 using 3 condition ,the solution of the problem is O(2n)


Pseudo Code:
Print Prompt “Enter the No. of disk”
Read Input From user
Tower(n, ’A’,’B’,’C’) //calling function
END
Now using Function Tower(n, A, B, C) ;
If n==1 Then
Move Disk from Source to destination
Else
Tower(n-1, A, C, B)
Move disk from Source to destination
Tower(n-1, A, B, C)
END

Program Code:-
#include<stdio.h>
#include<conio.h>
Void Tower(int,char,char,char); //function declaration
Void main()
{ int num ;
clrscr();
printf(“Enter the no of disks:”);
Scanf(“/d”,&num);
Printf(“The sequence of Moves involved in the tower of Hanoi are:\n”);

//function calling
Tower(num, ’A’, ’C’ ,’B’); // A,B,C are names of rods
getch();
}
//function Defination
Void Tower(int num, char fromsrc, char todes, char aux)
{
If(num==1)
{
printf(“\n Move disk 1 from rod %c to rod %c”,fromsrc, todes);
return ;
}//destination will act as auxiliary
Tower(num-1, fromsrc, aux, todes);
printf(“\n Move disk %d form rod %c to rod %c, num, fromsrc, todes);
//source will act as a auxiliary
Tower(num-1, aux, todes,fromsrc);
}
Practical – 3
Ques)= Write a Recursive Program to implement Quick sort

Theory- Quick Sort is also based on the concept of Divide and Conquer. It divides the unordered
list into two sub-lists: low elements sub-list and high elements sub-list, and then recursively sort
these sub-lists. In it first the element is picked from the list, which is called a pivot. Pivot can be
the first element or the last element or can be median or random element. Reorder the list with
a rule that all elements which are less than the pivot come before the pivot, whereas all
elements that are higher than the list come after the pivot. After partitioning the list, the pivot
is in its position. With the two sub-lists, the same is repeated recursively.
Based on the selection of pivot element 3 cases are defined:-

Best case

T(n) = 2T(n/2) +O(n)


T(n) = O(nlogn)
It takes place when pivot is the middle element.

Average case

T(n) = T(n/9) + T(9n/10) +O(n)


T(n)=O(nlogn)
It takes place for selection of any random pivot element.

Worst case

T(n) = T(0) + T(n-1) + O(n)


T(n) = O(n2)
It takes place when the largest or the smallest element is selected as pivot element.
Psuedocode-
quick_sort(int a[],int l,int u)
int j
if(l<u)
||j=partition(a,l,u)
||quick_sort(a,l,j-1)
||quick_sort(a,j+1,u)

partition(int a[],int l,int u)


v=a[l]
i=l
u+1;
do
|| do
||||i++;
|| while(a[i]<v&&i<=u);
||do
|||| j--;
||while(v<a[j]);
||if(i<j)
||||swap(a[i],a[j])
||while(i<j);
a[l]=a[j];
a[j]=v;
return(j);

Program Code:-

#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<ctime>

int quick_sort(int a[],int l,int u);


int partition(int a[],int l,int u);

using namespace std;


int n;

int main()
{
cout<<"\nEnter the no of elements in array: ";
cin>>n;
int *a=new int[n];
int lb=0,ub=n-1;
cout<<"\nEnter list elements\n";
for(int i=0;i<n;i++)
{
cout<<i+1<<") ";
cin>>a[i];
cout<<endl;
}
cout<<"\nThe list is: \n";
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
quick_sort(a,lb,ub);
cout<<"\nSorted Data ";
for (int i = 0; i< n; i++)
cout<<"\t"<<a[i];

getch();
}

int partition(int a[],int l,int u)


{
int v,i,j,temp;
v=a[l];
i=l;
j=u+1;

do
{
do
i++;

while(a[i]<v&&i<=u);

do
j--;
while(v<a[j]);

if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);

a[l]=a[j];
a[j]=v;

return(j);
}

int quick_sort(int a[],int l,int u)


{
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u);
}
}
Practical – 4
Ques)= Write a Program to Print Fibonacci series

Theory:- A Fibonacci series is defined as a series in which each number is the sum of the
previous two numbers. The program is implemented using recursion technique where user
enter the limit as input that is number of terms need to be printed. Initially first term is 0 and
second term is 1 and then accordingly series is evaluated further.

Example

0,1,1,2,3,5,8,11......

Given terms -> 0,1


Next term -> 0+1=1
Fourth term -> 1+1=2
and the process go on

The recursive equation for Fibonacci is

T(n) = T(n-1) + T(n-2) + O(1)


T(n) = O(2n)

On solving the above recursive equation we get the upper bound of Fibonacci as O(2n)  but this
is not the tight upper bound
Practical – 5

Ques)= Write a Program to find the power of a number using recursion

Theory:- The power of a number is the number multiplied to itself for the number of times it
has been raised to .
For example :- 7^3=343
The time complexity of the program is 0(n).

Pseudo Code:-

Take function as power()

int power(int b,int e)


b=2 and e=3
if(e==0) false
else
return (b*power(b,e-1)); i.e. return (2*power(2,3-1)); i.e. return (2*power(2,2));

A recursive call[power(2,2)]
if(e==0) false
else
return (b*power(b,e-1)); i.e. return (2*power(2,2-1)); i.e. return (2*power(2,1));

A recursive call[power(2,1)]
if(e==0) false
else
return (b*power(b,e-1)); i.e. return (2*power(2,1-1)); i.e. return (2*power(2,0));

A recursive call[power(2,0)]
if(e==0) true
return 1
So now we will have
1    … power(2,0)
2*1 = 2    … power(2,1)
2*2 = 4    … power(2,2)
Program Code:-

#include<stdio.h>
int power(int ,int ); //function declaration
int main()
{
int base, exponent,result;
printf("Enter the base\n");
scanf("%d",&base);
printf("Enter the exponent\n");
scanf("%d",&exponent);
result=power(base,exponent); //function calling
printf(“\n the answer is=%d”,result);
return 0;
}
int power(int b,int e) //function defination
{
if(e==0)
        return 1;
    else
        return (b*power(b,e-1));
}
Arrays

An Array is a data structure containing a number of data values all of which are of same
type.The Simplest form of array is one dimensional Array.

Syntax:- Datatype name of the array[no of elements]


int num[5]

In the above defined array Complier will allocate a contiguous block of memory of size=5*size
of (int)
Array can be either static or dynamic. For a static array user need to specify the size of array in
before whereas in dynamic array memory allocation take place at compile time.

To Access an array element the syntax is array name[index] like num[0] to access first element
num[1] for second element and so on
Specifying the length of an array using macro is considered to be an excellent practice
#define N 10
Int array[N];

Let us now solved some examples using concept of arrays:-


1) Printing array through different commands
2) Merging of 2 arrays of same size
3) Sum of two 1D array
4) Searching user choice element in array
5) Implementing dynamic array
6) Evaluating nth largest element of array
Practical – 6

Ques)= Write a Program to print the elements in array using different commands

Theory: Arrays can be accessed in different ways. First by implementing the function of an
array and then increasing every element of array using loop. Other way can be using pointer
where the name of array specifies the position of zeroth element.

Psuedo Code:-

for(j=0;j<n;j++)
||printf("%p\n",a)
||printf("%d\n",*a)
||a++

for(i=0;i<n;i++)
||printf("%p\n",&a[i])
||printf("%d\n",a[i])

for(k=0;k<n;k++)
||printf("%p\n",(a+k))
||printf("%d\n",*(a+k))
Program Code:-
#include<stdio.h>
int *init_array(int s)
{ int i;
int *ar=(int*) malloc(s*sizeof(*ar));
if(ar!=NULL)
{ for(i=0;i<s;i++)
{
ar[i]=i;
}
return ar;
}
else
{
return 0;
}
}
int main()
{
int n,i,j,k;
printf("enter the size\n");
scanf("%d",&n);
int *a=init_array(n);
printf("Array1- \n");
for(k=0;k<n;k++)
{
printf("%p\n",(a+k));
printf("%d\n",*(a+k));
}
printf("Array2- \n");
for(i=0;i<n;i++)
{
printf("%p\n",&a[i]);
printf("%d\n",a[i]);
}

printf("Array3- \n");
for(j=0;j<n;j++)
{
printf("%p\n",a);
printf("%d\n",*a);
a++;
}
}
Practical – 7

Ques)= Write a Program of Merging of 2 arrays into third array

Theory: To merge two arrays, three array variables are needed. In it start adding each and
every element of the first array to the third array (target array) after this, start appending
each and every element of the second array to the third array (target array).
EXAMPLE:-
arr1[] = { 1, 3, 4, }, arr2[] = {9, 6, 8}
output:- arr3[]={1, 3, 4, 9, 6, 8}
It’s Time complexity is:-0(n1+n2)

Psuedo Code:-

procedure concate_array(A)

Array B, C
index ← 0
FOR EACH value in B DO
A[index] ← B[n]
INCREMENT index
END FOR

FOR EACH value in C DO


A[index] ← C[n]
INCREMENT index
END FOR
DISPLAY A
end procedure
Program Code:-

#include <stdio.h>
int main()
{
int array[10];
int a[5] = {0, 2, 4, 6,} , b[5] = {1, 3, 5, 7, 9};
int i, index, n, m;
n = m = 5;
index = 0;
for(i = 0; i < n; n++)
{
array[index] = a[i];
index++;
}
for(i = 0; i < m; m++)
{
array[index] = b[i];
index++;
}

printf("\nEven -> ");

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


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

printf("\nOdd -> ");

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


printf(" %d", b[i]);

printf("\nConcat -> ");

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


printf(" %d", array[i]);

return 0;
}
Practical – 8

Ques)= Write a Program to display the sum of two 1D array

Theory- A one dimensional array or single dimensional array is the simplest type of array that
contains only one row for storing data. To add 2 arrays user will be asked to enter the size of
array using malloc function and the resulting array will also have the same size and now
elements of both arrays are added index by index and the result is displayed in the resulting
array. Now we check how malloc function is declared.

Syntax of malloc()

ptr = (castType*) malloc(size)

ptr = (int*) malloc(100 * sizeof(float))

Psuedocode-

add(int a1[],int a2[])


int res[size]
for(i=0 to size-1)
||res[i]=a1[i]+a2[i]

Program Code-

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

void main()
{

int i, n;
int *a, *b, *c;
printf("How many Elements in each array...\n");
scanf("%d", &n);

a = (int *)malloc(n * sizeof(int));


b = (int *)malloc(n * sizeof(int));
c = (int *)malloc(n * sizeof(int));
printf("Enter Elements of First List\n");
for (i = 0; i< n; i++)
{
scanf("%d", a + i);
}

printf("Enter Elements of Second List\n");


for (i = 0; i< n; i++)
{
scanf("%d", b + i);
}

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


{
*(c + i) = *(a + i) + *(b + i);
}

printf("Resultant List is\n");


for (i = 0; i< n; i++)
{
printf("%d\n", *(c + i));
}

}
Practical – 9

Ques)= Write a Program to implement a dynamic array

Theory- Dynamic array can be defined as a procedure in which the size of the array is changed
during runtime and C provide some function to achieve these tasks.There are 4 library function
provided by C .These are
1. malloc()
2. calloc()
3. free()
4. realloc()

malloc or  memory allocation  method in C is used to dynamically allocate a single large block of
memory with the specified size. It returns a pointer of type void which can be cast into a
pointer of any form.
SYNTAX
ptr=(cast-type*) malloc(byte-size)

calloc or contiguous allocation method in C is used to dynamically allocate the specified number


of blocks of memory of the specified type. It initializes each block with a default value ‘0’.
SYNTAX
ptr=(cast-type*) calloc(n, element-size)

realloc  or re-allocation method in C is used to dynamically change the memory allocation of a


previously allocated memory.
SYNTAX
ptr=realloc(ptr, newsize)
where ptr is reallocated with new memory size “newsize”

free method in C is used to dynamically de-allocate the memory. The memory allocated using


functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is
used
SYNTAX
free(ptr)

Psuedocode-

int *ar=(int*)malloc(s*sizeof(*ar));
if(ar!=NULL)
||for(i=0;i<s;i++)
||||ar[i]=i;
Program Code-

#include<stdio.h>
int *init_array(int s)
{
int i;
int *ar=(int*)malloc(s*sizeof(*ar));
if(ar!=NULL)
{
for(i=0;i<s;i++)
ar[i]=i;

return ar;
}
else
return 0;
}
int main()
{
int n,i;
printf("enter the size\n");
scanf("%d",&n);
int *a=init_array(n);
printf("Array- \n");
for(i=0;i<n;i++)
printf("%d",a[i]);

}
Practical – 10

Ques)= Write a Program to print nth largest element of the array

Theory- Sorting is the way of organising the elements of array in order and then the nth
element can be retrieved by printing the nth element of that sorted array. Program is
implemented on dynamic array where size of array is fixed using malloc function. Bubble sort
technique is used to achieve this task in which current element is compared with its adjacent
element and then swap the element if adjacent is smaller than the current one. Once the array
is sorted the nth largest element will be present on nth index and can be easily retrieved.

Psuedocode-

Sort(array)
for(i=0 to n)
|| for(j=0 to n-i-1)
||||if(array[j]<array[j+1])
||||swap(array[j],array[j+1])
return array

nth=array[n-1]
printf(nth)

Program Code-
#include<stdio.h>
int *input(int s)
{
int i;
int *ar=(int*)malloc(s*sizeof(*ar));
if(ar!=NULL)
{
printf("\nenter the elements of array\n");
for(i=0;i<s;i++)
scanf("%d",&ar[i]);

return ar;
}
else
return 0;
}

int *sort(int *b,int s)


{
int i,j,temp=0;
for(i=0;i<s;i++)
{
for(j=0;j<s-i-1;j++)
{
if(b[j]<b[j+1])
{
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}

}
}
return b;
}
int main()
{ int n,i;
printf("enter the size\n");
scanf("%d",&n);
int *a=input(n);
printf("Array- \n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
int *st=sort(a,n);
printf("\nSorted Array- \n");
for(i=0;i<n;i++)
{
printf("%d\t ",st[i]);
}
printf("\n Enter the nth position\n");
int p;
scanf("%d",&p);
if(p<=(n))
{
printf("%dth Largest is =%d",p,st[p-1]);
}
else
{printf("invalid request");
}
}
Linked List

A linked list is a linear data structure where each element is a separate object.
Linked list elements are not stored at contiguous location; the elements are linked using
pointers.
Each node of a list is made up of two items - the data and a reference to the next node. The last
node has a reference to null. The entry point into a linked list is called the head of the list. It
should be noted that head is not a separate node, but the reference to the first node. If the list
is empty then the head is a null reference. Here is the representation of linked list

Applications of Linked List

 Linked lists are used to implement stacks, queues, graphs, etc.


 Linked lists let you insert elements at the beginning and end of the list.
 In Linked Lists we don't need to know the size in advance

Types of Linked Lists


There are 3 different implementations of Linked List available, they are

 Singly Linked List


 Doubly Linked List
 Circular Linked List
Singly Linked List
Singly linked lists contain nodes which have a data part as well as an address part i.e. next,
which points to the next node in the sequence of nodes.
The operations we can perform on singly linked lists are insertion, deletion and traversal.

Doubly Linked List


In a doubly linked list, each node contains a data part and two addresses, one for
the previous node and one for the next node.

Circular Linked List


In circular linked list the last node of the list holds the address of the first node hence forming a
circular chain.
There are some operation that can be performed using linked list

INSERTION OPERATION ON SINGLY LINKED LIST


1. Insertion at beginning
2. Insertion at random position
3. Insertion at end

Psuedo code

struct node
||int data
||node *next
head=NULL

Insert_head(int val)
node *t=new node;
t->data=val
t->next=head
head=t

insert_rand_pos(int val,int pos)


node *temp=new node()
while(head!=NULL)
||c++
||if(c==pos)
||||temp->data=val
||||temp->next=headn->next
||||headn->next=temp
||headn=headn->next

Insert_tail(int val)
node *temp=new node()
while(head->next!=NULL)
||head=head->next
head->next=temp
temp->next=NULL
Program Code-

#include<stdio.h>
struct node{
int data;
struct node *next;
};
struct node *head;

void insert_at_head(int d)
{
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->data=d;
temp->next=head;
head=temp;
}

void insert_at_tail(int d)
{
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->data=d;
struct node *headn;
headn=head;
while(headn->next!=NULL)
{
headn=headn->next;
}
headn->next=temp;
temp->next=NULL;

}
void display()
{
struct node *headn;
headn=head;
printf("\n\n List:-\n");
while(headn!=NULL)
{
printf("%d ",headn->data);
headn=headn->next;
}
}
void insert_rand_pos(int p,int d)
{
int c=0;
struct node *headn;
struct node *temp=(struct node*)malloc(sizeof(struct node));
headn=head;
while(headn!=NULL)
{
++c;
if(c==p)
{
temp->data=d;
temp->next=headn->next;
headn->next=temp;
}
headn=headn->next;
}
if(c<p)
printf("\n position entered was invalid \n");
}

int main()
{
head=NULL;
int d,n,i;
printf("enter the number of element to be insert \n");
scanf("%d",&n);
printf("\n enter the data for head\n");
for(i=0;i<n/2;i++)
{
scanf("%d",&d);
insert_at_head(d);
}
printf("\n enter the data for tail\n");
for(i=0;i<n/2;i++)
{
scanf("%d",&d);
insert_at_tail(d);
}
int p,d1;
printf("\n enter the position at which data to be inserted \n");
scanf("%d",&p);
printf("\n enter the data to be inserted \n");
scanf("%d",&d1);
insert_rand_pos(p,d1);
display();
display();
}

DELETION OPERATION ON SINGLY LINKED LIST

Psuedo code

delete_head()
struct node *headn;
headn=head;
head=headn->next;
c=headn->data;
free(headn);
return c

delete_at_pos(int pos)
if(pos=0)
||del_head();
struct node *temp;
while(ehad!=NULL)
||if(c==pos-1)
||||temp=head->next;
||||k=temp->data;
||||head->next=head->next->next;
||||free(temp);
||headn=headn->next

delete_last()
struct node *temp;
while(head->next!=NULL)
||temp=head;
||head=head->next;
int k=headn->data;
temp->next=NULL;
free(headn);
return k;
Program Code-
struct node{
int data;
struct node *next;
};
struct node *head;

int del_head()
{
struct node *headn;
headn=head;
head=headn->next;
int c;
c=headn->data;
free(headn);
return c;
}

int del_last()
{
struct node *headn;
struct node *temp;
headn=head;
while(headn->next!=NULL)
{
temp=headn;
headn=headn->next;
}
int k=headn->data;
temp->next=NULL;
free(headn);
return k;
}

int del_pos(int p)
{
if(p=0)
{
del_head();
}
struct node *headn;
struct node *temp;
int c=0;
int k;
headn=head;
while(headn!=NULL)
{

if(c==p-1)
{
temp=headn->next;
k=temp->data;
headn->next=headn->next->next;
free(temp);

}
headn=headn->next;
}
if(c<p)
printf("\n position entered was invalid \n");
return k;
}
int main()
{
head=NULL;
int k,k1,k2;
k=del_head();
printf("\n deleted element = %d",k);
display();
k1=del_last();
printf("\n deleted element = %d",k1);
display();
printf("\n enter the position at which data to be deleted \n");
scanf("%d",&p);
k2=del_pos(p);
printf("\n deleted element = %d",k2);
display();

}
INSERTION AND DELETION OPERATION ON DOUBLE LINKED LIST
Psuedo code

struct node
||int info;
||struct node *next;
||struct node *prev;

node *start=NULL

add_begin(int val)
struct node *temp= new(struct node)
temp->prev = NULL
temp->info = val
temp->next = start
start->prev = temp
start = temp

add_after(int val,int pos)


struct node *tmp = new(struct node)
node *q=start
tmp->info = val
for(i=0 to pos-1)
||q=q->next
if (q->next == NULL)
||q->next = tmp;
||tmp->next = NULL;
||tmp->prev = q;
else
||tmp->next = q->next;
||tmp->next->prev = tmp;
||q->next = tmp;
||tmp->prev = q

add_last(int val)
struct node *s, *temp
temp = new(struct node)
temp->info = val
temp->next = NULL
if (start == NULL)
||temp->prev = NULL
||start = temp
else
||s = start
||while (s->next != NULL)
||||s = s->next
||||s->next = temp
||||temp->prev = s

delete_head(int val)
struct node *tmp
if (start->info == value)
||tmp = start
||start = start->next
||start->prev = NULL
||free(tmp)

delete_particular(int val)
struct node *q,*tmp
q = start
while (q->next->next != NULL)
||if (q->next->info == value)
||||tmp = q->next
||||q->next = tmp->next
||||tmp->next->prev = q
||||free(tmp)
||q = q->next

delete_last(int val)
struct node *q,*tmp
if (q->next->info == value)
||tmp = q->next
||free(tmp)
||q->next = NULL

Program Code-
include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;


struct node
{
int info;
struct node *next;
struct node *prev;
}*start;
void add_end(int value)
{
struct node *s, *temp;
temp = new(struct node);
temp->info = value;
temp->next = NULL;
if (start == NULL)
{
temp->prev = NULL;
start = temp;
}
else
{
s = start;
while (s->next != NULL)
s = s->next;
s->next = temp;
temp->prev = s;
}
}

void add_begin(int value)


{
if (start == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->prev = NULL;
temp->info = value;
temp->next = start;
start->prev = temp;
start = temp;
cout<<"Element Inserted"<<endl;
}
void add_after(int value, int pos)
{
if (start == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *tmp, *q;
int i;
q = start;
for (i = 0;i < pos - 1;i++)
{
q = q->next;
if (q == NULL)
{
cout<<"There are less than ";
cout<<pos<<" elements."<<endl;
return;
}
}
tmp = new(struct node);
tmp->info = value;
if (q->next == NULL)
{
q->next = tmp;
tmp->next = NULL;
tmp->prev = q;
}
else
{
tmp->next = q->next;
tmp->next->prev = tmp;
q->next = tmp;
tmp->prev = q;
}
cout<<"Element Inserted"<<endl;
}
void delete_element(int value)
{
struct node *tmp, *q;
/*first element deletion*/
if (start->info == value)
{
tmp = start;
start = start->next;
start->prev = NULL;
cout<<"Element Deleted"<<endl;
free(tmp);
return;
}
q = start;
while (q->next->next != NULL)
{
/*Element deleted in between*/
if (q->next->info == value)
{
tmp = q->next;
q->next = tmp->next;
tmp->next->prev = q;
cout<<"Element Deleted"<<endl;
free(tmp);
return;
}
q = q->next;
}
/*last element deleted*/
if (q->next->info == value)
{
tmp = q->next;
free(tmp);
q->next = NULL;
cout<<"Element Deleted"<<endl;
return;
}
cout<<"Element "<<value<<" not found"<<endl;
}

void display_dlist()
{
struct node *q;
if (start == NULL)
{
cout<<"List empty,nothing to display"<<endl;
return;
}
q = start;
cout<<"The Doubly Link List is :"<<endl;
while (q != NULL)
{
cout<<q->info<<" <-> ";
q = q->next;
}
cout<<"NULL"<<endl;
}
int main()
{
int choice, element, position;
start=NULL;
do
{
cout<<"\n-------Main Menu--------";
cout<<"\n1.Add at end";
cout<<"\n2.Add at begining";
cout<<"\n3.Add after position";
cout<<"\n4.Delete";
cout<<"\n5.Display";
cout<<"\n6.Quit"<<endl;
cout<<"\nEnter your choice : ";
cin>>choice;
switch ( choice )
{
case 1:
cout<<"\nEnter the element: ";
cin>>element;
add_end(element);
cout<<endl;
break;
case 2:
cout<<"\nEnter the element: ";
cin>>element;
add_begin(element);
cout<<endl;
break;
case 3:
cout<<"\nEnter the element: ";
cin>>element;
cout<<"\nInsert Element after postion: ";
cin>>position;
add_after(element, position);
cout<<endl;
break;
case 4:
if (start == NULL)
{
cout<<"\nList empty,nothing to delete";
break;
}
cout<<"\nEnter the element for deletion: ";
cin>>element;
delete_element(element);
cout<<endl;
break;
case 5:
display_dlist();
cout<<endl;
break;
}
}while(choice!=6);
}
INSERTION AND DELETION OPERATION ON CIRCULAR LINKED LIST

Psuedo code

struct node
||int info
||node *next

node *last=NULL

add_begin(int val)
struct node *temp= new(struct node)
temp->info = value
temp->next = last->next
last->next = temp

add_after(int val,int pos)


struct node *temp, *s
s = last->next
for (int i = 0;i < pos-1;i++)
||s = s->next
temp = new(struct node)
temp->next = s->next
temp->info = value
s->next = temp
if (s == last)
||last=temp

add_end(int value)
struct node *temp;
temp = new(struct node);
temp->info = value;
if (last == NULL)
||last = temp;
||temp->next = last;
else
||temp->next = last->next;
||last->next = temp;
||last = temp;

delete_element(int value)
struct node *temp, *s;
s = last->next
if (last->next == last && last->info == value)
||temp = last
||last = NULL
||free(temp)
if (s->info == value) /*First Element Deletion*/
||temp = s
||last->next = s->next
||free(temp)
while (s->next != last)
|| if (s->next->info == value) /*Deletion of Element in between*/
||||temp = s->next
||||s->next = temp->next
||||free(temp)
||s = s->next
if (s->next->info == value) /*Deletion of last element*/
||temp = s->next
||s->next = last->next
||free(temp)
||last = s

Program Code-
#include<iostream>
using namespace std;
struct node
{
int info;
struct node *next;
}*last;
void add_end(int value)
{
struct node *temp;
temp = new(struct node);
temp->info = value;
if (last == NULL)
{
last = temp;
temp->next = last;
}
else
{
temp->next = last->next;
last->next = temp;
last = temp;
}
}

void add_begin(int value)


{
if (last == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->info = value;
temp->next = last->next;
last->next = temp;
}

void add_after(int value, int pos)


{
if (last == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp, *s;
s = last->next;
for (int i = 0;i < pos-1;i++)
{
s = s->next;
if (s == last->next)
{
cout<<"There are less than ";
cout<<pos<<" in the list"<<endl;
return;
}
}
temp = new(struct node);
temp->next = s->next;
temp->info = value;
s->next = temp;
if (s == last)
{
last=temp;
}
}

void delete_element(int value)


{
struct node *temp, *s;
s = last->next;
/* If List has only one element*/
if (last->next == last && last->info == value)
{
temp = last;
last = NULL;
free(temp);
return;
}
if (s->info == value) /*First Element Deletion*/
{
temp = s;
last->next = s->next;
free(temp);
return;
}
while (s->next != last)
{
/*Deletion of Element in between*/
if (s->next->info == value)
{
temp = s->next;
s->next = temp->next;
free(temp);
cout<<"Element "<<value;
cout<<" deleted from the list"<<endl;
return;
}
s = s->next;
}
/*Deletion of last element*/
if (s->next->info == value)
{
temp = s->next;
s->next = last->next;
free(temp);
last = s;
return;
}
cout<<"Element "<<value<<" not found in the list"<<endl;
}

void display_list()
{
struct node *s;
if (last == NULL)
{
cout<<"List is empty, nothing to display"<<endl;
return;
}
s = last->next;
cout<<"Circular Link List: "<<endl;
while (s != last)
{
cout<<s->info<<"->";
s = s->next;
}
cout<<s->info<<endl;
}
int main()
{
int choice, element, position;
last=NULL;
do{cout<<"\nMain Menu";
cout<<"\n1.Add at end";
cout<<"\n2.Add at beginning";
cout<<"\n3.Add after";
cout<<"\n4.Delete";
cout<<"\n5.Display";
cout<<"\n6.Quit";
cout<<"\nEnter your choice : ";
cin>>choice;
switch(choice)
{case 1:
cout<<"\nEnter the element: ";
cin>>element;
add_end(element);
cout<<endl;
break;
case 2:
cout<<"\nEnter the element: ";
cin>>element;
add_begin(element);
cout<<endl;
break;
case 3:
cout<<"\nEnter the element: ";
cin>>element;
cout<<"\nInsert element after position: ";
cin>>position;
add_after(element, position);
cout<<endl;
break;
case 4:
if (last == NULL)
{cout<<"\nList is empty, nothing to delete";
break;
}
cout<<"\nEnter the element for deletion: ";
cin>>element;
delete_element(element);
cout<<endl;
break;
case 5:
display_list();
break;
}
}while(choice!=6);
}
Function Pointer

Generally, pointers is a variable that stores/points the address of another variable.It is used to
allocate memory dynamically during runtime
Function pointers are like normal pointers but they have the capability to point to a function.
Now lets check how to declare pointers to the following function:-

int add (int a, int b) int main()


{ ----------------------> {
int(*ptr)(int,int)
Return a+b; }
} HERE ptr is a pointer which is pointing to a function
Containing two integers argument and it returns an
Integer value.

How to assign the address of a function to a function pointer


int main()
{
int (*ptr)(int,int)=&add;
}

unlike normal pointers, a function pointer points to code, not data. Typically a function pointer
stores the start of executable code.
Also, we do not allocate de-allocate memory using function pointers

Let us now solved some examples through the function pointers


Ques-Write a program to implement addition and subtraction operation using
pointer to the function call

Theory: Here first declare add and sub functions that takes 2 input integers values as an
argument that is entered by user.Now using same pointer variable both the function is
invoked and return the result in integer variable

Psuedocode-
int add(int a,int b)
return a+b
int sub(int a,int b)
return a-b

main()
{
Int(*abc)(int,int)
abc=add
s=abc(a,b)
abc=sub
d=abc(a,b)

Sourcecode-
#include<stdio.h>
int add(int a,int b)
{
return (a+b);
}
int sub(int a,int b)
{
return (a-b);
}
int main()
{ int a,b;
int(*abc)(int,int);
abc=add;
printf("enter the values of a,b\n");
scanf("%d%d",&a,&b);
int s=abc(a,b);
abc=sub;
int d=abc(a,b);
printf("\n Result of sum=%d",s);
printf("\n Result of difference=%d",d);
}
STRINGS

Strings are one-dimensional array of characters terminated by a null character '\0'. Thus a null-
terminated string contains the characters that comprise the string followed by a null.
Strings are always enclosed by double quotes, Whereas, character is enclosed by single quotes
in C.
EXAMPLE OF STRING
char abc[6] = {'H', 'e', 'l', 'l', 'o', '\0'}

Memory Representation of String

Here user do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array.The mobile
number which consist of 10 numbers can be treated as string if enclosed under ‘ ‘ or “ “. Hence
it is also known as an array of characters. Operation on strings are not similar to that of array.

C library functions for strings (string.h)


C provides a library for strings. C string library functions do not allocate space for the strings
they manipulate, nor do they check that you pass in valid strings; it is up to your program to
allocate space for the strings that the C string library will use
Here is some of the functions in the Stardard C string libarary (string.h)

String
functions Description

strcat ( ) Concatenates str2 at the end of str1

strncat ( ) Appends a portion of string to another

strcpy ( ) Copies str2 into str1

Copies given number of characters of one string to


strncpy ( ) another

strlen ( ) Gives the length of str1


Returns 0 if str1 is same as str2. Returns <0 if strl <
strcmp ( ) str2. Returns >0 if str1 > str2

Same as strcmp() function. But, this function negotiates


strcmpi ( ) case.  “A” and “a” are treated as same.

strchr ( ) Returns pointer to first occurrence of char in str1

strrchr ( ) last occurrence of given character in a string is found

strstr ( ) Returns pointer to first occurrence of str2 in str1

strrstr ( ) Returns pointer to last occurrence of str2 in str1

strdup ( ) Duplicates the string

strlwr ( ) Converts string to lowercase

strupr ( ) Converts string to uppercase

strrev ( ) Reverses the given string

strset ( ) Sets all character in a string to given character

It sets the portion of characters in a string to given


strnset ( ) character

strtok ( ) Tokenizing given string using delim

Now some of these string function will be implemented without using string library function

Ques-Write a program to implement string functions without using (string.h)


header file
Theory: In this program different strings function will be implemented like comparison
between strings, copy of string ,to count no of characters in a string .All these tasks are
performed without using library function
Count number of characters in a string
#include<stdio.h>
int stringlen(char str1[50])
{ int ret=0;
while(str1[ret]!='\0')
{
ret++;
}
return ret;
}
void main()
{
char str1[50];
int ret=0;
printf("Enter a string:\n");
gets(str1);
ret=stringlen(str1);
printf("%s has %d elements..\n", str1, ret);
}
Copy String without using strcpy()

#include<stdio.h>
void stringcpy(char *source, char *dest)
{
int i=0;
while(source[i]!='\0')
{
dest[i] = source[i];
i++;
}

dest[i+1] = '\0';
}

void main()
{
char str1[50];
char str2[50];
printf("Enter the string: ");
gets(str1);
stringcpy(str1, str2);
printf("String 1: ");
puts(str1);
printf("\nString 2: ");
puts(str2);}
Swap Strings without using strcpy()

#include<stdio.h>
void stringcpy(char *source, char *dest)
{
int i=0;
while(source[i]!='\0')
{
dest[i] = source[i];
i++;
}
dest[i+1] = '\0';
}
void main()
{
char str1[50];
char str2[50];
char str3[50];

printf("Enter first string: ");


gets(str1);

printf("Enter second string: ");


gets(str2);

stringcpy(str1, str3);
stringcpy(str2, str1);
stringcpy(str3, str2);

printf("String 1: ");
puts(str1);
printf("\nString 2: ");
puts(str2);
}

String Comparison
#include<stdio.h>
int stringcmp(char str1[50], char str2[])
{
int ret=0;
int i=0;
while(str1[i]==str2[i])
{
if(str1[i]=='\0')
{
ret=1;
}
i=i+1;
}
return ret;
}
void main()
{ char str1[50], str2[50];
int ret=0;
printf("Enter two strings to compare:\n");
gets(str1);
gets(str2);
ret=stringcmp(str1, str2);
if(ret==1)
{
printf("%s and %s are same..\n", str1, str2);
}
else
{
printf("%s and %s are not same..\n", str1, str2);
}
}
Ques - Write a program to sort the student record i.e. name and roll number
alphabetically where each record is entered by user roll number wise

Theory- To implement this program Structure named student needs to be defined which
comprise of two things that is integer type roll number and string or character type name.
And here also we need to use a sorting technique and strcmp i.e. string compare function.

Psuedo code-

name_Sort(char names[])
for(i=0 to n-1)
||for(j=0 to n-i-1)
||||if(strcmp(names[j],names[j+1])>0)
||||||swap(names[j],names[j+1])

Program Code-
#include<stdio.h>
int slen(char *s)
{
int i;
for(i=0;s[i]!='\0';)
i++;
return i;
}

int scmp(char *s1, char *s2)


{
int i;
for(i=0;s1[i]==s2[i];i++)
{
if(s1[i]=='\0')
return 0;
}
return(s1[i]-s2[i]);
}

void scpy(char *s1, char *s2)


{
int i;
for(i=0;s2[i]!='\0';i++)
{
s1[i]=s2[i];
}
s1[i]='\0';
}

struct recorrd
{
int *rno;
char **names;
};
int main()
{
struct record;
int n;
printf("enter the no of students in class \n");
scanf("%d",&n);
record.rno=(int*)malloc(n*sizeof(int));
record.names=(char**)malloc(n*sizeof(char*));
char temp[100],temp1[100];
int i,len;
for(i=0;i<n;i++)
{
record.rno[i]=i+101;
printf("\n Enter the name of student %d : ",i+1);
scanf("%s",temp);
len=slen(temp);
record.names[i]=(char*)malloc(len*sizeof(char));
scpy(record.names[i],temp);
}

int p,q;
int f;
for(p=0;p<n;p++)
{
for(q=0;q<n-p-1;q++)
{
if(scmp(record.names[q],record.names[q+1])>0)
{
scpy(temp1,record.names[q]);
f=record.rno[q];
scpy(record.names[q],record.names[q+1]);
record.rno[q]=record.rno[q+1];
scpy(record.names[q+1],temp1);
record.rno[q+1]=f;
}
}
}

printf("\n Records after sorting of names alphabetically \n");


int x;
for(x=0;x<n;x++)
{
printf("Roll no= %d \t",record.rno[x]);
printf("Name-%s \n",record.names[x]);
}
}
Ques - Write a program to Reverse a String Using Stack

Theory- The stack is a linear data structure. Stack array list follows the Last in First Out
principle. The element gets to add up at the TOP and deleted from the TOP.In this program
push and pop function is define. The Push function checks whether the stack is full or not. If the
stack is full it’s not do anything but if not it takes input from the user and push it to the top of
the stack. The Pop function checks whether the stack is empty, if not then it prints the topmost
item and deletes it from the stack. Now, user inputs a string and Every character of that string
pushed in the stack and then we pop every character out. It makes it look like the string is just
reversed.

Psuedo code-

Push(char c)
If(top<size)
||s[top++]=c
Else
||print(stack overflow)

Pop()
If(top>0)
||c=s[--top]
||return(c);
Else
||print(stack empty)
||return \0

Program Code-

#include<stdio.h>
#include<string.h>
#define SIZE 100
int top=0;
char s[SIZE];
void Push(char c)
{
if(top<SIZE)
{
s[top++]=c;
}
else
{
printf("Stack Overflow.\n");
}
}
char Pop()
{
char c;
if(top>0)
{
c=s[--top];
return(c);
}
else
{
printf("Stack Empty.\n");
return'\0';
}
}
void main()
{
char inpstr[SIZE];
int i;
printf("Input String:\n");
gets(inpstr);
for(i=0; i<strlen(inpstr); i++)
{
Push(inpstr[i]);
}
for(i=0; i<strlen(inpstr); i++)
{
inpstr[i]=Pop();
}
printf("Reversed String= %s", inpstr);
}
Ques - Write a program to convert the entered string in uppercase and check
whether the string is palindrome or not.

Theory- A number or a word which remains the same, even after being reversed is called
palindrome. For example, mom, radar, or the number 45654, all are palindrome
For this function like strrev and strcmp are used because strrev read the string from right to left
and strcmp compares strings on their ASCII value and return 0 if they are same.
In order to convert the string in uppercase all character will posses ASCII value from 65-91 while
for lower case it varies from 97-122. Therefore subtracting 32 from ASCII value of lowercase
character will result in uppercase character.

Psuedo code-

Upper(char *s)
for(i=0 to s[i]!=’\0’)
||if(s[i]<=122 && s[i] >=97)
||||s[i]=s[i]-32

Palindrome(char *s)
s1=strrev(s)
if(strcmp(s,s1)==0)
print(palindrome)

Program Code-

#include<stdio.h>
int scmp(char *s1, char *s2)
{
int i;
for(i=0;s1[i]==s2[i];i++)
{
if(s1[i]=='\0')
return 0;
}
return(s1[i]-s2[i]);
}

int slen(char *s)


{
int i;
for(i=0;s[i]!='\0';)
i++;
return i;
}

void srev(char s1[],char s2[],int l)


{
int i,j=0;
for(i=l-1;i>=0;i--)
s2[j++]=s1[i];

s2[j]='\0';
printf("%s",s2);
}
void toup(char s[])
{
int i;
for(i=0;s[i]!='\0';i++)
{
if(s[i]>=97&&s[i]<=122)
{
s[i]-=32;
}
}
printf("\n upper case %s \n",s);
}
int main()
{

char s1[100];
printf("enter the string \n");
scanf("%s",&s1);
int l=slen(s1);
toup(s1);
char s2[100];
srev(s1,s2,l);
if(scmp(s1,s2)==0)
printf("\n palindrome");
else
printf("\n not plaindrome");
}
File Handling

File handling refers to the task of storing data in the form of input or output produced by
running C programs in data files, namely, a text file or a binary file for future reference and
analysis. There is a need for file handling in C because it helps in preserving the data or
information generated after running the program,their is no need to worry about the problem
of storing data in bulk and also it saves time

Their are different operations associated with file handling. Some of them are:-

Creating a new file: fopen()


Opening an existing file in your system: fopen()
Closing a file: fclose()
Reading characters from a line: getc()
Writing characters in a file: putc()
Reading a set of data from a file: fscanf()
Writing a set of data in a file: fprintf()
Reading an integral value from a file: getw()
Writing an integral value in a file: putw()
Setting a desired position in the file: fseek()
Getting the current position in the file: ftell()
Setting the position at the beginning point: rewind()

 A file-type pointer needs to be declared when working with files. It establishes communication
between the file and the program.

The basic syntax of opening a file is:

*fpointer = FILE *fopen(const char *file_name, const char *mode);


Ques - Write a program to count the number of characters, words and lines in a text
file.

Theory- The file will open in read mode using ‘fopen’ function where path of the file is passed
as an argument and ‘r’ specifying the read mode. To count the number of characters in the text
file, file will be read character by character till the file pointer reached the end of file. For
counting number of words every space will be checked and every word after new line character
will also be included while for counting lines every new line character will be taken into
consideration

Psuedo code-
FILE *f1
f1=fopen(“path”,r)
while(ch=fgetc(f1)!=eof)
||characters++
||if (ch == '\n' || ch == '\0')
||||lines++
||if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
||words++;
print(character,lines,words)

Program Code-

#include<stdio.h>
int main()
{
FILE *f;
char ch;
int characters = 0,words = 0,lines = 0;
char path[120];
printf("Enter source file path: ");
scanf("%s", path);

f=fopen(path,"r");
if(f==NULL)
{
printf("\n empty file\n");
}
while ((ch = fgetc(f)) != EOF)
{
characters++;
if (ch == '\n' || ch == '\0')
lines++;

if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')


words++;
}

if (characters > 0)
{
words++;
lines++;
}

printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);
fclose(f);
return 0;

}
Ques= Write a program to copy the data of one file to another using command
line arguments

Theory- It is possible to pass some values from the command line to your C programs when
they are executed. These values are called command line arguments. The command line
arguments are handled using main() function arguments where argc refers to the number of
arguments passed, and argv[] is a pointer array which points to each argument passed to the
program. 
For this program one of the file will open in read mode while the other one in write mode.
While passing the argument through command line, we need to specify how many argument
we need to pass. Moreover, we need to check whether the file opened should not be an empty
file.

Psuedo code-

File *f1,*f2
f1=fopen(“path”,r)
f2=fopen(“path”,w)
while(ch=getchar(f1)!=eof)
||fputc(ch,f2)
fclose(f1)
fclose(f2)

Program Code-

#include<stdio.h>
int main(int argc, char *argv[])
{
FILE *fs,*ft;
int ch;
if(argc!=3)
{
printf("Invalid numbers of arguments.");
return 1;
}
fs=fopen(argv[1],"r");
if(fs==NULL)
{
printf("Can't find the source file.");
return 1;
}
ft=fopen(argv[2],"w");
if(ft==NULL)
{
printf("Can't open target file.");
fclose(fs);
return 1;
}
while((ch=getchar(fs))!=EOF)
{
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
return 0;
}

You might also like