Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 27

C Programming and Data Structures

Experiments

1. A Simple C Program
Problem Statement:
Write a program that prints the square of an integer.

Algorithm:
1. Use an integer variable n.
2. Read the value from the console using scanf() function.
3. Use the arithmetic operator * (multiply) to generate the square of n.
4. Use the printf() function to print the output.

Step 1 Start
Step 2 N
Step 3 Input a number
from Keyboard
Step 4 n=n*n
Step 5 Print the output
Step 6 End

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
n=n*n;
printf("The square of the entered number is:\n%d",n);
getch();
}

Output:
Enter a number: 10
The square of the entered number is:
100

1
2. Palindrome Number
Problem Statement:
Write a program to check whether the given number is a Palindrome.

Algorithm:
A Palindrome number is a number which read from either left to right or right to left
gives the same value.
1. Read the number from the console and store it in an integer variable n.
2. Declare two more integer variables mod and n1.
3. Assign the number n to n1
4. Use while loop
5. Do the modulus operation on n1 and store it in an integer variable mod
6. Do the operation of storing the result of mod operation in step 5 to the variable
rev.
7. Continue the steps 5 and 6 until the value of n1 becomes zero.
8. Compare the value of the variables rev to the variable n
9. If the values in both the variables are same, then print the number is
Palindrome; else print that it is not a Palindrome.

Step 1 Start
Step 2 number1, remainder1, sum0, temp1
Step 3 Input a number from Keyboard
Step 4 numbertemp
Step 5 While number is greater than 0

Step 6 remainder= number mod 10


Step 7 Number divide by or equal to 10
Step 8 sum=sum*10+remainder
Step 9 If sum==temp
Step 10 Print the output as Palindrome
Step 11 else go to Step 12
Step 12 Print the output as not a Palindrome
Step 13 End

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

1
int number, remainder, sum=0, temp;
clrscr();
printf("Please enter a number");
scanf("%d", &number);
temp=number;
while(number>0)
{
remainder=number%10;
number/=10;
sum=sum*10+remainder;
}
if(sum==temp)
printf("\n%d is a Palindrome", temp);
else
printf("\n%d is not a Palindrome", temp);
getch();
}

Output:
Please enter a number 252
252 is a Palindrome

Please enter a number 255


252 is not a Palindrome

1
3. Matrix Multiplication
Problem Statement:
Write a program to multiply two matrices of any order.

Algorithm:
1. Declare three integer arrays
2. Declare three integer variables that would be the indices to the three arrays
declared in step 1.
3. Ask the user to enter the dimensions of the twp matrices to be multiplied.
4. Now check whether the matrices can be multiplied by applying the following rule:
“Two matrices can be multiplied if the column value of the first matrix is
same as the row value of the second matrix”.
5. If the result of step 4 evaluate to true then:
5.1. Print a message on the console that the matrices can be multiplied.
5.2. Ask the user to enter the values of the first and second matrices.
5.3. Now initialize all the values of the resultant matrix to zeros.
5.4. Now perform the matrix multiplication on both matrices and store the product
in the resultant matrix.
5.5. Print the values of the resultant matrix in a tabular format as shown in the
example.
6. If the result of step 4 evaluates to false, then print a message on the console
stating that these matrices cannot be multiplied.
7. Exit from the program.

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int A[10][10], B[10][10], C[10][10], n, i, j;
clrscr();
printf("Enter the order of the Matrix\n");
scanf("%d", &n);
printf("Enter the First Matrix Numbers\n");
for(i=0; i<n; i++)
for(j=0; j<n; j++)
scanf("%d", &A[i][j]);
printf("Enter the Second Matrix Numbers\n");

1
for(i=0; i<n; i++)
for(j=0; j<n; j++)
scanf("%d", &B[i][j]);
for(i=0; i<n; i++)
for(j=0; j<n; j++)
C[i][j]=A[i][j]*B[i][j];
printf("The product of the above two Matrix is\n");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
printf("%d\t", C[i][j]);
printf("\n");
}
getch();
}

Output:

Enter the order of the Matrix


2
Enter the First Matrix Numbers
2 3 4 5
Enter the Second Matrix Numbers
2 4 6 8
The Product of the above two Matrix is
4 12
24 40

1
4. Number Search
Problem Statement:
Write a program that will accept a string and character to search. The program will
call a function, which will search for the occurrence position of the character in the
string and return its position. Function should return -1 if the character is not found
in the input string.

Algorithm:

