0% found this document useful (0 votes)
23 views41 pages

C Lab II Ece Eee 2024 2025

Uploaded by

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

C Lab II Ece Eee 2024 2025

Uploaded by

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

lOMoARcPSD|45501237

C LAB- II ECE & EEE 2024-2025

Electronics & Communication Engineering (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Archana N ([email protected])
lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

CS3362 C Programming AND DATA Structures Laboratory

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

CS3362 C PROGRAMMING AND DATA STRUCTURES LABORATORY

LIST OF EXPERIMENTS

1. Practice of C programming using statements, expressions, decision making and iterative


statements
2. Practice of C programming using Functions and Arrays
3. Implement C programs using Pointers and Structures
4. Implement C programs using Files
5. Development of real time C applications
6. Array implementation of List ADT
7. Array implementation of Stack and Queue ADTs
8. Linked list implementation of List, Stack and Queue ADTs
9. Applications of List, Stack and Queue ADTs
10. Implementation of Binary Trees and operations of Binary Trees
11. Implementation of Binary Search Trees
12. Implementation of searching techniques
13. Implementation of Sorting algorithms : Insertion Sort, Quick Sort, Merge Sort
14. Implementation of Hashing – any two collision techniques

COURSE OUTCOMES:
At the end of the course, the students will be able to:

CO1: Use different constructs of C and develop applications


CO2: Write functions to implement linear and non-linear data structure operations
CO3: Suggest and use the appropriate linear / non-linear data structure operations for a given problem
CO4: Apply hash functions that result in a collision free scenario for data storage and Retrieval
CO5: Implement Sorting and searching algorithms for a given application

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX. NO: 1 C PROGRAMMING USING STATEMENTS, EXPRESSIONS


DATE:

AIM
1.A : To write a C program to illustrate the concept of Statements and Expressions.

AREA AND CIRCUMFERENCE OF A CIRCLEALGORITHM


Step 1: Start
Step 2: Read the input r
Step 3: Calculate area = pi * r * r Step 4: Calculate circum = 2 * pi * rStep 5: print area, circum ,
Step 6: Stop

PROGRAM
#include <stdio.h>
int main()
{
float radius;
double area, circumference;
printf("\n Enter the radius of the circle : ");
scanf("%f", &radius);
area = 3.14 * radius * radius; circumference=2*3.14*radius;
printf(" \n Area = %lf", area);
printf(" \n Circumference = %lf", circumference);
return 0;
}
OUTPUT
Enter the radius of the circle : 3Area = 28.260000
Circumference = 18.840000

ADDITION OF TWO NUMBERS

ALGORITHM
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values for num1, num2.
Step 4: Add num1 and num2 and assign the result to a variable sum.
Step 5: Display sum
Step 6: Stop
PROGRAM
#include <stdio.h>
int main()
{
int number1, number2, sum;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
// calculating sum
sum = number1 + number2;
printf("Sum of two numbers: ");
printf("%d + %d = %d", number1, number2, sum);
return 0;
}
OUTPUT
Enter two integers: 4 5
Sum of two numbers: 4 + 5 = 9

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

RESULT: Thus the C Program to illustrate concept of Statements and Expressions has been executed.

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX. NO: 1.2 C PROGRAMMING USING DECISION MAKING


DATE: (CONTROL OR BRANCHING)
AIM

To write a C Program to illustrate the concept of Decision making and Branching statements.

DECISION MAKING DESCRIPTION

C supports decision control statements that can alter the flow of a sequence of instructions. These statements help
to jump from one part of the program to another depending on whether a particularcondition is satisfied or not.

These decision control statements include:

if statement,

if–else statement,

if–else–if statement, and

switch–case statement.

(A) IF-ELSE STATEMENT - NUMBER IS EVEN OR ODDALGORITHM


Step 1 : Input a number NStep
2 : if (N%2==0)
Step 3 : print <Even Number=
Step 4 : else

Step 5: Print <Odd number=

Step 6: Exit

PROGRAM

#include <stdio.h>int main()


{

int a;

printf("\n Enter the value of a : ");scanf("%d", &a);

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

if(a%2==0)

printf("\n %d is even", a);else


printf("\n %d is odd", a);return 0;
}

OUTPUT

Enter the value of a : 6

6 is even

Enter the value of a : 6161 is odd

B. IF–ELSE–IF STATEMENT
C Program to check whether a number is negative, positive or zero using if–else–if Statement
ALGORITHM:
1. Input a number from the user.

2. If number is less than zero, then it is a negative integer.

3. Else if number is greater than zero, then it is a positive integer.

4. Else, the number is equal to zero.

5. End.

PROGRAM

#include <stdio.h>
int main()
{
int num;
printf("\n Enter any number : ");
scanf("%d", &num);
if(num==0)
printf("\n The value is equal to zero");
else if(num>0)
printf("\n The number is positive");
else
printf("\n The number is negative");
return 0;
}

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

OUTPUT:

Enter any number : -50


The number is negativeEnter any number : 9
The value is equal to zero

C. SWITCH–CASE STATEMENT

Check whether entered character is a vowel or not using switch–case StatementALGORITHM


Step 1: Start
Step 2: Declare character type variable ch and Read ch from User
Step 3: // Checking both lower and upper case vowels.
IF (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' ||ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' ||ch == 'u' || ch == 'U' )
Print "Vowel"ELSE
Print "Consonant"
Step 4: Stop

PROGRAM:

#include <stdio.h>
int main()

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

{
char c;

printf("Enter an Alphabet\n");
scanf("%c", &c);
switch(c) {case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("%c is VOWEL", c);break;
default:
printf("%c is CONSONANT", c);
}
return 0;
}

OUTPUT
Enter an Alphabete
e is VOWEL Enter an AlphabetZ
Z is CONSONANT

RESULT:

Thus the C Program to illustrate the concept of Decision making and Branching statements.

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX. NO: 1.3 C PROGRAMMING USING ITERATIVE STATEMENTS


DATE: (LOOPING STATEMENTS)
AIM

To write a C Program to illustrate the Iteration concepts using Looping Statements.

DESCRIPTION

ITERATIVE OR LOOPING STATEMENTS

Iterative statements are used to repeat the execution of a sequence of statements until the specifiedexpression
becomes false. C supports three types of iterative statements also known as looping statements. They are
 while loop
 do–while loop
 for loop

A.WHILE LOOP

PRINT THE FIRST 10 NUMBERS USING A WHILE LOOP

ALGORITHM

Step 1: Start

Step 2: Assign i=1

Step 3: Read a number, num


Step 4: While i<=num
Print i Compute i=i+1
Step 5: Stop

PROGRAM

#include <stdio.h>
int main()
{

int i = 1,n;
printf("Enter the Number");
scanf("%d",&n);
while(i<=n)
{

printf("\n %d", i);


i = i + 1;
}

return 0;

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

OUTPUT:

Enter the Number 1


0
1
2
3
4
5
6
7
8
9
10
B. DO–WHILE LOOP

PRINT NUMBERS FROM 1 TO 10.ALGORITHM


Step 1: Start

Step 2: Assign i=1

Step 3: Read a number, num


Step 4: DO
Print i Compute i=i+1
While i<=num
Step 5: Stop

PROGRAM

#include <stdio.h>
int main()
{
int i = 1;do
{
printf("\t %d", i);
i = i + 1;
}
while(i<=10);
return 0;
}

OUTPUT:

1 2 3 4 5 6 7 8 9 10

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

CALCULATE THE AVERAGE OF FIRST 20 NUMBERS.


#include <stdio.h>
int main()
{

int n, i = 0, sum =0;


float avg = 0.0;
printf("\n Enter the value of n : ");
scanf("%d", &n);
do

{
sum = sum + i;
i = i + 1;
}
while(i<=n);
avg = (float)sum/n;
printf("\n The sum of first %d numbers = %d",n, sum);
printf("\n The average of first %d numbers = %.2f", n, avg);
return 0;
}

OUTPUT

Enter the value of n : 20

The sum of first 20 numbers = 210

The average of first 20 numbers = 10.05

C. FOR LOOP

C Program to print the first n numbers using for loop.ALGORITHM


Step 1: Start
Step 2: Assign i=1
Step 3: Read a number, num
Step 4: For i<=num
Print i Compute i=i+1
Step 5: Stop

PROGRAM

#include <stdio.h>
int main()
{
int i, n;
printf("\n Enter the value of n :");
scanf("%d", &n);
for(i=1;i<=n;i++)
printf("\n %d", i);
return 0;
}

OUTPUT:
Enter the value of n : 51
2
3
4
5

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

RESULT: Thus the C Program to illustrate Iteration using Looping Statements was executed.

EX. NO: 2 C programming using Functions and Array


EX.NO:2.1 Factorial of a Number Using Recursion

Aim: To write a C program for Factorial of a Number Using Recursion


Algorithm:
Step 1: Start
Step 2: Read number n
Step 3: Call factorial(n)
Step 4: Print factorial f
Step 5: Stop

factorial(n)
Step 1: If n==1 then return 1
Step 2: Else
f=n*factorial(n-1)
Step 3: Return f

//Factorial of a Number Using Recursion

#include<stdio.h>
long int multiplyNumbers(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}

long int multiplyNumbers(int n)


{
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}

Output
Enter a positive integer: 6Factorial of 6 = 720

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

Ex.No:2.2 ARRAYS
C Programming for Matrix Multiplication

Aim:
To write a C program for Matrix Multiplication
Algorithm:
Start.
1. Enter the value of m and n (or) order of the first matrix.
2. Enter the value of p and q (or) order of the second matrix.
3. Create a matrix of size a[m][n] and b[p][q].
4. Enter the element of matrices row-wise using loops.
5. If the number of columns of the first matrix is not equal to the number of rows of the
second matrix, print matrix multiplication is not possible and exit. If not, proceed to the
next step.
6. Create a third matrix, c of size m x q, to store the product.
7. Set a loop from i=0 to i=m.
8. Set an inner loop for the above loop from j=0 to j=q.
9. Initialise the value of the element (i, j) of the new matrix to 0.
10. Set an inner loop inside the above loop from k=0 to k=p.
11. Using the add and assign operator (+=) store the value of a[i][k] * b[k][j] in the third
matrix, c[i][j].
12. Print the third matrix.
13. Stop.

Program:

#include<stdio.h>
int main() {
int a[10][10], b[10][10], c[10][10], n, i, j, k;
printf("Enter the value of N (N <= 10): ");
scanf("%d", & n);
printf("Enter the elements of Matrix-A: \n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", & a[i][j]);
}
}
printf("Enter the elements of Matrix-B: \n");
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] = 0;
for (k = 0; k < n; k++)
{
c[i][j] += a[i][k] * b[k][j];
}
}
Downloaded by Archana N ([email protected])
lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

}
printf("The product of the two matrices is: \n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{ printf("%d\t", c[i][j]);
}
printf("\n");
}
return 0;
}

