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

Mca r20 Java

Uploaded by

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

Mca r20 Java

Uploaded by

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

CHAITANYA ENGINEERING COLLEGE

KOMMADI, VISAKHAPATNAM
(Approved by AICTE, New Delhi & Affiliated to JNTU Gurajada Vizianagaram)
NBA & NAAC Accredited

DATA STRUCTURES LAB MANUAL


For

MCA I YEAR I SEMESTER

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CHAITANYAVALLEY, KOMMADI, MADHURWADA, VISAKHAPATNAM-530048


CHAITANYA ENGINEERING COLLEGE

CHAITANYAVALLEY, KOMMADI, MADHURWADA, VISAKHAPATNAM-530048

CERTIFICATE

This is to certify that

is a student studying

PIN NO. branch has done

no. of experiments during the year

in the subject

Head of Department External Examiner Lecture-in-charge


INDEX
EXP.NO. CONTENTS DATE PAGE
1. a)Write a program in c to display the n terms of even natural
number and their sum
b) Write a program in c to display the n terms of harmonic series
and their sum. 1+1/2+1/3+1/4+1/5..... n terms.
c) Write a c program to check whether the given number is
Armstrong or not.
d)Write a c program to calculate the factorial of a given
number.
2. a) Write a Program in C for multiplication of two square matrices.
b)Write a Program in C to find transpose of a given matrix.
3. a) Write a program in C to check whether a number is prime
or not using the function.
b) Write a recursive program which computes the nth
Fibonacci number, for appropriate values of n.
c) Write a Program in C to add numbers using call by
reference.
4. Write a Java Program for sorting a given list of names in
ascending order.
5. Write a Java Program that illustrates how runtime
polymorphism is achieved.
6. Write a Java Program to create and demonstrate packages.
7. Write a Java Program, using StringTokenizer class, which
reads a line of integers and then displays each integer and the
sum of all integers.
8. Write a Java Program that reads on file name form the user
then displays information about whether
the file exists, whether the file is readable/ writable, the type
of file and the length of the file in bytes
and display the content of the using FileInputStream class.
9. Write a Java Program that displays the number of
characters, lines and words in a text/text file.
10. Write an Applet that displays the content of a file.
11. Write a Java Program that works as a simple calculator. Use
a grid layout to arrange buttons for the digits and for the + *?%
operations. Add a text field to display the result.
12. Write a Java Program for handling mouse events.
13. Write a Java Program demonstrating the life cycle of a
thread.
14. Write a Java Program that lets users create Pie charts. Design
your own user interface (with Swings& AWT).

15. Write a Java Program to implement a Queue, using user


defined Exception Handling (also make use of throw,
throws).
1.
a) Write a program in c to display the n terms of even natural number and their sum.

#include <stdio.h>

int main() {
int n, sum = 0;

// Input the value of n


printf("Enter the number of terms: ");
scanf("%d", &n);

printf("First %d even natural numbers are:\n", n);

// Display the even natural numbers and calculate their sum


for (int i = 1; i <= n; i++) {
int even_number = 2 * i;
printf("%d ", even_number);
sum += even_number;
}

// Display the sum


printf("\nSum of the first %d even natural numbers is: %d\n", n, sum);

return 0;
}

Output:

Enter the number of terms: 5


First 5 even natural numbers are:
2 4 6 8 10
Sum of the first 5 even natural numbers is: 30

b) Write a program in c to display the n terms of harmonic series and their sum. 1+1/2+1/3+1/4+1/5..... n
terms.

#include <stdio.h>

int main() {
int n;
float sum = 0.0;

// Input the number of terms


printf("Enter the number of terms: ");
scanf("%d", &n);
// Display the harmonic series and calculate the sum
printf("The first %d terms of the harmonic series are:\n", n);
for (int i = 1; i <= n; i++) {
printf("1/%d ", i);
sum += 1.0 / i;
}

// Display the sum of the harmonic series


printf("\nSum of the first %d terms of the harmonic series is: %.4f\n", n, sum);

return 0;
}

Output:

Enter the number of terms: 5


The first 5 terms of the harmonic series are:
1/1 1/2 1/3 1/4 1/5
Sum of the first 5 terms of the harmonic series is: 2.2833

c) Write a c program to check whether the given number is Armstrong or not.

#include <stdio.h>
#include <math.h>

int main() {
int num, originalNum, remainder, result = 0, n = 0;

// Input the number


printf("Enter a number: ");
scanf("%d", &num);

originalNum = num;

// Find the number of digits in the given number


while (originalNum != 0) {
originalNum /= 10;
++n;
}

originalNum = num;

// Calculate the sum of the nth powers of its digits


while (originalNum != 0) {
remainder = originalNum % 10; // Extract the last digit
result += pow(remainder, n); // Raise the digit to the power of n and add it to result
originalNum /= 10; // Remove the last digit
}
// Check if the sum is equal to the original number
if (result == num)
printf("%d is an Armstrong number.\n", num);
else
printf("%d is not an Armstrong number.\n", num);

return 0;
}

Output:

Enter a number: 153


153 is an Armstrong number.

d) Write a c program to calculate the factorial of a given number.

#include <stdio.h>

// Function to calculate factorial