1. Read the input string from the user. This could be done in the following ways:
a. Read an array of characters into a pre-declared character array.
b. Read it using a scanf function
2. Read a character from the user which has to be searched in the above string.
3. Declare an index into the character string or array and use the comparison
operator and do the search.
4. If the character is found, update its occurrence in a counter variable, and proceed
with the search process until the end of the string is
encountered and update the counter variable accordingly.
5. If the character is not found, then print an error message stating that the search
character is not found.

Program:

#include<stdio.h>
void main( )
{
int array[10];
int i, N, keynum, found=0;
clrscr( );
scanf(“%d”,&N);
printf(“Enter the elements one by one\n”);
for(i=0;i<N;i++)
{
scanf(“%d”,&array[i]);
printf(“Input array is\n”);
for(i=0;i<N;i++)
{
printf(“%d\n”,arrayi]);
}
printf(“Enter the element to be searched\n”);
scanf(“%d”,&keynum);
for(i=0;i<N;i++)
{
if(keynum==array[i])
{
found=1;
break;
}
}

1
if(found==1)
printf(“SUCCESSFUL SEARCH\n”);
else
printf(“SEARCH IS FAILED”);
getch( );
}

Output:

Enter the value of N


5
Enter the elements one by one
23
12
56
43
89
Input array is
23
12
56
43
89
Enter the element to be searched
56
SUCCESSFUL SEARCH

Enter the value of N


3
Enter the elements one by one
456
213
879
Input array is
456
213
879
Enter the element to be searched
100
SEARCH IS FAILED

1
5. Calculator Implementation
Problem Statement:
Write a program to implement a calculator to perform all the four basic arithmetic
operation on integers.

Algorithm:
1. Declare 4 functions add, sub, mul, div that return the result as an integer value.
2. Write the coding in those functions to perform the intended operations.
3. All these four functions should be declared outside the main functions in a single
program file.
4. use a switch case function to take the input form the user and perform the
appropriate call to the function.
5. Now display the result.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
char ch;
clrscr();
printf("Main Menu\n1. Addition\n2. Subtraction\n3. Multiplication\n4.
Division\n");
printf("~~~~~~~~~~~~~~~~~\n");
printf("Please choose one of the program\n");
ch=getche();
printf("\nPlease enter the first number:\n");
scanf("%d",&a);
printf("Please enter the second number:\n");
scanf("%d",&b);
switch(ch)
{
case '1':
c=a+b;
break;
case '2':
c=a-b;
break;
case '3':
c=a*b;
break;
case '4':

1
c=a/b;
break;
default:
printf("~~~Invalid Input~~~\n");
}
printf("\nThe result is %d",c);
getch();
}

Output:

Main Menu
1. Addition
2. Subtraction
3. Multiplication
4. Division
~~~~~~~~~~~~
Please choose one of the program
1
Please enter the first number:
50
Please enter the second number:
2
The result is 57

Main Menu
1. Addition
2. Subtraction
3. Multiplication
4. Division
~~~~~~~~~~~~
Please choose one of the program
2
Please enter the first number:
50
Please enter the second number:
2
The result is 48.00

Main Menu
1. Addition
2. Subtraction
3. Multiplication
4. Division
~~~~~~~~~~~~
Please choose one of the program
3

1
Please enter the first number:
50
Please enter the second number:
2
The result is 100

Main Menu
1. Addition
2. Subtraction
3. Multiplication
4. Division
~~~~~~~~~~~~
Please choose one of the program
4
Please enter the first number:
50
Please enter the second number:
2
The result is 25

1
6. Stack Implementation
Problem Statement:
Write a program to implement linked lists using pointers

Algorithm:
A better arrangement for using an array takes account of the fact that insertions and
deletions occur only at the top. We can anchor the bottom of the stack at the bottom
(high-indexed end) of the array, and let the stack grow towards the top (low-indexed
end) of the array. A cursor called top indicates the current position of the first stack
element.
The following data structure may be used for this implementation:
type
STACK = record
top: integer;
elements: array[1 ..maxlength] of elementtype
end;
The five basic operations which are to be implemented on a Stack are listed below:

procedure MAKENULL(var S: STACK)


begin
S.top = maxlength + 1;
end; { MAKENULL}
function EMPTY(S: STACK): boolean;

begin

if S.top> maxlength then


return true;
else
return false;
end; {EMPTY}

function TOP (var S:Stack) :elementtype;


begin
if EMPTY(S) then
error(Stack is empty’)
else
return (S.elements[S.top])
end; {TOP}

procedure POP( var S: STACK);


begin
if EMPTY(S) then
error(’Stack is empty’)
else
S.top = S.top + I
end; {POP}

procedure Push( x: elementtype; var S: STACK);


begin
if S.top = 1 then
error(“Stack is full’)
else begin