output
Enter the value of N (N <= 10): 2Enter the elements of Matrix-A: 2 2
22
Enter the elements of Matrix-B:2 2
22

Product of the two matrices is :8 8


8 8

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX.NO: 3 C Programming for Working of Pointers


Aim:
To write a C program for Working of Pointers
Algorithm:

1. int* pc, c;2. c = 22;


2. printf("Address of c: %p\n", &c);
3. printf("Value of c: %d\n\n", c); // 22
4. pc = &c;
5. printf("Address of pointer pc: %p\n", pc);
6. printf("Content of pointer pc: %d\n\n", *pc); // 22
7. return 0;

Working of Pointers

#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc);// 22c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}

Output
Address of c: 2686784Value of c: 22

Address of pointer pc: 2686784Content of pointer pc: 22

Address of pointer pc: 2686784Content of pointer pc: 11

Address of c: 2686784V

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX.NO:3.2 Dynamic memory allocation of structs

To write a C program for Dynamic memory allocation of structs


Aim: To write a C program for Dynamic memory allocation of structs
Algorithm:
1. struct person *ptr;
2. printf("Enter the number of persons: ");
3. scanf("%d", &n);
4. ptr = (struct person*) malloc(n * sizeof(struct person));
5. for(i = 0; i < n; ++i)
6. printf("Enter first name and age respectively: ");
7. scanf("%s %d", (ptr+i)->name, &(ptr+i)->age);
8. printf("Displaying Information:\n");
9. for(i = 0; i < n; ++i)
10. printf("Name: %s\tAge: %d\n", (ptr+i)->name, (ptr+i)->age)