unsigned long long factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: factorial of 0 or 1 is 1
}
return n * factorial(n - 1); // Recursive case
}

int main() {
int number;
unsigned long long result;

// Prompt user for input


printf("Enter a positive integer: ");
scanf("%d", &number);

// Check if input is valid


if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
result = factorial(number);
printf("Factorial of %d is %llu\n", number, result);
}

return 0;
}

Output:

Enter a positive integer: 5


Factorial of 5 is 120
2.
a) Write a Program in C for multiplication of two square matrices.
#include <stdio.h>

#define MAX 10 // Maximum size of the matrix

void inputMatrix(int matrix[MAX][MAX], int size, const char* name) {


printf("Enter elements of matrix %s (%dx%d):\n", name, size, size);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("Enter element [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
}

void displayMatrix(int matrix[MAX][MAX], int size) {


for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}

void multiplyMatrices(int mat1[MAX][MAX], int mat2[MAX][MAX], int result[MAX][MAX], int


size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
result[i][j] = 0; // Initialize the result matrix element
for (int k = 0; k < size; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}

int main() {
int size;
int mat1[MAX][MAX], mat2[MAX][MAX], result[MAX][MAX];
printf("Enter the size of the square matrices (max %d): ", MAX);
scanf("%d", &size);

if (size > MAX || size <= 0) {


printf("Invalid matrix size. Please enter a size between 1 and %d.\n", MAX);
return 1;
}

// Input matrices
inputMatrix(mat1, size, "A");
inputMatrix(mat2, size, "B");

// Multiply matrices
multiplyMatrices(mat1, mat2, result, size);

// Display results
printf("Matrix A:\n");
displayMatrix(mat1, size);

printf("Matrix B:\n");
displayMatrix(mat2, size);

printf("Resultant Matrix (A x B):\n");


displayMatrix(result, size);

return 0;
}
Output:
Enter the size of the square matrices (max 10): 2
Enter elements of matrix A (2x2):
Enter element [1][1]: 1
Enter element [1][2]: 2
Enter element [2][1]: 3
Enter element [2][2]: 4
Enter elements of matrix B (2x2):
Enter element [1][1]: 5
Enter element [1][2]: 6
Enter element [2][1]: 7
Enter element [2][2]: 8
Matrix A:
1 2
3 4

Matrix B:
5 6
7 8

Resultant Matrix (A x B):


19 22
43 50
b) Write a Program in C to find transpose of a given matrix.
#include <stdio.h>

#define MAX 10 // Maximum size of the matrix

void inputMatrix(int matrix[MAX][MAX], int rows, int cols) {


printf("Enter elements of the matrix (%dx%d):\n", rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
}

void displayMatrix(int matrix[MAX][MAX], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}

void transposeMatrix(int matrix[MAX][MAX], int transposed[MAX][MAX], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transposed[j][i] = matrix[i][j];
}
}
}

int main() {
int rows, cols;
int matrix[MAX][MAX], transposed[MAX][MAX];

// Input matrix dimensions


printf("Enter the number of rows (max %d): ", MAX);
scanf("%d", &rows);
printf("Enter the number of columns (max %d): ", MAX);
scanf("%d", &cols);

if (rows > MAX || cols > MAX || rows <= 0 || cols <= 0) {
printf("Invalid dimensions. Please enter dimensions between 1 and %d.\n", MAX);
return 1;
}

// Input the matrix


inputMatrix(matrix, rows, cols);

// Find the transpose


transposeMatrix(matrix, transposed, rows, cols);

// Display the original and transposed matrices


printf("Original Matrix:\n");
displayMatrix(matrix, rows, cols);

printf("Transposed Matrix:\n");
displayMatrix(transposed, cols, rows);

return 0;
}
Output:

Enter the number of rows (max 10): 2


Enter the number of columns (max 10): 3
Enter elements of the matrix (2x3):
Enter element [1][1]: 1
Enter element [1][2]: 2
Enter element [1][3]: 3
Enter element [2][1]: 4
Enter element [2][2]: 5
Enter element [2][3]: 6

Original Matrix:
1 2 3
4 5 6

Transposed Matrix:
1 4
2 5
3 6

3.
a) Write a program in C to check whether a number is prime or not using the function.

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

// Function to check if a number is prime


bool isPrime(int n) {
if (n <= 1) {
return false; // Numbers <= 1 are not prime
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false; // Divisible by i means not prime
}
}
return true; // Prime if no divisors found
}

int main() {
int number;

// Input the number


printf("Enter a positive integer: ");
scanf("%d", &number);

// Check if the number is prime


if (isPrime(number)) {
printf("%d is a prime number.\n", number);
} else {
printf("%d is not a prime number.\n", number);
}

return 0;
}

Output:

Enter a positive integer: 17


17 is a prime number.

Enter a positive integer: 18


18 is not a prime number.

b) Write a recursive program which computes the nth Fibonacci number, for appropriate values
of n.

#include <stdio.h>

// Recursive function to calculate the nth Fibonacci number


int fibonacci(int n) {
if (n <= 0) {
return 0; // Base case: Fibonacci(0) = 0
} else if (n == 1) {
return 1; // Base case: Fibonacci(1) = 1
} else {
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}
}

