Mca r20 Java
Mca r20 Java
KOMMADI, VISAKHAPATNAM
(Approved by AICTE, New Delhi & Affiliated to JNTU Gurajada Vizianagaram)
NBA & NAAC Accredited
CERTIFICATE
is a student studying
in the subject
#include <stdio.h>
int main() {
int n, sum = 0;
return 0;
}
Output:
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;
return 0;
}
Output:
#include <stdio.h>
#include <math.h>
int main() {
int num, originalNum, remainder, result = 0, n = 0;
originalNum = num;
originalNum = num;
return 0;
}
Output:
#include <stdio.h>
int main() {
int number;
unsigned long long result;
return 0;
}
Output:
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);
// 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);
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
int main() {
int rows, cols;
int matrix[MAX][MAX], transposed[MAX][MAX];
if (rows > MAX || cols > MAX || rows <= 0 || cols <= 0) {
printf("Invalid dimensions. Please enter dimensions between 1 and %d.\n", MAX);
return 1;
}
printf("Transposed Matrix:\n");
displayMatrix(transposed, cols, rows);
return 0;
}
Output:
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>
int main() {
int number;
return 0;
}
Output:
b) Write a recursive program which computes the nth Fibonacci number, for appropriate values
of n.
#include <stdio.h>
int main() {
int 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 :
#include <stdio.h>
int main() {
int num1, num2, result;
return 0;
}
Output:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file;
char filename[100];
char line[256];
int n;
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;
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.
#include <stdio.h>
int main() {
int num;
return 0;
}
Non-Recursive :
#include <stdio.h>
return result;
}
int main() {
int num;
return 0;
}
Output :
Enter a number: 5
Factorial of 5 is 120
#include <stdio.h>
int main() {
int n, m;
return 0;
}
Non-Recursive :
#include <stdio.h>
int main() {
int n, m;
return 0;
}
Output :
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>
int main() {
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);
Non-recursive:
#include <stdio.h>
#include <math.h>
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:
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>
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]);
}
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:
#include <stdio.h>
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
}
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;
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:
7.
#include <stdio.h>
typedef struct {
int data[MAX];
int top;
} Stack;
// Function to initialize the stack
stack->top = -1;
if (isFull(stack)) {
} else {
stack->data[++stack->top] = value;
if (isEmpty(stack)) {
printf("Stack Underflow! Cannot pop.\n");
return -1;
} else {
return stack->data[stack->top--];
if (isEmpty(stack)) {
return -1;
} else {
return stack->data[stack->top];
if (isEmpty(stack)) {
printf("Stack is empty!\n");
} else {
printf("Stack elements:\n");
printf("%d\n", stack->data[i]);
}
}
int main() {
Stack stack;
initializeStack(&stack);
do {
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
scanf("%d", &value);
push(&stack, value);
break;
case 2:
value = pop(&stack);
if (value != -1)
break;
case 3:
value = peek(&stack);
if (value != -1)
break;
case 4:
display(&stack);
break;
case 5:
printf("Exiting...\n");
break;
default:
return 0;
Output:
1. Push
2. Push
3. Display
4. Peek
5. Pop
6. Display
7. Exit
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>
int data;
} Node;
if (!newNode) {
exit(1);
newNode->data = value;
newNode->next = NULL;
return newNode;
newNode->next = *top;
*top = newNode;
if (*top == NULL) {
return -1;
*top = (*top)->next;
free(temp);
return value;
if (top == NULL) {
return -1;
return top->data;
if (top == NULL) {
printf("Stack is empty!\n");
return;
printf("Stack elements:\n");
printf("%d\n", top->data);
top = top->next;
int main() {
do {
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
scanf("%d", &value);
push(&stack, value);
break;
case 2:
value = pop(&stack);
if (value != -1)
break;
case 3:
value = peek(stack);
if (value != -1)
case 4:
display(stack);
break;
case 5:
printf("Exiting...\n");
break;
default:
return 0;
Output:
1. Push
2. Push
3. Display
4. Peek
5. Pop
6. Display
7. Exit
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");
}
}
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”.
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);
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);
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);
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));
}
}
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;
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
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