Dynamic memory allocation of structs


#include <stdio.h> #include <stdlib.h>struct person {
int age;
float weight; char name[30];
};
int main()
{
struct person *ptr;int i, n;
printf("Enter the number of persons: ");scanf("%d", &n);
ptr = (struct person*) malloc(n * sizeof(struct person));for(i = 0; i < n; ++i)
{
printf("Enter first name and age respectively: ");scanf("%s %d", (ptr+i)->name, &(ptr+i)->age);
}
printf("Displaying Information:\n");for(i = 0; i < n; ++i)
printf("Name: %s\tAge: %d\n", (ptr+i)->name, (ptr+i)->age);return 0;
}
OUT PUT
When you run the program, the output will be:
Enter the number of persons: 2
Enter first name and age respectively: Harry 24
Enter first name and age respectively: Gary 32
Displaying Information:
Name: Harry Age: 24
Name: Gary Age: 32

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

Store Information in Structure and Display it


Aim: To write a C program for Store Information in Structure and Display it
Algorithm:
1. struct student2.
2. {
3. char firstName[50];
4. int roll;
5. float marks;6.
6. } s[5];
7. for (i = 0; i < 5; ++i)
8. s[i].roll = i + 1;
9. printf("\nFor roll number%d,\n", s[i].roll);
10. printf("Enter first name: ");
11. scanf("%s", s[i].firstName);
12. printf("Enter marks: ");
13. scanf("%f", &s[i].marks);
14. printf("Displaying Information:\n\n");
15. printf("\nRoll number: %d\n", i + 1);
16. printf("First name: ");
17. puts(s[i].firstName);
18. printf("Marks: %.1f", s[i].marks);