int main() {
int n;

// Input from user


printf("Enter a positive integer (n): ");
scanf("%d", &n);

if (n < 0) {
printf("Invalid input. Please enter a non-negative integer.\n");
} else {
// Compute and display the nth Fibonacci number
printf("Fibonacci(%d) = %d\n", n, fibonacci(n));
}

return 0;
}

Output :

Enter a positive integer (n): 5


Fibonacci(5) = 5

Enter a positive integer (n): 10


Fibonacci(10) = 55

c) Write a Program in C to add numbers using call by reference.

#include <stdio.h>

// Function to add two numbers using call by reference


void addNumbers(int *a, int *b, int *sum) {
*sum = *a + *b; // Dereference pointers to calculate the sum
}

int main() {
int num1, num2, result;

// Input two numbers


printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);

// Call the function to calculate the sum


addNumbers(&num1, &num2, &result);

// Display the result


printf("The sum of %d and %d is %d.\n", num1, num2, result);

return 0;
}

Output:

Enter the first number: 10


Enter the second number: 20
The sum of 10 and 20 is 30.
4.
a) Write a Program in C to append multiple lines at the end of a text file.

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

int main() {
FILE *file;
char filename[100];
char line[256];
int n;

// Prompt user for the file name


printf("Enter the name of the file to append to: ");
scanf("%s", filename);

// Open the file in append mode


file = fopen(filename, "a");
if (file == NULL) {
printf("Error: Could not open file %s\n", filename);
exit(1);
}

// Prompt user for the number of lines to append


printf("Enter the number of lines you want to append: ");
scanf("%d", &n);
getchar(); // Clear the newline character from input buffer

printf("Enter the lines to append (press Enter after each line):\n");


for (int i = 0; i < n; i++) {
printf("Line %d: ", i + 1);
fgets(line, sizeof(line), stdin);
fputs(line, file);
}

// Close the file


fclose(file);
printf("Successfully appended %d lines to %s\n", n, filename);

return 0;
}

Output :
Enter the name of the file to append to: example.txt
Enter the number of lines you want to append: 2
Enter the lines to append (press Enter after each line):
Line 1: This is the third line.
Line 2: This is the fourth line.
b) Write a Program in C to copy a file in another name.

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

int main() {
FILE *sourceFile, *destFile;
char sourceFilename[100], destFilename[100];
char ch;

// Prompt user for source file name


printf("Enter the name of the source file: ");
scanf("%s", sourceFilename);

// Open the source file in read mode


sourceFile = fopen(sourceFilename, "r");
if (sourceFile == NULL) {
printf("Error: Could not open source file %s\n", sourceFilename);
exit(1);
}

// Prompt user for destination file name


printf("Enter the name of the destination file: ");
scanf("%s", destFilename);

// Open the destination file in write mode


destFile = fopen(destFilename, "w");
if (destFile == NULL) {
printf("Error: Could not create destination file %s\n", destFilename);
fclose(sourceFile);
exit(1);
}

// Copy contents from source to destination file


while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destFile);
}

// Close both files


fclose(sourceFile);
fclose(destFile);

printf("File %s successfully copied to %s\n", sourceFilename, destFilename);

return 0;
}

Input:
Enter the name of the source file: source.txt
Enter the name of the destination file: copy.txt
Output:
File source.txt successfully copied to copy.txt

5.

a)Write recursive and non-recursive program for calculation of Factorial of an integer.

#include <stdio.h>

// Recursive function to calculate factorial


int factorial_recursive(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: factorial of 0 or 1 is 1
} else {
return n * factorial_recursive(n - 1); // Recursive case
}
}

int main() {
int num;

// Take user input


printf("Enter a number: ");
scanf("%d", &num);

// Calculate and print the factorial


printf("Factorial of %d is %d\n", num, factorial_recursive(num));

return 0;
}

Non-Recursive :
#include <stdio.h>

// Non-recursive function to calculate factorial


int factorial_iterative(int n) {
int result = 1;

// Loop to calculate factorial


for (int i = 1; i <= n; i++) {
result *= i;
}

return result;
}

int main() {
int num;

// Take user input


printf("Enter a number: ");
scanf("%d", &num);

// Calculate and print the factorial


printf("Factorial of %d is %d\n", num, factorial_iterative(num));

return 0;
}

Output :

Enter a number: 5
Factorial of 5 is 120

b) Write recursive and non-recursive C-program for calculation of GCD (n,m)

#include <stdio.h>

// Recursive function to calculate GCD using Euclidean Algorithm


int gcd_recursive(int a, int b) {
if (b == 0) {
return a; // Base case: GCD(a, 0) = a
} else {
return gcd_recursive(b, a % b); // Recursive call
}
}

int main() {
int n, m;

// Take user input


printf("Enter two numbers: ");
scanf("%d %d", &n, &m);

// Calculate and print the GCD


printf("GCD of %d and %d is %d\n", n, m, gcd_recursive(n, m));

return 0;
}

Non-Recursive :

#include <stdio.h>

// Non-recursive function to calculate GCD using Euclidean Algorithm


int gcd_iterative(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b; // Replace b with the remainder of a divided by b
a = temp; // Update a to the previous value of b
}
return a; // Once b becomes 0, a is the GCD
}