1
S.top = S.top —1;
S.elements[S.top] = x
end
end; {PUSH}

Program:
#include<stdio.h>
#include<conio.h>
# define MAX 4
struct stack
{
int top;
int items[MAX];
};
int empty(struct stack *);
int full(struct stack *);
void push(struct stack *, int);
int pop(struct stack *);
void display(struct stack *);
int empty(struct stack *p)
{
return((p->top==-1)?1:0);
}
int full(struct stack *p)
{
return(p->top==(MAX-1)?1:0);
}
void push(struct stack *p, int item)
{
p->items[++p->top]=item;
}
int pop(struct stack *p)
{
return(p->items[p->top--]);
}
void display(struct stack *p)
{
int i;
printf("\nStack elements are:");
for(i=p->top; i>=0; i--)
printf("%d\t",p->items[i]);
}
void main()
{
int ch,x;
struct stack s;
s.top=-1;

1
clrscr();
do
{
printf("\n\n\t Menu\n1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter your choice\n\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(full(&s))
printf("\n stack full\n");
else
{
printf("Enter elements to be pushed:\n");
scanf("%d",&x);
push(&s,x);
display(&s);
}
break;
case 2:
if(empty(&s))
printf("Empty Stack");
else
{
printf("\n The deleted element is:%d\t",pop(&s));
display(&s);
}
break;
case 3:
if(empty(&s))
printf("\n Stack Empty");
else
{
display(&s);
}
break;
case 4:
printf("Exit");
break;
default:
printf("Invalid Choice\n");
}
}
while(ch!=4);
getch();
}

1
Output:

Menu
1. Push
2. Pop
3. Display
4. Exit
Enter your choice
1
Enter elements to be pushed:
10

Stack elements are: 10


Menu
1. Push
2. Pop
3. Display
4. Exit
Enter your choice
1
Enter elements to be pushed:
20

Stack elements are: 20 10


Menu
1. Push
2. Pop
3. Display
4. Exit
Enter your choice
1
Enter elements to be pushed:
30

Stack elements are: 30 20 10


Menu
1. Push
2. Pop
3. Display
4. Exit
Enter your choice
1
Enter elements to be pushed:
40

Stack elements are: 40 30 20 10


Menu

1
1. Push
2. Pop
3. Display
4. Exit
Enter your choice
1

Stack Full
Menu
1. Push
2. Pop
3. Display
4. Exit
Enter your choice
2

The deleted item is: 40


Stack elements are: 30 20 10

Menu
1. Push
2. Pop
3. Display
4. Exit
Enter your choice
2

The deleted item is: 30


Stack elements are: 20 10

Menu
1. Push
2. Pop
3. Display
4. Exit
Enter your choice
2

The deleted item is: 20


Stack elements are: 10

Menu
1. Push
2. Pop
3. Display
4. Exit

1
Enter your choice
2

The deleted item is: 10


Stack elements are:

Menu
1. Push
2. Pop
3. Display
4. Exit
Enter your choice
2
Empty Stack

Menu
1. Push
2. Pop
3. Display
4. Exit
Enter your choice
3

Stack Empty

Menu
1. Push
2. Pop
3. Display
4. Exit
Enter your choice
4
Exit

1
7. Linked List Implementation
Problem Statement:
Write a program to implement linked lists using pointers.

Algorithm:
This implementation uses pointers to link successive list elements. This
implementation frees us from using contiguous memory for storing a list. However,
the price paid is the extra space for pointers.
In this representation, a list is made up of cells, each cell consisting of an
element of the list and a pointer to the next cell on the list. If the list is a1, a2… an,
the cell holding a1 has a pointer to the cell holding ai+1, for I = 1, 2,..., n-1.
The cell holding an has a NULL pointer.
There is a header cell pointing to the cell holding a1 the header holds no element. In
the case of an empty list, the header’s pointer is NULL and there are no other cells.

The position i will be a pointer to the cell holding the pointer to ai for I = 1, 2,.. ,n.
Position 1 is a pointer to the header, and position END(L) is a pointer the last cell of
L (the linked list).

type
celltype = record
element: elementtype;
Next: celltype
end;
LIST = celltype
Position =celltype;

END(L): A function that works by moving the pointer q down the list from the
header, until it reaches the end, which is detected by the fact that q points to a cell
with a NULL pointer.
procedure INSERT(x: elementtype; p:position)
var
temp:position;
Begin
temp = p.next;
new(p.next);
p.next.element = x;
p.next.next = temp
end;
procedure DELETE(p:position)
begin
p.next = p.next.next;
end; {DELETE}
function LOCATE(x: elementtype; L:LIST) : position
var
p: position;
begin