Store Information in Structure and Display it


#include <stdio.h>
struct student t
{
char firstName[50];
int roll;
float marks;
} s[5];
int main()
{
int i;
printf("Enter information of students:\n");
for (i = 0; i < 5; ++i)
{
s[i].roll = i + 1;
printf("\nFor roll number%d,\n", s[i].roll)
;printf("Enter first name: ");
scanf("%s", s[i].firstName);
printf("Enter marks: ");
scanf("%f", &s[i].marks);
}
printf("Displaying Information:\n\n");
for (i = 0; i < 5; ++i)
{
printf("\nRoll number: %d\n", i + 1);
printf("First name: ");
puts(s[i].firstName);
printf("Marks: %.1f", s[i].marks);
printf("\n");
}
Downloaded by Archana N ([email protected])
lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

return 0;
}

Output
Enter information of students:

For roll number1,Enter name: TomEnter marks: 98

For roll number2,Enter name: JerryEnter marks: 89


.
.
Displaying Information:

Roll number: 1Name: Tom Marks: 98


.
.

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX.NO:4 Read name and marks of n number of students and store them in a FILE

Aim:
To write a C program for read name and marks of n number of students and store them ina file
Algorithm:

1. char name[50];
2. int marks, i, num;
3. printf("Enter number of students: ");
4. scanf("%d", &num);
5. FILE *fptr;
6. fptr = (fopen("C:\\student.txt", "w"));
7. if(fptr == NULL)
8. printf("Error!");
9. exit(1);
10. for(i = 0; i < num; ++i)
11. printf("For student%d\nEnter name: ", i+1);
12. scanf("%s", name);
13. printf("Enter marks: ");
14. scanf("%d", &marks);
15. fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);
16. fclose(fptr);

Program:
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr;
fptr = (fopen("C:\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
for(i = 0; i < num; ++i)
{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);
}
fclose(fptr); return 0;
}
Output
Enter number of students: 2

Enter name: AAAEnter marks: 60


Enter marks: 70
Enter marks: 80
Downloaded by Archana N ([email protected])
lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

Enter name: BBBEnter marks: 45


Enter marks: 15
Enter marks: 10

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX.NO:5 Development of real time C applications


Simple Calculator using switch Statement
Aim:
To write a C program for Simple Calculator using switch Statement
Procedure:

 Step 1- Display messages like “press 1 for addition, 2 for subtraction, 3 for
multiplication,4 for division”
 Step 2- accept the choice from the user and store it in a variable (say choice)
 Step 3- put choice in the switch as switch(choice)
 Step 4- put the case accordingly like case 1 for addition, case 2 for subtraction and so on
and store and print the result. Also give a default case for wrong choice