int main() {
int n, m;

// Take user input


printf("Enter two numbers: ");
scanf("%d %d", &n, &m);

// Calculate and print the GCD


printf("GCD of %d and %d is %d\n", n, m, gcd_iterative(n, m));

return 0;
}

Output :

Enter two numbers: 56 98


GCD of 56 and 98 is 14

c) Write recursive and non-recursive program in C for Towers of Honai : N Disks are to be transferred
from peg S to peg D with peg 1 as the intermediate peg.

#include <stdio.h>

void towersOfHanoiRecursive(int n, char source, char destination, char auxiliary) {


if (n == 1) {
printf("Move disk 1 from %c to %c\n", source, destination);
return;
}
towersOfHanoiRecursive(n - 1, source, auxiliary, destination);
printf("Move disk %d from %c to %c\n", n, source, destination);
towersOfHanoiRecursive(n - 1, auxiliary, destination, source);
}

int main() {
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);

printf("The sequence of moves is:\n");


towersOfHanoiRecursive(n, 'S', 'D', 'A');
return 0;
}

Non-recursive:
#include <stdio.h>
#include <math.h>

// Function to print the move


void printMove(int disk, char from, char to) {
printf("Move disk %d from %c to %c\n", disk, from, to);
}

// Non-recursive Towers of Hanoi implementation


void towersOfHanoiNonRecursive(int n) {
char source = 'S', destination = 'D', auxiliary = '1';
int totalMoves = pow(2, n) - 1;

// Adjusting pegs for even number of disks


if (n % 2 == 0) {
char temp = destination;
destination = auxiliary;
auxiliary = temp;
}

for (int i = 1; i <= totalMoves; i++) {


int disk = __builtin_ctz(i) + 1; // Find the disk to move
char from, to;

// Determine source and destination pegs for the move


if (i % 3 == 1) {
from = source;
to = destination;
} else if (i % 3 == 2) {
from = source;
to = auxiliary;
} else {
from = auxiliary;
to = destination;
}

// Swap pegs if disk is out of order


if (n % 2 == 0 && i % 3 != 1) {
char temp = to;
to = from;
from = temp;
}

printMove(disk, from, to);


}
}

int main() {
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);
printf("The sequence of moves using non-recursive approach is:\n");
towersOfHanoiNonRecursive(n);
return 0;
}

Output:

Enter the number of disks: 3

The sequence of moves using non-recursive approach is:


Move disk 1 from S to D
Move disk 2 from S to 1
Move disk 1 from D to 1
Move disk 3 from S to D
Move disk 1 from 1 to S
Move disk 2 from 1 to D
Move disk 1 from S to D

6.

a) Write a C Program that use both recursive and non-recursive functions to perform Linear
search for a Key value in a given list.

#include <stdio.h>

// Non-recursive Linear Search Function


int linearSearchNonRecursive(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Return the index of the key
}
}
return -1; // Key not found
}

// Recursive Linear Search Function


int linearSearchRecursive(int arr[], int n, int key, int index) {
if (index >= n) {
return -1; // Key not found
}
if (arr[index] == key) {
return index; // Return the index of the key
}
return linearSearchRecursive(arr, n, key, index + 1); // Recur for the next index
}

int main() {
int n, key, choice, result;
printf("Enter the number of elements in the list: ");
scanf("%d", &n);

int arr[n];
printf("Enter the elements of the list:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Enter the key to search for: ");


scanf("%d", &key);

printf("Choose the search method:\n");


printf("1. Non-recursive Linear Search\n");
printf("2. Recursive Linear Search\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
result = linearSearchNonRecursive(arr, n, key);
break;
case 2:
result = linearSearchRecursive(arr, n, key, 0);
break;
default:
printf("Invalid choice!\n");
return 0;
}

if (result != -1) {
printf("Key %d found at index %d\n", key, result);
} else {
printf("Key %d not found in the list.\n", key);
}

return 0;
}

Output:

Enter the number of elements in the list: 5


Enter the elements of the list:
10 20 30 40 50
Enter the key to search for: 30
Choose the search method:
1. Non-recursive Linear Search
2. Recursive Linear Search
Enter your choice: 1

Key 30 found at index 2


b) Write a C Program that use both recursive and non-recursive functions to perform Binary search
for a Key value in a given list.

#include <stdio.h>

// Function to perform binary search non-recursively


int binarySearchNonRecursive(int arr[], int size, int key) {
int low = 0, high = size - 1;

while (low <= high) {


int mid = low + (high - low) / 2;

if (arr[mid] == key)
return mid; // Return index if the key is found
else if (arr[mid] < key)
low = mid + 1; // Search in the right half
else
high = mid - 1; // Search in the left half
}
return -1; // Return -1 if the key is not found
}

// Function to perform binary search recursively


int binarySearchRecursive(int arr[], int low, int high, int key) {
if (low > high)
return -1; // Return -1 if the key is not found

int mid = low + (high - low) / 2;

if (arr[mid] == key)
return mid; // Return index if the key is found
else if (arr[mid] < key)
return binarySearchRecursive(arr, mid + 1, high, key); // Search in the right half
else
return binarySearchRecursive(arr, low, mid - 1, key); // Search in the left half
}

