Fundamental of Computer Science Practical File
Fundamental of Computer Science Practical File
Function Calling itself is called Recursion. In Recursion when each time the function call itself
with a slightly Simpler Version of the original Problem
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
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
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)
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
Average case
Worst case
Program Code:-
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<ctime>
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();
}
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);
}
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......
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
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:-
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.
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];
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
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
#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++;
}
return 0;
}
Practical – 8
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()
Psuedocode-
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);
}
Practical – 9
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)
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
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;
}
}
}
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
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_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();
}
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_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>
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_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 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:-
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
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'}
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.
String
functions Description
Now some of these string function will be implemented without using string library function
#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];
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;
}
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;
}
}
}
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]);
}
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:-
A file-type pointer needs to be declared when working with files. It establishes communication
between the file and the program.
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 (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;
}