Program:
#include <stdio.h>
int main()
{
char op;
double first, second;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);
printf("Enter two operands: ");
scanf("%lf %lf", &first, &second);switch (op)
{
case '+':
printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
break;
// operator doesn't match any case constantdefault:
printf("Error! operator is not correct");
}
return 0;
}
Output
Enter an operator (+, -, *,):
*Enter two operands: 1.5
4.5
1.5 * 4.5 = 6.8

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX.NO:5. 2 EMI Calculator program in C

Aim:
To Write a C program for EMI Calculator program in C

Procedure:
EMI Calculator: This program will read total loan amount (principal), rateand time in
years and prints the per month EMI of that loan amount.
The formula used in this program is:
(P*R*(1+R)T)/(((1+R)T)-1)
Here,

 P is loan amount.
 R is interest rate per month - we will read in yearly and convert in monthly in
program.
 T is loan time period in year - we will read in yearly and convert in monthly in
program

Program:
#include <stdio.h>
#include <math.h>
int main()
{
float principal, rate, time, emi;
printf("Enter principal: ");
scanf("%f", &principal);
printf("Enter rate: ");
scanf("%f", &rate);
printf("Enter time in year: ");
scanf("%f", &time);
rate = rate / (12 * 100); /*one month interest*/time = time * 12; /*one month period*/
emi = (principal * rate * pow(1 + rate, time)) / (pow(1 + rate, time) - 1);
printf("Monthly EMI is= %f\n", emi);
return 0;
}

Output:
Enter principal: 20000
Enter rate: 10
Enter time in year: 2
Monthly EMI is= 922.899536

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX.NO:7 Array implementation of Stack and


Queue ADTs

Aim:
Write a program to Array implementation of Stack
and Queue ADTs

Algoritham

Step 1 push() to insert an element into the stack


Step 2 pop() to remove an element from the stack
Step 3 top() Returns the top element of the stack.
Step 4 isEmpty() returns true if stack is empty else
false.
Step 5 size() returns the size of stack.

// C program for array implementation of stack


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

struct Stack
{
int top;
unsigned capacity;int* array;
};

struct Stack* createStack(unsigned capacity)


{
struct Stack* stack = (structStack*)malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity *sizeof(int));
return stack;
}
int isFull(struct Stack* stack)
{
return stack->top == stack->capacity - 1;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}
void push(struct Stack* stack, int item)
{
if (isFull(stack))return;
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}
top by 1
int pop(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top--];
Downloaded by Archana N ([email protected])
lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

}
int peek(struct Stack* stack)
{
if (isEmpty(stack)) return INT_MIN;
return stack->array[stack->top];
}
// Driver program to test above functions
int main()
{
struct Stack* stack = createStack(100);
push(stack, 10);
push(stack, 20);
}

OUTPUT:

10 pushed into stack


20 pushed into stack
30 pushed into stack
30 Popped from stack
Top element is : 20
Elements present in stack : 20 10

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX.NO: 8 Implementation of the queue using linked list

AIM: Write a program to Implementation of the queue using linked list

Algoritham :

 Step 1 We will maintain two node pointer "front" and "back", which always points to the head and
tail node of linked list respectively. This will ensure that we will add node at rear of linked list and
remove node from front of linked list.

 Step 2 We will start with an empty linked list, where both front and back pointer is set to NULL.

 Step 3 Enqueue Operation : We will dynamically allocate memory for a struct node variable(let's
say temp). Then we will attach new node at the end of linked list by setting back->next = temp.
Finally set back pointer to temp.(back = temp;)

 Step 4 Dequeue Operation : Remove head node(pointed by front pointer) of the linked list. Store the
front pointer in a temp variable. Now, move front pointer to next node(front = front->next;).
Deallocate memory of temp node using free.

 Step 5 getFrontElement Operation : Returns the value of head node of linked list without removing
it.(return front->data;)

 Step 6 isEmpty Check : If both front and back pointers are NULL, then Queue is empty otherwise
non-empty.

/*Program :

Queue using linked list Language : C*/