int main() {
int n, key, result;

printf("Enter the number of elements in the list: ");


scanf("%d", &n);

int arr[n];
printf("Enter %d sorted elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the key to search: ");
scanf("%d", &key);

// Non-recursive search
result = binarySearchNonRecursive(arr, n, key);
if (result != -1)
printf("Non-Recursive: Key found at index %d\n", result);
else
printf("Non-Recursive: Key not found\n");

// Recursive search
result = binarySearchRecursive(arr, 0, n - 1, key);
if (result != -1)
printf("Recursive: Key found at index %d\n", result);
else
printf("Recursive: Key not found\n");

return 0;
}

Output:

Enter the number of elements in the list: 6


Enter 6 sorted elements:
10 20 30 40 50 60
Enter the key to search: 40

Non-Recursive: Key found at index 3


Recursive: Key found at index 3

7.

a) Write a C-Program that implement stack (list operations) using arrays.

#include <stdio.h>

#define MAX 100 // Maximum size of the stack

typedef struct {

int data[MAX];

int top;

} Stack;
// Function to initialize the stack

void initializeStack(Stack* stack) {

stack->top = -1;

// Function to check if the stack is empty

int isEmpty(Stack* stack) {

return stack->top == -1;

// Function to check if the stack is full

int isFull(Stack* stack) {

return stack->top == MAX - 1;

// Function to push an element onto the stack

void push(Stack* stack, int value) {

if (isFull(stack)) {

printf("Stack Overflow! Cannot push %d\n", value);

} else {

stack->data[++stack->top] = value;

printf("Pushed %d onto the stack.\n", value);

// Function to pop an element from the stack

int pop(Stack* stack) {

if (isEmpty(stack)) {
printf("Stack Underflow! Cannot pop.\n");

return -1;

} else {

return stack->data[stack->top--];

// Function to peek the top element of the stack

int peek(Stack* stack) {

if (isEmpty(stack)) {

printf("Stack is empty! No top element.\n");

return -1;

} else {

return stack->data[stack->top];

// Function to display the stack

void display(Stack* stack) {

if (isEmpty(stack)) {

printf("Stack is empty!\n");

} else {

printf("Stack elements:\n");

for (int i = stack->top; i >= 0; i--) {

printf("%d\n", stack->data[i]);

}
}

int main() {

Stack stack;

initializeStack(&stack);

int choice, value;

do {

printf("\nStack Operations Menu:\n");

printf("1. Push\n");

printf("2. Pop\n");

printf("3. Peek\n");

printf("4. Display\n");

printf("5. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter the value to push: ");

scanf("%d", &value);

push(&stack, value);

break;

case 2:

value = pop(&stack);
if (value != -1)

printf("Popped value: %d\n", value);

break;

case 3:

value = peek(&stack);

if (value != -1)

printf("Top element: %d\n", value);

break;

case 4:

display(&stack);

break;

case 5:

printf("Exiting...\n");

break;

default:

printf("Invalid choice! Please try again.\n");

} while (choice != 5);

return 0;

Output:

1. Push

2. Push

3. Display

4. Peek
5. Pop

6. Display

7. Exit

Enter the value to push: 10

Pushed 10 onto the stack.

Enter the value to push: 20

Pushed 20 onto the stack.

Stack elements:

20

10

Top element: 20

Popped value: 20

Stack elements:

10

b) Write a C-Program that implement stack (list operations) using Linked list.

#include <stdio.h>

#include <stdlib.h>

// Node structure for the linked list

typedef struct Node {

int data;

struct Node* next;

} Node;

// Function to create a new node


Node* createNode(int value) {

Node* newNode = (Node*)malloc(sizeof(Node));

if (!newNode) {

printf("Memory allocation failed!\n");

exit(1);

newNode->data = value;

newNode->next = NULL;

return newNode;

// Function to push an element onto the stack

void push(Node** top, int value) {

Node* newNode = createNode(value);

newNode->next = *top;

*top = newNode;

printf("Pushed %d onto the stack.\n", value);

// Function to pop an element from the stack

int pop(Node** top) {

if (*top == NULL) {

printf("Stack Underflow! Cannot pop.\n");

return -1;

Node* temp = *top;

int value = temp->data;

*top = (*top)->next;
free(temp);

return value;

// Function to peek the top element of the stack

int peek(Node* top) {

if (top == NULL) {

printf("Stack is empty! No top element.\n");

return -1;

return top->data;

// Function to display the stack

void display(Node* top) {

if (top == NULL) {

printf("Stack is empty!\n");

return;

printf("Stack elements:\n");

while (top != NULL) {

printf("%d\n", top->data);

top = top->next;

int main() {

Node* stack = NULL; // Initialize the stack as empty


int choice, value;

do {

printf("\nStack Operations Menu:\n");

printf("1. Push\n");

printf("2. Pop\n");

printf("3. Peek\n");

printf("4. Display\n");

printf("5. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter the value to push: ");

scanf("%d", &value);

push(&stack, value);

break;

case 2:

value = pop(&stack);

if (value != -1)

printf("Popped value: %d\n", value);

break;

case 3:

value = peek(stack);

if (value != -1)

printf("Top element: %d\n", value);


break;

case 4:

display(stack);

break;

case 5:

printf("Exiting...\n");

break;

default:

printf("Invalid choice! Please try again.\n");

} while (choice != 5);

return 0;

Output:

1. Push

2. Push

3. Display

4. Peek

5. Pop

6. Display

7. Exit

Enter the value to push: 10

Pushed 10 onto the stack.

Enter the value to push: 20


Pushed 20 onto the stack.

Stack elements:

20

10

Top element: 20

Popped value: 20

Stack elements:

10
D:\maha>javac Ascending_Order.java D:\
maha>java Ascending_Order
Enter number of names you want to enter:4
Enter all the names:
satish
yoshitha
maha
mani
Names in Sorted Order:maha,mani,satish,yoshitha
1. Write a Java Program that illustrates how runtime polymorphism is achieved.
class Shape {
void draw()
{
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing a square");
}
}

public class Poly_example {


public static void main(String[] args) {
Shape s1 = new Circle();
Shape s2 = new Square();

s1.draw(); // Calls draw() of Circle class


s2.draw(); // Calls draw() of Square class
}
}
Output:
D:\maha>javac Poly_example.java D:\
maha>java Poly_example Drawing a
circle
Drawing a square
2. Write a Java Program to create and demonstrate packages.
(i) Creating a package:
Steps:
1. First declare the name of the package using package keyword
Example: package mypack;
2. Type the following SOURCE-CODE under this package statement. In package : class
data, methods all are public

package mypack
public class box
{
public int
l=10,b=20;
public void
display()
{
System.out.println(l);
System.out.println(b);
}
}
3. Create sub directory with a name same that of package name under the current
working directory by as follows. d:\>md mypack
4. Under this subdirectory store the above SOURCE-CODE with a file name “box.java”.

(ii) importing a package:


Steps:
1. packages can be accessed by using the import statement

General form: import pack1[.pack2].(classname/*);Example:


import java.io.*;
Here pack1 is name of top level package and pack2 is name of sub package
2. Type the following SOURCE-CODE under the current working directory and save
the SOURCE-CODE with a file name “example.java”.

import
mypack.bo
x;class
packagede
mo
{
public static void main(String args[])
{
box
b1=new
box();
b1.display(
);
}
}
3. Now compile the above SOURCE-CODE in the current working directory d:\
javac packagedemo.java
4. Execute the above SOURCE-CODE in current working directory

java packagedemo
OUT-PUT:
10
20
3. Write a Java Program, using StringTokenizer class, which reads a line of integers
and then displays each integer and the sum of all integers.
import java.util.*;
class Demo_string_tokenizer{
public static void main(String args[])
{ int n;
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter integers with one space gap:");
String s = sc.nextLine();
StringTokenizer st = new StringTokenizer(s, " ");
while (st.hasMoreTokens()) {
String temp = st.nextToken();
n = Integer.parseInt(temp);
System.out.println(n);
sum = sum + n;
}
System.out.println("sum of the integers is: " + sum);
sc.close();
}
}
Output:
D:\maha>javac Demo_string_tokenizer.java
D:\maha>java Demo_string_tokenizer
Enter integers with one space gap:
21
2
1
sum of the integers is: 3
4. Write a Java Program that reads on file name
form the user then displays information about
whether the file exists, whether the file is readable/
writable, the type of file and the length of the file in
bytes and display the content of the using
FileInputStream class.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Files_example {
public static void main(String args[]) {
//Creating a Path object
Path path = Paths.get("D:/maha/sample.txt");
//Verifying if the file is readable
boolean bool = Files.isReadable(path);
if(bool) {
System.out.println("readable");
} else {
System.out.println("not readable");
}
bool = Files.isWritable(path);
if(bool) {
System.out.println("writable");
} else {
System.out.println("not writable");
}
bool = Files.isExecutable(path);
if(bool) {
System.out.println("executable");
} else {
System.out.println("not executable");
}
}
}
Output:
D:\maha>javac Files_example.java D:\
maha>java Files_example
not readable
not writable
not
executable
5. Write a Java Program that displays the
number of characters, lines and words in a
text/text file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Word_countin_file
{
public static void main(String[] args)
{
BufferedReader reader =
null; int charCount = 0;
int wordCount = 0;
int lineCount = 0;
try
{
reader = new BufferedReader(new FileReader("D:/maha/sample.txt"));
String currentLine = reader.readLine();
while (currentLine != null)
{
lineCount++;
String[] words = currentLine.split(" ");
wordCount = wordCount + words.length;
for (String word : words){
charCount = charCount + word.length();
}
currentLine = reader.readLine();
}
System.out.println("Number Of Chars In A File : "+charCount);
System.out.println("Number Of Words In A File : "+wordCount);
System.out.println("Number Of Lines In A File : "+lineCount);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
reader.close(); //Closing the reader
}
catch (IOException e)
{ e.printStackTrace
();
}
}
}
}
Output:
D:\maha>javac Word_countin_file.java
D:\maha>java Word_countin_file
Number Of Chars In A File : 86
Number Of Words In A File : 14
Number Of Lines In A File : 4
6. Write an Applet that displays the content of a file.
import java.applet.*;
import java.awt.*;
import java.io.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
String content = "";
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStream fis = new FileInputStream("sample.txt");
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
fis.close();
content = new String(buff);
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)
{
System.out.println("Cannot read file...");
}
g.drawString(content,20,20);
}
}
<applet code="MyApplet" height="300" width="500">
</applet>
Output:
7. Write a Java Program that works as a
simple calculator. Use a grid layout to
arrange buttons for the digits and for the +
*?% operations. Add a text field to display
the result.
import java.awt.*;
import java.awt.event.*;
public class MyCalculator extends Frame implements ActionListener {
double num1,num2,result;
Label lbl1,lbl2,lbl3;
TextField tf1,tf2,tf3;
Button btn1,btn2,btn3,btn4;
char op;
MyCalculator() {
lbl1=new Label("Number 1: ");
lbl1.setBounds(50,100,100,30);

tf1=new TextField();
tf1.setBounds(160,100,100,30);

lbl2=new Label("Number 2: ");


lbl2.setBounds(50,170,100,30);

tf2=new TextField();
tf2.setBounds(160,170,100,30);

btn1=new Button("+");
btn1.setBounds(50,250,40,40);

btn2=new Button("-");
btn2.setBounds(120,250,40,40);

btn3=new Button("*");
btn3.setBounds(190,250,40,40);

btn4=new Button("/");
btn4.setBounds(260,250,40,40);

lbl3=new Label("Result : ");


lbl3.setBounds(50,320,100,30);
tf3=new TextField();
tf3.setBounds(160,320,100,30);

btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
btn4.addActionListener(this);
add(lbl1); add(lbl2); add(lbl3);
add(tf1); add(tf2); add(tf3);
add(btn1); add(btn2); add(btn3); add(btn4);
setSize(400,500);
setLayout(null);
setTitle("Calculator");
setVisible(true);

public void actionPerformed(ActionEvent ae) {

num1 = Double.parseDouble(tf1.getText());
num2 = Double.parseDouble(tf2.getText());

if(ae.getSource() == btn1)
{
result = num1 + num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn2)
{
result = num1 - num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn3)
{
result = num1 * num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn4)
{
result = num1 / num2;
tf3.setText(String.valueOf(result));
}
}

public static void main(String args[]) {


MyCalculator calc=new MyCalculator();
}
}
Output:
D:\maha>javac MyCalculator.java D:\
maha>java MyCalculator
8. Write a Java Program for handling mouse events.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Mouse_Event implements MouseListener,ActionListener
{
static JFrame frame;
static JTextField text;
//Driver function
public static void main(String[] args)
{
frame=new JFrame("Mouse
Event");
frame.setBackground(Color.white);
frame.setSize(500,500);
frame.setLayout(null);
//Create a TextField
text=new JTextField();
text.setBounds(0,0,500,50);
frame.add(text);
//Create a exit button to close the frame
JButton exit=new JButton("Exit");
exit.setBounds(220,235,60,30);
frame.add(exit);
//Create an object of the class Mouse_Event
Mouse_Event obj=new Mouse_Event();
//Associate MouseListener with the frame
frame.addMouseListener(obj);
//Associate ActionListener with button exit
exit.addActionListener(obj);
//Display frame
frame.setVisible(true);
}
//function to dispose the frame on click of exit
button @Override
public void actionPerformed(ActionEvent e)
{
frame.dispose();
}
//function to get co-ordinates from where cursor entered the frame
@Override
public void mouseEntered(MouseEvent e)
{
text.setText("");
text.setText("Mouse Entered the frame from point ");
text.setText(text.getText()+e.getX()+" "+e.getY());
}
//function to get co-ordinates from where cursor exited the frame
@Override
public void mouseExited(MouseEvent e)
{
text.setText("");
text.setText("Mouse Exited the frame from point ");
text.setText(text.getText()+e.getX()+" "+e.getY());
}
//function to get co-ordinates where mouse was released
@Override
public void mouseReleased(MouseEvent e)
{
text.setText("");
String button="Right";
if(e.getButton()==MouseEvent.BUTTON1)
button="Left";
text.setText(button+" Button Released at point ");
text.setText(text.getText()+e.getX()+" "+e.getY());
}
//function to get co-ordinates where and which button of mouse was pressed
@Override
public void mousePressed(MouseEvent e)
{
text.setText("");
String button="Right";
if(e.getButton()==MouseEvent.BUTTON1)
button="Left";
text.setText(button+" Button Pressed at point ");
text.setText(text.getText()+e.getX()+" "+e.getY());
}
//function to get co-ordinates where and which button of mouse was clicked
@Override
public void mouseClicked(MouseEvent e)
{
text.setText("");
String button="Right";
if(e.getButton()==MouseEvent.BUTTON1)
button="Left";
text.setText(button+" Button Clicked at point ");
text.setText(text.getText()+e.getX()+" "+e.getY());
}
}
Output:
D:\maha>javac Mouse_Event.java
D:\maha>java Mouse_Event
9. Write a Java Program demonstrating the life cycle of a thread.
class MyThread implements Runnable {
@Override
public void run()
{ try {
// Running state
System.out.println(Thread.currentThread().getName() + " is RUNNING");
// Simulating waiting state using sleep
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " is in WAITING/SLEEPING");
synchronized (this) {
// Simulating timed waiting state using wait with timeout
wait(1000);
System.out.println(Thread.currentThread().getName() + " is in TIMED_WAITING");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// Thread terminates, moves to TERMINATED state
System.out.println(Thread.currentThread().getName() + " is TERMINATED");
}
}
public class ThreadStatesDemo {
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread, "MyThread");
// New state
System.out.println(thread.getName() + " is in NEW state");
// Starting the thread, moves to RUNNABLE
thread.start();
System.out.println(thread.getName() + " is RUNNABLE");
// Main thread waits for the child thread to finish
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
D:\maha>javac ThreadStatesDemo.java D:\
maha>java ThreadStatesDemo
MyThread is in NEW state
MyThread is RUNNABLE
MyThread is RUNNING
MyThread is in WAITING/SLEEPING
MyThread is in TIMED_WAITING
MyThread is TERMINATED
10. Write a Java Program that lets users
create Pie charts. Design your own user interface
(with Swings& AWT).
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;

class Slice
{ double
value; Color
color;
public Slice(double value, Color color)
{ this.value = value;
this.color = color;
}
}
class MyComponent extends JComponent
{ Slice[] slices = {
new Slice(5, Color.black), new Slice(33, Color.green), new Slice(20, Color.yellow), new
Slice(15, Color.red)
};
MyComponent() {}
public void paint(Graphics g)
{ drawPie((Graphics2D) g, getBounds(), slices);
}
void drawPie(Graphics2D g, Rectangle area, Slice[] slices)
{ double total = 0.0D;

for (int i = 0; i < slices.length; i++)


{ total += slices[i].value;
}
double curValue = 0.0D;
int startAngle = 0;
for (int i = 0; i < slices.length; i++)
{ startAngle = (int) (curValue * 360 / total);
int arcAngle = (int) (slices[i].value * 360 / total);
g.setColor(slices[i].color);
g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);
curValue += slices[i].value;
}
}
}
public class Frame_pie {
public static void main(String[] argv) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MyComponent());
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Output:
D:\maha>javac Frame_pie.java
D:\maha>java Frame_pie
11. Write a Java Program to implement a Queue, using user defined Exception
Handling (also make use of throw, throws).
import java.util.*;
import java.lang.*;
class QueueError extends Exception
{
public QueueError(String msg)
{
super(msg);
}
}
class Que
{
private int size;
private int front = -1;
private int rear = -1;
private Integer[] queArr;
public Que(int size)
{
this.size = size;
queArr = new Integer[size];
}
public void insert(int item) throws Exception,QueueError
{
try
{
if(rear == size-1)
{
throw new QueueError("Queue Overflow");
}
else if(front==-1)
{
rear++;
queArr[rear] = item;
front = rear;
}
else
{
rear++;
queArr[rear] = item;
}
}catch(QueueError qe)
{
qe.printStackTrace();
}
}
public void delete() throws Exception,QueueError
{
try
{
if(front == -1)
{
throw new QueueError("Queue Underflow");
}
else if(front==rear)
{
System.out.println("\nRemoved "+queArr[front]+" from Queue");
queArr[front] = null;
front--;
rear--;
}
else
{
System.out.println("\nRemoved "+queArr[front]+" from Queue");
queArr[front] = null;
for(int i=front+1;i<=rear;i++)
{
queArr[i-1]=queArr[i];
}
rear--;
}
}
catch(QueueError qe)
{
qe.printStackTrace();
}
}
public void display() throws Exception,QueueError
{
try
{
if(front==-1)
throw new QueueError("Queue is Empty");
else
{
System.out.print("\nQueue is: ");
for(int i=front;i<=rear;i++)
{
System.out.print(queArr[i]+"\t");
}
System.out.println();
}
}
catch(QueueError qe)
{
qe.printStackTrace();
}
}
}
class Exception_queue
{
public static void main(String[] args) throws Exception,QueueError
{
System.out.println("\n\n\tQueue test using Array\n\n");
Scanner scan = new Scanner(System.in);
System.out.print("Enter size of Queue array: ");
int size = scan.nextInt();
Que que = new Que(size);
char ch;
try
{
while(true)
{
System.out.println("\n\n\tQueue operations \n");
System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Display");
System.out.println("4. Exit\n");
System.out.print("Enter your choice: ");
int choice = scan.nextInt();
switch(choice)
{
case 1: System.out.print("\nEnter integer number to insert:");
que.insert(scan.nextInt());
break;
case 2:que.delete();
break;
case 3:que.display();
break;
case 4:return;
}
}
}
catch(QueueError qe)
{
qe.printStackTrace();
}
}
}
Output:
D:\maha>javac Exception_queue.java
D:\maha>java Exception_queue
Queue test using Array
Enter size of Queue array: 4
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter integer number to insert:23
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 3
Queue is: 23
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 2
Removed 23 from Queue

Queue operations

1. Insert
2. Delete
3. Display
4. Exit

Enter your choice: 23


Queue operations

1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 3
QueueError: Queue is Empty
at Que.display(Exception_queue.java:81)
at Exception_queue.main(Exception_queue.java:126)
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 4

You might also like