1
p = L;
while p.next <> NULL
if p.next.element = x then
return(p) {if not found)
end; {LOCATE}
function MAKENULL(var L: LIST) : position
begin
new(L);
L.next = NULL;
Return(L);
end: {MAKENULL}

Program:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define NULL 0
typedef struct record
{
char name[20];
int roll;
struct record *next;
}rec;
int flag=0;
main( )
{
rec *new,*app,*append(rec *pt),*ins(rec *pt),*del(rec *pt);
char nm[20],choice;
int rl;
void list(rec *pt,int);
new=(rec *) malloc(sizeof(rec));
app=new;
do
{
choice=menu( );
switch(choice)
{
case '1':
app=append(app);
break;
case '2':
heading( );
list(new,1);
getch( );
break;
case '3':

1
new=ins(new);
break;
case '4':
new=del(new);
break;
case '5':
exit(0);
default:
printf("Your choice is invalid- Try Again");
getch( );
}
}
while(1);
}
rec* append(rec *record)
{
printf("\nName please [X to exit]:");
fflush(stdin);
gets(record->name);
if(strcmpi(record->name,"x")==0)
{
record->next=NULL;
return(record);
}
else
{
printf("\nRoll no. : ");
fflush(stdin);
scanf("%d",&record->roll);
record->next = (rec *)malloc(sizeof(rec));
append(record->next);
}
}
void list(rec *rd,int i)
{
if(rd->next==NULL)
return;
printf("%3d %-20s %5d\n", i++, strupr(rd->name), rd->roll);
list(rd->next,i);
}
rec* ins(rec *record)
{
char word[20];
rec *find(rec *,char *),*new1,*local;
printf("\nType NAME, before the new record to be inserted : ");
fflush(stdin);
gets(word);

1
local=find(record,word);
if(local==NULL)
{
printf("Record not found ");
getch();
return(record);
}
new1=(rec *)malloc(sizeof(rec));
printf("\nEnter Students name to be inserted ..");
fflush(stdin);
gets(new1->name);
printf("\nEnter roll no:");
fflush(stdin);
scanf("%d", &new1->roll);
if(flag==0)
{
new1->next=local->next;
local->next=new1;
return(record);
}
else
{
new1->next=record;
record=new1;
return(record);
}
}
rec* del(rec *record)
{
rec *find(rec *, char *), *local, *temp;
char word[20];
printf("\nEnter students name to be deleted:");
fflush(stdin);gets(word);
local=find(record,word);
if(local==NULL)
{
printf("Record not found ");
getch( );
return(record);
}
if(flag==0)
{
temp=local->next;
local->next=local->next->next;
free(temp); return(record);
}
else

1
{
temp=record;
record=local->next;
free(temp); return(record);
}
}
rec *find(rec *rd, char *nm)
{
flag=0;
if(strcmpi(rd->name, nm)==0)
{
flag=1; return(rd);
}
if(strcmpi(rd->next->name,nm)==0)
return(rd);
else
{
if(rd->next->next==NULL)
return(NULL);
else
find(rd->next,nm);
}
}
menu( )
{
char choice;
clrscr( );
printf("\n\n Main Menu\n");
printf("\n\n\t 1 - APPEND Records\n"
" 2 - LIST Records\n"
" 3 - INSERT Records\n"
" 4 - DELETE Records\n"
" 5 - EXIT\n\n");
printf("Your choice please...");
fflush(stdin);choice=getche( );
return(choice);
}
heading( )
{
clrscr( );
printf("\n SL.\t NAME\t\t\tROLL \n\n");
}

1
Output:

Main Menu
1 - APPEND Records
2 - LIST Records
3 - INSERT Records
4 - DELETE Records
5 - EXIT

Your choice please...1


Name please [X to exit]: ABC

Roll no. : 123

Name please [X to exit]: x

Main Menu
1 - APPEND Records
2 - LIST Records
3 - INSERT Records
4 - DELETE Records
5 - EXIT

Your choice please...2

SL. NAME ROLL

1 ABC 123

Main Menu
1 - APPEND Records
2 - LIST Records
3 - INSERT Records
4 - DELETE Records
5 - EXIT

Your choice please...3


Type NAME, before the new record to be inserted : abc

Enter Students name to be inserted ..xyz

Enter roll no:678

Main Menu
1 - APPEND Records

1
2 - LIST Records
3 - INSERT Records
4 - DELETE Records
5 - EXIT

Your choice please...2

SL. NAME ROLL

1 XYZ 678
2 ABC 123