#include<stdio.h>
#include<stdlib.h> struct node
{
int data;
struct node *next;
};
struct node *front = NULL, *rear = NULL;
void enqueue(int val)
{
struct node *newNode = malloc(sizeof(struct node));
newNode->data = val;
newNode->next = NULL;
if(front == NULL && rear == NULL)
front = rear = newNode;
else
{
rear->next = newNode;
rear = newNode;
}
}
void dequeue()
{
struct node *temp;

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

if(front == NULL)
printf("Queue is Empty. Unable to perform dequeue\n");
else
{
temp = front;

front = front->next;
if(front == NULL)
rear = NULL;
}
}
void printList()
{
struct node *temp = front; while(temp)
{
printf("%d->",temp->data); temp = temp->next;
}
printf("NULL\n");
}
int main()
{
enqueue(10);
enqueue(20);
enqueue(30);
printf("Queue :");
printList();
dequeue();
printf("After dequeue the new Queue :");
printList();
dequeue();
printf("After dequeue the new Queue :");
printList();
return 0;
}

Output
Queue :10->20->30->NULL
After dequeue the new Queue :20->30->
NULL After dequeue the new Queue :30->NULL

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX.NO:10 Implementation of Binary Trees and operations of Binary Trees


Aim:
Write a program to Implementation of Binary Trees and operations of Binary Trees
Algorithm

Step 1 First, declared a function "create"

Step 2 It takes a value as an input and creates and returns a node that will have the data variableequal to the
value, and the left and right pointer variables will point to NULL.

Step 3 To insert the left child, use the insertLeft function,

Step 4 which takes the pointer to the parent node and the value.

Step 5 Then internally it calls the create function and the node returned by it is attached to the leftpointer of
the parent node.

Step 6 Similarly, the insertRight function works.

Program:
// Tree traversal in C#include <stdio.h> #include <stdlib.h> struct node
{
int item;
struct node* left; struct node* right;
};
void inorderTraversal(struct node* root)
{
if (root == NULL) return; inorderTraversal(root->left); printf("%d ", root->item); inorderTraversal(root-
>right);

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

}
void preorderTraversal(struct node* root)
{
if (root == NULL) return; printf("%d ", root->item); preorderTraversal(root->left); preorderTraversal(root-
>right);
}
void postorderTraversal(struct node* root)
{
if (root == NULL) return; postorderTraversal(root->left); postorderTraversal(root->right);printf("%d ", root-
>item);
}
struct node* create(int value)
{
struct node* newNode = malloc(sizeof(struct node));newNode->item = value;
newNode->left = NULL; newNode->right = NULL;return newNode;
}
struct node* insertLeft(struct node* root, int value)
{
root->left = create(value);return root->left;
}
struct node* insertRight(struct node* root, int value)
{
root->right = create(value);return root->right;
}
int main()
{
struct node* root = create(1);insertLeft(root, 4);
insertRight(root, 6);
insertLeft(root->left, 42);
insertRight(root->left, 3);
insertLeft(root->right, 2);
insertRight(root->right, 33);
printf("Traversal of the inserted binary tree \n");printf("Inorder traversal \n"); inorderTraversal(root);
printf("\nPreorder traversal \n"); preorderTraversal(root); printf("\nPostorder traversal \n");
postorderTraversal(root);

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

}
Output :
Traversal of the inserted binary tree

Inorder traversal42 4 3 1 2 6 33

Preorder traversal1 4 42 3 6 2 33

Postorder traversal42 3 4 2 33 6 1

EX.NO: 11 Implementation of Binary Search Trees


Aim:
Write a program to Implementation of Binary Trees and operations of Binary Trees
Algorithm

Step 1 Define Node class which has three attributes namely: data, left and right. Here, leftrepresents
the left child of the node and right represents the right child of the node.

Step 2 When a node is created, data will pass to the data attribute of the node and both left andright will
be set to null.

Step 3 Define another class which has an attribute root.


Root represents the root node of the tree and initializes it to null.
Step 4 insert() will insert the new value into a binary search tree:
It checks whether root is null, which means tree is empty. New node will becomeroot node of tree.
If tree is not empty, it will compare value of new node with root node. If value of new node is greater than
root, new node will be inserted to right subtree. Else, it will be inserted in left subtree.
Step 5 deleteNode() will delete a particular node from the tree:
If value of node to be deleted is less than root node, search node in left subtree.Else, search in right
subtree.
If node is found and it has no children, then set the node to null. If node has one child then, child node will
take position of node.
If node has two children then, find a minimum value node from its right subtree.This minimum value node
will replace the current node.

Program:

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

struct node{int data;

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

struct node *left; struct node *right;


};
struct node *root= NULL;
struct node* createNode(int data){
struct node *newNode = (struct node*)malloc(sizeof(struct node));newNode->data= data;
newNode->left = NULL; newNode->right = NULL;return newNode;
}
void insert(int data) {
struct node *newNode = createNode(data);if(root == NULL){
root = newNode;return;
}
else {
struct node *current = root, *parent = NULL;while(true) {
parent = current;
if(data < current->data) {current = current->left; if(current == NULL) {
parent->left = newNode;return;
}
}
//If data is greater than current's data, node will be inserted to the right of treeelse {
current = current->right;if(current == NULL) {
parent->right = newNode;return;
} } } } }
struct node* minNode(struct node *root)
{
if (root->left != NULL)
return minNode(root->left);else
return root;
}
struct node* deleteNode(struct node *node, int value)
{
if(node == NULL){return NULL;
}
else {
if(value < node->data)
node->left = deleteNode(node->left, value);

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

else if(value > node->data)


node->right = deleteNode(node->right, value);else {
if(node->left == NULL && node->right == NULL)node = NULL;
else if(node->left == NULL) {node = node->right;
}
else if(node->right == NULL) {node = node->left;
}
else {
struct node *temp = minNode(node->right);node->data = temp->data;
node->right = deleteNode(node->right, temp->data);
}
}
return node;
} }
void inorderTraversal(struct node *node)
{
if(root == NULL){ printf("Tree is empty\n");return;
}
else
{
if(node->left!= NULL) inorderTraversal(node->left); printf("%d ", node->data); if(node->right!= NULL)
inorderTraversal(node->right);
} }
int main()
{
insert(50);insert(30);insert(70);insert(60);insert(10);insert(90);
printf("Binary search tree after insertion: \n");inorderTraversal(root);
struct node *deletedNode = NULL; deletedNode = deleteNode(root, 90);
printf("\nBinary search tree after deleting node 90: \n");inorderTraversal(root);
deletedNode = deleteNode(root, 30);
printf("\nBinary search tree after deleting node 30: \n");inorderTraversal(root);

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

deletedNode = deleteNode(root, 50);


printf("\nBinary search tree after deleting node 50: \n");inorderTraversal(root);
return 0;
}

Output:
Binary search tree after insertion:10 30 50 60 70 90
Binary search tree after deleting node 90:10 30 50 60 70
Binary search tree after deleting node 30:10 50 60 70
Binary search tree after deleting node 50:10 60 70

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX.NO 12 Implementation of searching techniques


Aim:
Write a program to Implementation of searching techniques
Algorithm

Step 1 Searching for the key element is done in a linear fashion.Step 2 It is the simplest searching technique.
Step 3 It does not expect the list to be sorted.
Step 4 Limitation − It consumes more time and reduce the power of system.

Program:

#include<stdio.h>
int main ()
{
int a[50], n, i, key, flag = 0;
printf("enter the no: of elements");
scanf ("%d",&n);
printf("enter the elements:");
for (i=0; i<n; i++)
scanf( "%d", &a[i]);
printf("enter a key element:");
scanf ("%d", &key);
for (i=0; i<n; i++)
{
if (a[i] == key)
{
flag = 1;
break;
}
}
if (flag == 1)
printf("search is successful:");
else
printf("search is unsuccessfull:");
return 0;
}

Output
enter the no: of elements5
enter the elements:12
45
13
67
78
enter a key element:67search
is successful:

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX.NO:13.A. Merge Sort Algorithm

Aim:
To Write a program to implement merge sort in C language.

Algorithm:

Step1. Declare Array, left, right and mid variables


Step 2. Find mid by formula mid = (left+right)/2
Step 3. Call MergeSort for the left to mid
Step 4. Call MergeSort for mid+1 to right
Step 5. Continue step 2, 3, and 4 while the left is less than the right
Step 6. Then Call the Merge function
Step 7 End

Program:

#include <stdio.h>
void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;int n2 = end - mid;
int LeftArray[n1], RightArray[n2]; //temporary arraysfor (int i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];

i = 0; /* initial index of first sub-array */


j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */

while (i < n1 && j < n2)