1
8. Heapsort Algorithm
Problem Statement:
Write a program to implement the Heapsort technique.

Algorithm
Heap sort forces a certain property onto an array which makes it into what is known
as a heap. The elements of the array can be thought of as lying in a tree structure:
The children of a[i] are a[2*i] and a[2*i÷1]. The tree structure is purely notional;
there are no pointers etc. Note that the array indices run through the “nodes” in
breadth-first order, i.e. parent, children, grand-children
An array a[i..j] is called a heap if the value of each element is greater than or equal
to the values of its children, if any. Clearly, if a[1 ..N] is heap, then a[1] is the
largest element of the array.
Now, if a[k+1 . . N] is a heap, a[k. .N] can be made into a heap efficiently:

downHeap(int afi, mt k, mt N)
/ PRE: a[k+1..N] is a heap */
f* POST: a[k..N] is a heap */
{ int newElt, child;
newElt=a[k];
while(k <= N12) 1* k has child(s) */
{ child = 2*k;
/ pick larger child */
if(child < N && a[child] < a[child+1])
child++;
if(newElt >= a[child]) break;
/* else */
a[k] = a[child]; 1* move child up*/
k = child;
}
a[k] = newElt;
}/*down Heap*/
This operation moves the new element, a[k], down the heap, moving larger children
up, until the new element can be placed in such a way as to maintain the heap
property. The heap can have “height” at most log2(N), so the operation takes at
most O(log(N)) time.
Heap Sort
This now leads to a version of heap sort known as (bottom-up) heap sort:
heapSort(int a[], int N)
/*sort a[1..N], N.B 1 to N*/
{int i, temp;
for(i=N/2; I >= 1; I--)
downHeap(a, i, N);
/* a[1 . .N] is now a heap*/
for(i=N; I>1;i--)
{ temp = a[i];

1
a[i]=a[1]; /* largest of a[1 ..i] */
a[1]=temp;
downHeap(a,1,i-1); /* restore a[1..i-1] heap */
}
}/*heapSort*/

Program:
#include<stdio.h>
void heap_sort(int *, int );
void create_heap(int *, int);
void display(int *, int);
void create_heap(int list[],int n)
{
int k, j, i, temp;
clrscr();
for(k = 2; k <= n; ++k)
{
i=k;
temp = list [k];
j=i/2 ;
while((i>1) && (temp>list[j]))
{
list[i] = list[j];
i=j;
j=i/2;
if (j<1)
j=1;
}
list[i] = temp ;
}
}
void heap_sort(int list[], int n)
{
int k, temp, value, j,i,p;
int step = 1;
for(k =n; k >= 2; --k)
{
temp=list[1];
list[1]=list[k];
list[k]=temp ;
i=1;
value=list[1];
j=2;
if((j+1)<k)
{
if(list[j+1] > list[j])
j++;

1
}
while((j <= ( k-1 )) && (list[j] > value))
{
list[i] = list[j];
i = j;
j = 2*i;
if((j+1) < k)
{
if(list[j+1] > list[j])
j++;
}
else
{
if(j > n)
j = n;
}
list[i] = value;
printf("\n Step = %d", step);
step++;
}
for(p = 1; p <= n; p++)
printf("%d\t", list[p]);
}
}
void display(int list[], int n)
{
int i;
for(i = 1 ; i <=n; ++ i)
{
printf("%d\t", list[i]);
}
}
void main ( )
{
int list[200];
int i, size = 10;
printf("\n size of the list: %d", size);
for(i = 1 ; i <= size ; ++i)
{
list[i] = rand ( ) % 100;
}
printf("\n Entered list is as follows:\n");
display(list,size);
create_heap(list,size);
printf("\n Heap\n");
display(list,size);
printf("\n\n");

1
heap_sort(list,size);
printf("\n\n Sorted list is as follows:\n\n");
display(list,size);
getch( );
}

Output:

Heap
95 82 90 48 56 17 46 15 30 26

Step =1
Step =2
90 82 46 48 56 17 26 15 30 95
Step =3
Step =4
82 56 46 48 30 17 26 15 90 95
Step =5
Step =6
56 48 46 15 30 17 26 82 90 95
Step =7
Step =8
48 30 46 15 26 17 56 82 90 95
Step =9
46 30 17 15 26 48 56 82 90 95
Step = 10
30 26 17 15 46 48 56 82 90 95
Step = 11
26 15 17 30 46 48 56 82 90 95
17 15 26 30 46 48 56 82 90 95
15 17 26 30 46 48 56 82 90 95

Sorted list is as follows:

15 17 26 30 46 48 56 82 90 95

You might also like