{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];i++;

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

}
else
{
a[k] = RightArray[j];j++;
}
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];i++;
k++;
}
while (j<n2)
{
a[k] = RightArray[j];j++;
k++;
}
}
void mergeSort(int a[], int beg, int end)
{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}
void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17, 40, 42 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");printArray(a, n);
mergeSort(a, 0, n - 1);
printf("After sorting array elements are - \n");printArray(a, n);
return 0;
}

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

Output:
Before sorting array elements are –12 31 25 8 32 17 40 42
After sorting array elements are –8 12 17 25 31 32 40 42

EX.NO:13.B Write a program to implement insertion sort in C language.


Aim:
To write a program to implement insertion sort in C language.
Algorithm

Step 1 - If the element is the first element, assume that it is already sorted. Return 1.Step2 - Pick the next
element, and store it separately in a key.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to thenext
element. Else, shift greater elements in the array towards the right.
Step 5 - Insert the value.
Step 6 - Repeat until the array is sorted.

Program:
#include <stdio.h>
void insert(int a[], int n) /* function to sort an aay with insertion sort */
{
int i, j, temp;
for (i = 1; i < n; i++)
{
temp = a[i];
j = i - 1;
while(j>=0 && temp <= a[j])
{a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}
void printArr(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

int a[] = { 12, 31, 25, 8, 32, 17 };


int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}

Output:

Before sorting array elements are –12 31 25 8 32 17 40 42

After sorting array elements are –8 12 17 25 31 32 40 42

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

EX.NO:14 Write a program to Implementation of Hashing – any two collision techniques

Aim:

To write a program Implementation of Hashing – any two collision techniques in C

Algorithm:

Step 1 Hashing is an efficient method to store and retrieve elements.

Step 2 It’s exactly same as index page of a book. In index page, every topic is associated with apage
number.

Step 3 If we want to look some topic, we can directly get the page number from the index.Step 4 Likewise, in
hashing every value will be associated with a key.
Step 5 Using this key, we can point out the element directly.

Program:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 20
struct DataItem
{
int data;int key;
};
struct DataItem* hashArray[SIZE];
struct DataItem* dummyItem;
struct DataItem* item;
int hashCode(int key)
{
return key % SIZE;
}
struct DataItem *search(int key)
{
int hashIndex = hashCode(key);

while(hashArray[hashIndex] != NULL)
{
if(hashArray[hashIndex]->key == key)
return hashArray[hashIndex];
++hashIndex;
hashIndex %= SIZE;
}

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

return NULL;
}
void insert(int key,int data)
{
struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem));
item->data = data;
item->key = key;
int hashIndex = hashCode(key);
while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1)
{
++hashIndex; hashIndex %= SIZE;
}
hashArray[hashIndex] = item;
}
struct DataItem* delete(struct DataItem* item)
{
int key = item->key;get the hash
int hashIndex = hashCode(key); while(hashArray[hashIndex] != NULL)
{
if(hashArray[hashIndex]->key == key)
{
struct DataItem* temp = hashArray[hashIndex];hashArray[hashIndex] = dummyItem;
return temp;
}
++hashIndex;
hashIndex %= SIZE;
}
return NULL;
}
void display()
{
int i = 0;
for(i = 0; i<SIZE; i++)
{ if(hashArray[i] != NULL)
printf(" (%d,%d)",hashArray[i]->key,hashArray[i]->data);
else
printf(" ~~ ");
}
printf("\n");
}

int main()
{
dummyItem = (struct DataItem*) malloc(sizeof(struct DataItem));dummyItem->data = -1;
dummyItem->key = -1;
insert(1, 20);
insert(2, 70);
insert(42, 80);
insert(4, 25);
insert(12, 44);
insert(14, 32);
insert(17, 11);
insert(13, 78);

Downloaded by Archana N ([email protected])


lOMoARcPSD|45501237
lOMoAR cPSD| 45501237

insert(37, 97);
display();
item = search(37);
if(item != NULL)
{
printf("Element found: %d\n", item->data);
} else {
printf("Element not found\n");
}
delete(item);
item = search(37);
if(item != NULL)
{
printf("Element found: %d\n", item->data);
}
else
{
printf("Element not found\n");
}
}

Output:

~~
(1,20) (2,70) (42,80) (4,25)
~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~(12,44) (13,78) (14,32)
~ ~ ~ ~ (17,11) (37,97)
~~

Element found: 97Element not found

Downloaded by Archana N ([email protected])

You might also like