Aamir

Download as pdf or txt
Download as pdf or txt
You are on page 1of 121

SEVENTH DAY ADVENTIST SENIOR

SECONDARY SCHOOL
36, Park Street, Kolkata-700016

Computer Project
(2022-23)

Name : Md Aamir
Class : XII
Sec : Science
Subject : Computer

Submitted To : Kaushambi Sinha Mondal

Submitted On : 08th December ,2022

1
ACKNOWLEDGEMENT

I would like to express my special thanks of gratitude to my


teacher Ms. Kaushambi Sinha Mondalas well as our principal
Mr. Ashok Gill who gave me the golden opportunity to do
this wonderful project on the topic “Introduction to Java”,
which also helped me in doing a lot of research and I came
to know about so many new things I am really thankful to
them

Secondly, I would also like to thank my parents and friends who


helped me a lot in finalizing this project within the limited time
frame.

2
CONTENT
SL NO. TOPIC PAGE NO.
PART-1 THEORY
1 INTRODUCTION TO JAVA 4
2 METHODS AND CONSTRUCTORS 5
3 STRING MANIPULATION 9
4 ARRAYS 13
Part-2 PROGRAMS
1 A program to print the pattern. 15
2 A string program to replace each consonant present in a word with the 18
previous letter.
3 A program to convert a decimal number to an octal number. 22
4 A string program to start the letters of a word with vowels followed by the 25
consonants.
5 A string program to print all the possible combinations of a three letter 29
word.
6 A constructor program to find the roots of a quadratic equation. 31
7 A program to shift elements of two 1-d arrays in 'Z' form. 34
8 A string program to print a word in an alphabetical order. 37
9 A program to print HCF of two numbers using recursion. 40
10 A program to convert a decimal number to binary using recursion. 42
11 To Display Spiral Matrix. 44
12 To Display Magic Square 49
13 A program to convert two decimal number to binary and add both the binary 54
numbers.
14 A program to check whether a number is magic number or not. 58
15 A string program to replace a vowel with the next vowel in a word/string. 61
16 A program to print the elements only above the right diagonal in a 2-d array. 64
17 A program to print sum of all boundary elements in a 2-d array. 68
18 A program to print only left and right diagonals of a 2-d array. 71
19 A program to merge two 1-d arrays and sort them in ascending order. 74
20 A method overloading program to find areas of square, rectangle or circle as 78
per the user's choice
21 A constructor program to the wage of an employee. 82
22 A program to check whether a number is Emirp number or not. 87
23 A program to calculate salary of an employee 90
24 A program to calculate the perimeter and of a Parallelogram 95
25 A program to decode the entered string 99
26 A program to show the working of the Automatic Teller Machine 104
27 A program to show the working of the Calculator 108
28 A program to display Calendar of any month of any year 112
29 A program to calculate GCD using Recursion 117
30 A program to create a string and replace all vowels with* 119
3
PART-1
THEORY
INTRODUCTION TO JAVA
Java is a programming language created by James Gosling from Sun Microsystems (Sun) in 1991.
The target of Java is to write a program once and then run this program on multiple operating
systems. The first publicly available version of Java (Java 1.0) was released in 1995. Sun
Microsystems was acquired by the Oracle Corporation in 2010. Oracle has now the steermanship
for Java. In 2006 Sun started to make Java available under the GNU General Public License
(GPL). Oracle continues this project called OpenJDK.

Over time new enhanced versions of Java have been released. The current version of Java is Java
1.8 which is also known as Java 8.

Java is defined by a specification and consists of a programming language, a compiler, core


libraries and a runtime (Java virtual machine) The Java runtime allows software developers to
write program code in other languages than the Java programming language which still runs on
the Java virtual machine. The Java platform is usually associated with the Java virtual
machine and the Java core libraries.

The Java language was designed with the following properties:

• Platform independent: Java programs use the Java virtual machine as abstraction and do not
access the operating system directly. This makes Java programs highly portable. A Java
program (which is standard-compliant and follows certain rules) can run unmodified on all
supported platforms, e.g., Windows or Linux.
• Object-orientated programming language: Except the primitive data types, all elements in Java
are objects.
• Strongly-typed programming language: Java is strongly-typed, e.g., the types of the used
variables must be pre-defined and conversion to other objects is relatively strict, e.g., must be
done in most cases by the programmer.
• Interpreted and compiled language: Java source code is transferred into the bytecode format
which does not depend on the target platform. These bytecode instructions will be interpreted
by the Java Virtual machine (JVM). The JVM contains a so called Hotspot-Compiler which
translates performance critical bytecode instructions into native code instructions.
• Automatic memory management: Java manages the memory allocation and de-allocation for
creating new objects. The program does not have direct access to the memory. The so-called
garbage collector automatically deletes objects to which no active pointer exists.

The Java syntax is similar to C++. Java is case-sensitive, e.g., variables


called myValue and myvalue are treated as different variables.

4
METHODS AND CONSTRUCTOR
A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known
as functions.

Why use methods? To reuse code: define the code once, and use it many times

Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses (). Java provides some pre-defined methods,
such as System.out.println(), but you can also create your own methods to
perform certain actions:

Example
Create a method inside Main:

publicclassMain{

staticvoidmyMethod(){

// code to be executed

A constructor in Java is a special method that is used to initialize objects. The


constructor is called when an object of a class is created. It can be used to set
initial values for object attributes:

Example
Create a constructor:

// Create a Main class

publicclassMain{

intx;// Create a class attribute

5
// Create a class constructor for the Main class

publicMain(){

x =5;// Set the initial value for the class attribute x

publicstaticvoidmain(String[]args){

MainmyObj=newMain();// Create an object of class Main (This will call the


constructor)

System.out.println(myObj.x);// Print the value of x

// Outputs 5

Sr. Key Constructors Methods


No.

Purpose Constructor is used to create and initialize Method is used to execute


1
an Object . certain statements.

Invocation A constructor is invoked implicitly by the A method is to be invoked


2
System. during program code.

Invocation A constructor is invoked when new A method is invoked when it is


3
keyword is used to create an object. called.

Return A constructor can not have any return type. A method can have a return
4
type type.

Object A constructor initializes an object which is A method can be invoked only


5
not existent. on existing object.

Name A constructor must have same name as A method name can not be
6
that of the class. same as class name.

6
Types of Method
There are two types of methods in Java:
• Predefined Method.
• User-defined Method.

In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them
in the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc. When we call any of the predefined methods in our
program, a series of codes related to the corresponding method runs in the background
that is already stored in the library.

Each and every predefined method is defined inside a class. Such as print() method is
defined in the java.io.PrintStream class. It prints the statement that we write inside
the method. For example, print("Java"), it prints Java on the console.

User defined Method


User Defined Methods in Java, Java static methods, Java non static methods, java
method with return a value and java method without return any value.

Java Built-in methods – String methods, Array methods, Number methods and
character methods

7
Types of Java Constructors
There are three types of constructors: Default, No-arg constructor and
Parameterized.

Default constructor
If you do not implement any constructor in your class, Java compiler inserts
a default constructor into your code on your behalf. This constructor is known as
default constructor. You would not find it in your source code(the java file) as it
would be inserted into the code during compilation and exists in .class file.

Non-parameterized constructor:
Constructor with no arguments is known as non-parameterized constructor.
The signature is same as default constructor, however body can have any code
unlike default constructor where the body of the constructor is empty.

Parameterized constructor
Constructor with arguments(or you can say parameters) is known
as Parameterized constructor.

8
STRING MANIPULATION
String manipulations are very common things for any programming language. Java is a

programming language where we can see a huge amount of built-in functions to fulfill our

purpose of string manipulations. There are various things you can do in Java programming like

getting the length of a string, finding the character within a string, String concatenation, getting

substring, string modification, etc. We can also change the case of a given string, this is also a

part of the string manipulation. We have some built-in functions to handle this.

How does it work?


Java programming language comes up with a huge list of string manipulations functions we can

use as per our business requirements. We can manipulate a string in many ways.

Given below are the different ways for manipulating a string:

1. String concatenations: Suppose we have two strings in separate. We want these two

strings to be concatenated in one. For this, we can simply use the traditional one (the +

operator).

String str1= “Hello”;

String str2 = “India”;

String finalResult = str1+” ”+str2;

9
2. Changing the case of the given string: We can change the case of the

string whenever required by using toLowerCase() and the toUpperCase() Java

built-in functions.

3. Sub-string inside a string: we have a Contain() method in Java to deal with

the checking of the string inside a string. We can use this function to check

with some sequence of characters in a defined string. We can also use the

substring() of the Java.

4. Cleaning the string with the unwanted character: For this, we can use the

Java trim() function. This function can be used to remove the space from the

beginning and the end of the given string.

5. String reverse: String reverse is again the part of string manipulation. This

is all about getting the string from the last index to the first index. For

example, we have “Hello world!”, the reverse of this string will be

“!dlroWolleH”.

Syntax:

1. toLowerCase()

10
public String toLowerCase();

This function changes the case of the given string to the lower case. We can

use this function at the time of string to handle the ignore case with the

compareTo() function itself.

2. toUpperCase()

public String toLowerCase();

This function remains the same as toLowerCase() but it changes the case to

uppercase.

3. Substring()

String substring(int StartIndex, int LastIndex)

In the example code area, we will see the use of this function with the index as

an input and the output as well. For this, we need to have a string upon which

we will be performing this operation. We can use the position from where we

want the string in place of the StartIndex and we can replace the LastIndex

with the end index to where we want the string.

11
ARRAYS
An array is a container object that holds a fixed number of values of a
single type. The length of an array is established when the array is created.
After creation, its length is fixed. You have seen an example of arrays
already, in the main method of the "Hello World!" application. This section
discusses arrays in greater detail.

An array of 10 elements.

Each item in an array is called an element, and each element is accessed


by its numerical index. As shown in the preceding illustration, numbering
begins with 0. The 9th element, for example, would therefore be accessed
at index 8.

The following program, ArrayDemo, creates an array of integers, puts


some values in the array, and prints each value to standard output.

There are two types of arrays:


1)Single dimensional Array
2)Multidimensional Array

12
Single Dimensional Arrays

one-dimensional array in Java programming.


Anything having one-dimension means that there is only one parameter to deal
with. In regular terms, it is the length of something. Similarly, as far as an array is
concerned, one dimension means it has only one value per location or index.
One-dimensional array in Java programming is an array with a bunch of values
having been declared with a single index.

class OnedimensionalStandard
{
3
public static void main(String args[])
4
{
5
int[] a=new int[3];//declaration
6
a[0]=10;//initialization
7
a[1]=20;
8
a[2]=30;
9
//printing array
10
System.out.println("One dimensional array elements are");
11
System.out.println(a[0]);
12
System.out.println(a[1]);
13
System.out.println(a[2]);
14
}
15 }

Output:
1 One dimensional array elements are
2 10
3 20
4 30

13
Multidimensional Array in Java
A multidimensional array is an array of arrays. Each element of a
multidimensional array is an array itself. For example,

int[][] a = newint[3][4];

Here, we have created a multidimensional array named a. It is a 2-


dimensional array, that can hold a maximum of 12 elements,

2-dimensional Array

Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts with 0 and

not 1.

Let's take another example of the multidimensional array. This time we will be creating a 3-

dimensional array. For example,

String[][][] data = new String[3][4][2];

Here, data is a 3d array that can hold a maximum of 24 (3*4*2) elements of type String.

14
Part-2
Programs
Question 1
Write a program in java to display the given pattern:-
12345
1234
123
12
1
12
123
1234
12345

Algorithm
Step 1: Start
Step 2: Initialize n=5
Step 3: Start a nested for loop,
Condition for outer loop: (int i=1;i<=5;i++)
Condition for inner loop: (int j=1;j<=n;j++)
Step 4: Print the value of j every time the loop
initializes
Step 5: End the loop
Step 6: Stop
15
Answer
public class Pattern
{
public static void main(String[] args)
{
//Printing upper half of the pattern
for (int i = 5; i>= 1; i--)
{
for (int j = 1; j <= i; j++)
{
System.out.print(j+" ");
}
System.out.println();
}
//Printing lower half of the pattern
for (inti = 2; i<= 5; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(j+" ");
}
System.out.println();
}

16
}
}

Output
12345
1234
123
12
1
12
123
1234
12345

Variable Description Table

Variable Name Variable Type Purpose


i int Control variable for
outer for loop
j int Control variable for
InnerFor loop

17
Question 2
Write a program to input a sentence and create a new sentence by
replacing each consonant with the previous letter. If the previous
letter in a vowel, then replace it with the next letter. display the new
sentence

Algorithm:
Step 1: Start
Step 2: Accept a sentence in upper case and store it in s
Step 3: Find the length of the sentence
Step 4: Initialize ch and chr as characters and String st
Step 5: Start a for loop from int i=0 to i<l
Step 6: Check every character at i ,
If it is a vowel, then store it as it is in st
If it is a consonant, then store the character at (i-1) in chr
Step 7: Add st and chr
Step 8: End the loop
Step 9: Print st
Step 10: Stop

18
Answer
Import java.util.*;
class Consonants{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);//Taking input
System.out.print("ENTER THE SENTENCE");
String s = sc.nextLine();
s = s.toUpperCase();
String t = "";
for(inti = 0; i<s.length(); i++){
charch = s.charAt(i);//extracting character from string
if(Character.isLetter(ch)){//checking if it is a vowel
if(isVowel(ch))
t += ch;
else{
char p = (char)(ch - 1);
if(isVowel(p))
t += (char)(ch + 1);
else
t += p;
}
}
else

19
t += ch;
}
System.out.println(t);
}
public static booleanisVowel(char ch){
switch(ch){//checking condition
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return true;
default:
return false;
}
}//end of main
}//end of class

20
Output
ENTER THE SENTENCE
THE CAPITAL OF INDIA IS NEW DELHI
SGE BAQISAK OG IMCIA IR MEV CEKGI

Variable Description Table


Variable Name Variable Type Purpose
s String For storing the string
t String For storing modified
string
i int Loop variable
ch,p char For extracting
character from string

21
Question 3
Write a program to specify a class DeciOct to convert a decimal number
to its equivalent octal number Do specify the main() function.

Algorithm:
Step 1: Start
Step 2: Accept a decimal number
Step 3: Use the method toOctalString(int) to convert the decimal
number to octal number
Step 4: Print the octal number
Step 5: Stop

Answer
Importjava.util.*;
classDeciOct
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
int n=sc.nextInt();//taking input
System.out.println("THE OCTAL NUMBER IS:"+cal(n));//printing the
result
}//end of main
public static intcal(int n)

22
{ int r=0;int n1=0;int rev=0;
while(n!=0)
{
r=n%8;//condition to convert decimal to octal
n=n/8;
n1=r+n1*10;
}
while(n1>0)
{
r=n1%10;
rev=rev*10+r;
n1=n1/10;
} return rev;
}
}//end of class

23
Output
ENTER THE NUMBER
10
THE OCTAL NUMBER IS:12

Variable Description Table


Variable Name Variable Type Purpose
n int For storing input
r int For storing remainder
n1 int For storing copy of n
rev int For storing reverse

24
Question 4
Design a class ConsChange to input a word and shift all the consonants
of the word to the beginning followerd by the vowels. Display the new
words.

Algorithm
Step 1: Start
Step 2: Make a constructor ConsChange() to initialize variables len
and word
Step 3: Create a function readword() to accept the word and find its
length.
Step 4: Create a function shiftcons() to shift all the consonants
present in the word to the beginning.
Step 5 : Create a function changeword() to store the new word in
variable ‘s’
Step 6: Print the changed word
Step 7: Stop

Answer
import java.io.*;//importing package
import java.util.*;
classConsChange{
private String word;
privateintlen;
publicConsChange(){//constructor to initialize variable

25
word = new String();
len = 0; }
public void read(){
Scanner sc=new Scanner(System.in);
System.out.print("Word: ");
word = sc.nextLine();//inputting word
word = word.trim();
if(word.indexOf(' ') > 0)
word = word.substring(0, word.indexOf(' '));//extracting the word
word = word.toLowerCase();//converting it to lowercase
len = word.length();//finding the length of word }
public void shifts(){
String v = new String();
String c = new String();
for(inti = 0; i<len; i++){
charch = word.charAt(i);
switch(ch){//condition for checking vowel
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
v += ch;

26
break;
default:
c += ch;} }
word = c + v;}
public void change(){
String c = new String();
for(inti = 0; i<len; i++){
charch = word.charAt(i);//extracting character
switch(ch){
case 'a'://condition for vowel
case 'e':
case 'i':
case 'o':
case 'u':
c += ch;
break;
default:
c += Character.toUpperCase(ch);}
word = c;}}
public void show(){
System.out.println("Original word: " + word);
this.shifts();
System.out.println("Changed word: " + word); }//printing the word

27
public static void main(String args[]) {
ConsChangeobj=new ConsChange();
obj.read();
obj.show();
}//end of main
}//end of class
Output
Word: vowel
Original word: vowel
Changed word: vwloe

Variable Description Table


Variable Name Variable Type Purpose
word String For storing input
len int For storing length of
string
ch char For storing extracted
character
c char For converting to
uppercase

28
Question 5
Write a program to accept a three letter word and print all the
probable three letter combinations. No Letter should be repeated in
the output

Algorithm:
Step 1: Start
Step 2: Accept a three letter word
Step 3: Find its length
Step 4: Start a nested for loop to print all the possible combinations
of the letters after checking that none of the letter is repeating
End nested for loop.
Step 5: Stop

Answer
// Java program to print all the probable words of a given string
import java.util.*;
public class top {

// Function to print all the permutations of str


static void printPermutn(String str, String ans)
{
// If string is empty
if (str.length() == 0) {
System.out.print(ans + " ");

29
return;
}
for (inti = 0; i<str.length(); i++) {
// ith character of str
charch = str.charAt(i);
// Rest of the string after excluding theith character
String ros = str.substring(0, i) + str.substring(i + 1);
// Recurvise call
printPermutn(ros, ans + ch); }
} // Driver code
public static void main(String[] args)
{ Scannersc=new Scanner(System.in);
String s =sc.nextLine();
printPermutn(s, ""); }}
Output
top
top tpootp opt pto pot

Variable Description Table


Variable Name Variable Type Purpose
s String For storing input
ch char For extracting
character
ros String For storing word

30
Question 6
A class quad contains the following data members and member to find
the roots of a quadratic equation. If ax2+bx+c=0 is the quadratic
equation , then b2-4ac>0,
Roots are real and unequal where,
X1=(-b+ √(b2-4ac))/2a
x2=(-b- √(b2-4ac))/2a
If b2-4ac=0
Roots are real and equal where,
x1=x2=-b/2a If b2-4ac <0, roots
are imaginary.
Specify class quad giving details of the following
1)quad (float,float,float)
2)floatdiscriminant()
3)void root_equal() 4)void
root_real() 5)void root()

Algorithm
Step 1:start
Step 2:initializea,b,c with inputed value
Step 3:find the discriminant of the quation
Step 4:check the condition
Step 5:based on the condition call a specific function void root_equal or
root_real
Step 6: print the root of the equation
Step 7:stop

31
Answer
import java.util.*;//importing package
class quad{
float a,b,c;
quad(float a1,float b1,float c1){
a=a1;
b=b1;
c=c1;
}
float discriminant(){
float result = b * b - 4 * a * c;//finding discriminant of root
return result;
}
void root_real(){//finding root of real root
double x1 = (-b +(Math.sqrt(b*b)-4*a*c))/2*a ;
double x2 = (-b -(Math.sqrt(b*b)-4*a*c))/2*a ;
System.out.println("The roots are " + x1 + " and " + x2);
}
void root_equal(){//finding root of equal root
double x1 = -b / (2.0 * a);
double x2=x1;
System.out.println("The root is " + x1+" and "+x2);
}
void root() {
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE VALUE OF A");//inputting the value
float a=sc.nextFloat();
System.out.println("ENTER THE VALUE OF B");
float b=sc.nextFloat();
System.out.println("ENTER THE VALUE OF C");
float c=sc.nextFloat();
quad ob=new quad(a,b,c);
float d=ob.discriminant();

32
if(d==0)
ob.root_equal();//calling root_equal function
else if(d>0)
ob.root_real();//calling root_real function
else
System.out.println("ROOT ARE IMAGINARY");
}
}

Output
ENTER THE VALUE OF A
1
ENTER THE VALUE OF B
2
ENTER THE VALUE OF C
1
The root is -1.0 and -1.0

Variable Description Table


Variable Name Variable Type Purpose
a,b,c float To store the
coefficients of a, b
and c
d float For storing the
discriminant
x1,x2 double For storing value of
root

33
Question 7
Write a program in Java to store 10 numbers each , in two different
single dimensional Array.Now shift the elements in ’Z’ form such that
n[0] is shifted in m[0] and m[0] in n[1],n[1] in m[1] and son on as shown
below. Display the array elements after shifting them.
Sample Input
m[0] m[1] m[2] m[3] m[4] m[5]
m 45 61 25 34 40 74
n[0] n[1] n[2] n[3] n[4] n[5]
n 62 20 34 44 60 12 -
Sample output
m 62 20 34 44 60 12
n 69 45 61 25 34 40

Algorithm:
Step 1: Start
Step 2: Accept the no. of shells in the array
Step 3: Accept the elements in both the arrays
Step 4: Print the numbers in both the arrays
Step 5: Store the value of m[n-1] in a temporary variable
Step 6: Start a for loop to swap the numbers of both the arrays in ‘z’
Form
End for loop
Step 7: Print both the arrays after swapping
Step 8: Stop

34
Answer
import java.util.*;
class Shift
{
public static void main()
{
Scanner sc=new Scanner (System.in);
inti,n,t;
int m[]=new int[20];
int p[]=new int[20];
System.out.println("Enter the no. of shells in the array:");
n = sc.nextInt();//inputting the array
System.out.println("Enter the numbers in the first array:");
for(i=0;i<n;i++)//inputting the elements of array
{
m[i]=sc.nextInt();
}
System.out.println("Enter the numbers in the second array:");
for(i=0;i<n;i++)//inputting the elements of second array
{
p[i]=sc.nextInt();
}
System.out.println("The numbers present in the first array:");
for(i=0;i<n;i++)
{
System.out.print(m[i]+" ");
}
System.out.println();
System.out.println("The numbers present in the second
array:");
for(i=0;i<n;i++)
{
System.out.print(p[i]+" ");
}
System.out.println();
t=m[n-1];
35
for(i=(n-1);i>=1;i--)//shifting elements in z form
{
m[i]=p[i];
p[i]=m[i-1];
}
m[0]=p[0];
p[0]=t;
System.out.println("The numbers after shifting
are:");//printing the elements
System.out.println("The elements of the first array are:");
for(i=0;i<n;i++)
{
System.out.print(m[i]+" ");
}
System.out.println();
System.out.println("The elements of the second array are:");
for(i=0;i<n;i++)
{
System.out.print(p[i]+" ");
}
System.out.println();
}//end of main
}//end of class
Output

62 20 34 44 60 12
69 45 61 25 34 40

Variable Description Table


Variable Name Variable Type Purpose
i int Loop variable
m[]n[] int Array for storing
elements
t int For storing elements
36
Question 8
Write a program in Java to accept a word and pass it to a method .
Arrange all the letters of the in word in its alphabetical order and
display the result.
Sample Input : understanding
Sample output : addeginnmstu

Algorithm:
Step 1: Start
Step 2: Accept a word and find its length
Step 3: Start a for loop from i=0 to i<l to place the vowels present to
the beginning
End for loop
Step 4: Print the new word
Step 5: Stop

37
Answer
importjava.util.*;
class word
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE WORD");
String s=sc.nextLine();
int l=s.length();char ch[]=new char[l];
s=s.toUpperCase();char s1=' ';String word="";char small=' ';int
pos=0;char temp=' ';
for(inti=0;i<l;i++)
{
ch[i]=s.charAt(i);
}
for (inti = 0; i< l-1; i++)
{
// Find the minimum element in unsorted array
intmin_idx = i;
for (int j = i+1; j < l; j++)
if (ch[j] <ch[min_idx])
min_idx = j;

38
// Swap the found minimum element with the first
// element
temp = ch[min_idx];
ch[min_idx] = ch[i];
ch[i] = temp;
}
for(inti=0;i<l;i++)
{
word=word+ch[i];
}
System.out.println(word);
}
}
Output
ENTER THE WORD
understanding
ADDEGINNNRSTU

Variable Description Table


Variable Name Variable Type Purpose
s String For storing input
l int For storing letter
temp char For storing character
Min_index int For storing index
i int Loop variable

39
Question 9
Write a program in Java to input two numbers. Use a recursive function
that returns HCF of both the numbers.

Algorithm:
Step 1: Start
Step 2: Create a parameterized function hcf to find the HCF of the
two numbers using the recursive function
Step 3: Create a main class
Step 4: Accept two numbers to find the HCF
Step 5: Call the parameterized function by making an object of the
class
Step 6: Print the HCF
Step 7: Stop

Answer
importjava.util.*;//importing package
class HCF
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE TWO NUMBERS");//inputting the
number
int a=sc.nextInt();

40
int b=sc.nextInt();
System.out.println("THE HCF IS "+hcf(a,b));
}
public static inthcf(int n1,int n2)
{
if (n2 != 0)
returnhcf(n2, n1 % n2);//finding hcf
else
return n1;
}//end of main
}//end of class
Output
ENTER THE TWO NUMBERS
120
6
THE HCF IS 6

Variable Description Table


Variable Name Variable Type Purpose
a,b int For storing input
n1,n2 int For finding hcf

41
Question 10
Write a program to convert a decimal number to its binary form using
recursion.

Algorithm:
Step 1: Start
Step 2: Create a parameterized function that will return 0 if the
decimal number is 0, else it will convert it to binary number
Step 3: Create a main class
Step 4: Accept the decimal number
Step 5: Call the function
Step 6: Print the binary number
Step 7: Stop

Answer
// Java program for decimal to binary
// conversion using recursion
importjava.util.*;
import java.io.*;
class binary
{
// Decimal to binary conversion
// using recursion
staticint find(intdecimal_number)
{

42
if (decimal_number == 0)
return 0;
else
return (decimal_number % 2 + 10 * find(decimal_number / 2));
}
// Driver Code
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
intdecimal_number =sc.nextInt();
System.out.println(find(decimal_number)); }
} Output
ENTER THE NUMBER
5
101

Variable Description Table


Variable Name Variable Type Purpose
Decimal_number int For storing input and
converting decimal to
binary

43
Question 11
To Display Spiral Matrix.

ALGORITHM
STEP 1 - START STEP 2 - INPUT a[][]

STEP 3 - IF p!=(int)Math.pow(l,2) GOTO STEP 4 STEP 4 - IF


co!=0 GOTO STEP 5

STEP 5 - re=1

STEP 6 - IF ri=1;ri<=k1-re;ri++ GOTO STEP 7 STEP 7 -


p++,c++

STEP 8 - IF c==l GOTO STEP 9 STEP 9 - BREAK

STEP 10 - a[r][c]=p

STEP 11 - IF c==l GOTO STEP 12 STEP 12 - BREAK

STEP 13 - IF dw=1 GOTO STEP 14 STEP 14 -


p++,r++,a[r][c]=p

STEP 15 - IF le=1 GOTO STEP 16 STEP 16 - p++,c--,a[r][c]=p

STEP 17 - IF up=1 GOTO STEP 18 STEP 18 - p++,r--,a[r][c]=p

STEP 19 - k1=k1+2, k2=k2+2 & co++

STEP 20 - up++ & IF up<=k2-1 GOTO STEP 18 STEP 21 - le++


& IF le<=k2-1 GOTO STEP 16 STEP 22 - dw++ & IF dw<=k1-
1 GOTO STEP 14 STEP 23 - IF y=0 GOTO STEP 24
44
STEP 24 - IF yy=0 GOTO STEP 25 STEP 25 - PRINT
"\t"+a[y][yy]) & ()

STEP 26 - yy++ & IF yy<l GOTO STEP 25 STEP 27 - y++ & IF


y<l GOTO STEP 24 STEP 28 – END

45
Solution
import java.io.*; class SpiralMatrix

{public static void main(String[] args) throws IOException


//main function

{int a[][],r,c,k1=2,k2=3,p=0,co=0,re=0;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in)); System.out.println("enter
the dimension of matrix A x A =");

int l = Integer.parseInt(br.readLine()); //accepting


dimension of square spiral matrix a=new int[l][l];

r=l/2;c=r-1; if(l%2==0)

{System.out.println("wrong entry for spiral path");


System.exit(0);

/*Calculating and displaying spiral matrix*/


while(p!=(int)Math.pow(l,2))

{if(co!=0) re=1;

for(int ri=1;ri<=k1-re;ri++)

{p++;c++;if(c==l)break;a[r][c]=p;} if(c==l)break;

for(int dw=1;dw<=k1-1;dw++)
46
{p++;r++;a[r][c]=p;} for(int le=1;le<=k2-1;le++)

{p++;c--;a[r][c]=p;}

for(int up=1;up<=k2-1;up++)

{p++;r--;a[r][c]=p;} k1=k1+2; k2=k2+2;

co++;

for(int y=0;y<l;y++) //Displaying matrix

{for(int yy=0;yy<l;yy++) System.out.print("\t"+a[y][yy]);


System.out.println(); System.out.println();

}}}

47
Variable Description Table
No. Name Type Method Description
1 br BufferedReader main() BufferedReader object
2 a int[][] main() spiral matrix
3 r int main() l/2
4 c int main() r-1
5 k1 int main() stores 2
6 k2 int main() stores 3
7 p int main() loop gate
8 co int main() coloumn index
9 re int main() row index
10 l int main() dimensions of thr matrix
11 ri int main() right side matrix loop variable
12 le int main() left side matrix loop variable
13 dw int main() down side matrix loop variable
14 up int main() up side matrix loop variable
15 y int main() loop variable to print matrix
16 yy int main() loop variable to print matrix

Output

48
Question 12
To Display Magic Square

ALGORITHM
STEP 1 - START

STEP 2 - arr[][]=new int[n][n],c=n/2-1,r=1,num

STEP 3 - IF num=1;num<=n*n;num++ GOTO STEP 4 STEP 4


- r--,c++

STEP 5 - IF r==-1 GOTO STEP 6 STEP 6 - r=n-1

STEP 7 - IF c>n-1 GOTO STEP 8 STEP 8 - c=0

STEP 9 - IF arr[r][c]!=0 GOTO STEP 10 STEP 10 - r=r+2 & c--

STEP 11 - num++ & IF num<=n*n GOTO STEP 4 STEP 12 -


arr[r][c]=num

STEP 13 - IF r==0&&c==0 GOTO STEP 14

STEP 14 - r=n-1, c=1 & arr[r][c]=++num STEP 15 - IF c==n-


1&&r==0 GOTO STEP 16

STEP 16 - arr[++r][c]=++num STEP 17 - PRINT ()

STEP 18 - IFr=0 GOTO STEP 19 STEP 19 - IF c=0 GOT STEP


20 STEP 20 - PRINT arr[r][c]+" " & ()

STEP 21 - c++ & IF c<n GOTO STEP 20 STEP 21 - r++ & r<n
49
GOTO STEP 19 STEP 22 – END

50
Solution
/*A Magic Square is a square whose sum of diagonal
elements, row elements and coloumn

elements is the same*/ import java.io.*;

class MagicSquare

{public static void main(String args[])throws Exception


//main function

{BufferedReader br = new BufferedReader(new


InputStreamReader(System.in)); System.out.println("enter
the dimension of magical square=");

int n = Integer.parseInt(br.readLine()); //accepting


dimensions int arr[][]=new int[n][n],c=n/2-1,r=1,num;

for(num=1;num<=n*n;num++) //loop for finding magic


square elements

{r--; c++;

if(r==-1) r=n-1; if(c>n-1) c=0;

if(arr[r][c]!=0)

{r=r+2; c--;

arr[r][c]=num; if(r==0&&c==0)
51
{r=n-1; c=1;

arr[r][c]=++num;

if(c==n-1&&r==0) arr[++r][c]=++num;

System.out.println();

for(r=0;r<n;r++) //loop displaying magic square

{for(c=0;c<n;c++) System.out.print(arr[r][c]+" ");


System.out.println();

}}}

52
Variable Description Table
No. Name Type Method Description
1 br BufferedReader main() BufferedReader object
2 n int main() input dimensions
3 arr int[][] main() magic square matrix
4 num int main() loop variable for magic square
5 r int main() row
6 c int main() coloumn

Output

53
Question 13
Write a program to input two decimal numbers m.n. Convert these
decimal numbers into equivalent binary numbers .Add these binary
numbers and print their sum in binary form Sample Input-
m:14,n:10 Sample Output -binary of 14=1110 ,binary of 10=1010
,sum=11000

Algorithm:
Step 1:Start
Step 2:Taketwo input from the user
Step 3:Start a nested while loop
Step 4:Dividing each digit by 2
Step 5: adding the two binary number
Step 6:print the sum
Step 7:stop

Answer
import java.util.*;//importing package
import java.io.*;
class two
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE TWO DECIMAL NUMBERS");
int n=sc.nextInt();//taking input from the user
54
int m=sc.nextInt();
int r=0;String s1="",s2="";int r1=0;
while(n>0)
{
r=n%2;
n=n/2;
s1=r+s1;
}
while(m>0)
{
r1=m%2;
m=m/2;
s2=r1+s2;
}
System.out.println(addBinary(s1,s2));
}
static String addBinary(String a, String b)
{
// Initialize result
String result = "";
// Initialize digit sum
int s = 0;
// Traverse both strings starting

55
// from last characters
inti = a.length() - 1, j = b.length() - 1;
while (i>= 0 || j >= 0 || s == 1)
{
// Compute sum of last
// digits and carry
s += ((i>= 0)? a.charAt(i) - '0': 0);
s += ((j >= 0)? b.charAt(j) - '0': 0);
// If current digit sum is
// 1 or 3, add 1 to result
result = (char)(s % 2 + '0') + result;
// Compute carry
s /= 2;
// Move to next digits
i--; j--;
}

return result; }
}

56
Output
ENTER THE TWO DECIMAL NUMBERS
14
10
11000

Variable Description Table


Variable Name Variable Type Purpose
m,n int For storing input
s2,s1 String For storing binary
form
r,r1 int For storing remainder

57
Question 14
A magic number is a number whose eventual sum of digits is equal to 1
Write a program to input a number and check whether it is a magic
number or not. Input:4627=4+6+2+7
=19
=1+9=10
=1+0=1
Sample
Output:4627 is a magic number.

Algorithm:
Step 1: Start
Step 2: Accept the number to be checked
Step 3: Store the number in ‘n’ as well as in ‘num’
Step 4: Create a while loop , if the condition is met then each digits
of the number gets added up eventually getting a single digit.
End while.
Step 5: Create a if-else loop where,If the sum of the digits is equal to
1 , then if part gets executed. If it is not equal to 1 then the
else part gets executed.
End if-else
Step 6: Stop
Answer
importjava.util.Scanner;//importing package
public class MagicNumber{
public static void main(String[] args) {
58
int n, r = 1, num, sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number=");//taking input
n = sc.nextInt();
num = n;//making copy of n
while (num> 9) {
while (num> 0) {
r = num % 10;
sum = sum + r;//getting the sum of the no.
num = num / 10;
}
num = sum;
sum = 0;
}
if (num == 1)
{
System.out.println("Magic Number");
}
else
{
System.out.println("Not Magic Number");
}
}//end of main

59
}//end of class
Output
Enter number=4627
Magic Number

Variable Description Table


Variable Name Variable Type Purpose
n int For storing input
num int For storing copy of n
r int For storing remainder
sum int For storing sum

60
Question 15
Write a program in JAVA to input a sentence in Uppercase . Create a
new sentence by replacing each vowel with the next vowel (i.e. A with
E,…V with A).Other characters must raming same . Display the new
sentences accordingly Sample Input : WE CELEBRATE REPUBLIC DAY.
Sample Output:WI CILIBRETI RIPABLOC DEY.

Algorithm:
Step 1: Start
Step 2: Accept a sentence in upper case
Step 3: Find its length and store in l
Step 4: Start a for loop from i=0 to i<l to extract each letter
And if the letter is a vowel then change the letter to the
Next vowel and store it in new variable st
Step 5: End for loop
Step 6: Print the new sentence
Step 7: Stop

ANSWER
import java.util.*;//importing package
class sent{
public static void main(){
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE STRING IN UPPERCASE");//taking input
from user
String s=sc.nextLine();String s1="";

61
for(inti=0;i<s.length();i++){
char ch=s.charAt(i);
switch(ch)
{//replacing the vowel with the next vowel
case 'A':
s1=s1+"E";break;
case 'E':
s1=s1+"I";break;
case 'I':
s1=s1+"O";break;
case 'O':
s1=s1+'U';break;
case 'U':
s1=s1+'A';break;
default:
s1=s1+ch;
}
}

System.out.println("THE MODIFIED STRING IS "+s1);


}//end of main
62
}//end of class

63
Output
ENTER THE STRING IN UPPERCASE
WE CELEBRATE REPUBLIC DAY
THE MODIFIED STRING IS WI CILIBRETI RIPABLOC DEY

Variable Description Table


Variable Name Variable Type Purpose
s String For storing input
s1 String For storing modified
string
ch char For extracting
character
i int Loop variable

64
QUESTION 16
Write a program to store different numbers in 5*5 matrix. Display the
numbers which are above the right diagonal.
Sample Input:
13 22 14 23 21
16 14 15 34 10
71 -11 10 40 12
41 13 11 56 19
22 71 45 12 34
Sample Output:
13 22 14 23
16 14 15
71 11
41

Algorithm:
Step 1: Start
Step 2: Accept the matrix size
Step 3: Run a if loop to check whether the size of the matrix is out of
bounds or not
Step 4: Run a nested for loop to accept the elements in the matrix
End nested for loop.
Step 5: Run another nested for loop to print the matrix
End nested for loop.
Step 6: Run another nested for loop to get the elements above the

65
right diagonal.
End nested for loop.
Step 7: Run a if loop with the condition (i+j<m-1)
to get the elements above the right diagonal
End if
Step 8: Print the elements
Step 9: Stop

Answer
import java.util.*;//importing package
class doubledimensional
{
public static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5];
System.out.println("ENTER THE NUMBERS");//taking input from user
for(inti=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}

66
}
for(int i=0;i<5;i++)//printing the double dimensional array
{
for(int j=0;j<5;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
System.out.println("Elements above right diagonal:");
for(inti = 0; i< 5; i++){
for(int j = 0; j < 5; j++){
if(i + j < 5 - 1)//condition for printing the elements above right diagonal
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}
}

67
Output
ENTER THE NUMBERS
13 22 14 23 21
16 14 15 34 10
71 -11 10 40 12
41 13 11 56 19
22 71 45 12 34

13 22 14 23
16 14 15
71 11
41
Variable Description Table
Variable Name Variable Type Purpose
a[][] int For storing elements
of array
i,j int Loop variable

68
Question 17
Write a program in Java to create 4X4 matrix in double dimensional
array. Display the sum of boundary element. Also , print the matrix and
its boundary elements(only) separately.

Algorithm:
Step 1: Start
Step 2: Accept the elements in the array
Step 3: Print the elements in the array
Step 4: Run a nested for loop to get the sum of all the elements in
the array and store in s1.
End nested for loop
Step 5: Run a nested for loop to get the sum of the non boundary
elements in the array and store in s2.
End nested for loop
Step 6: Subtract s2 from s1 to get the sum of only the boundary
elements
Step 7: Print the difference between the two sums
Step 8: Stop

Answer
import java.util.*;//importing the package
class matrix{
public static void main() {
Scanner sc=new Scanner(System.in);

69
int a[][]=new int[4][4];int sum=0;
System.out.println("ENTER THE MATRIX");//taking input from user
for(inti=0;i<4;i++) {
for(int j=0;j<4;j++) {
a[i][j]=sc.nextInt();
}
}
for(inti=0;i<4;i++){
for(int j=0;j<4;j++){//printing the double dimensional array
System.out.print(a[i][j]+" ");
}System.out.println();
}
for(int i = 0; i< 4; i++) {
for(int j = 0; j < 4; j++){
if (i == 0 || j == 0 || i == 4-1||j==4-1)
{
sum = sum + a[i][j];//finding the sum of boundary elements
}
}
System.out.println();
}
System.out.println("Sum of boundary is " + sum);
}

70
}
Output
ENTER THE MATRIX
1234567891234567
SUM OF BOUNDARY ELEMENTS :57

Variable Description Table


Variable Name Variable Type Purpose
a[][] int For storing elements
of array
i,j int Loop variable
sum int For finding sum of
boundary elements

71
Question 18
Write a program in Java to create 4X4 matrix and print only the left and
the right diagonal of the matrix.

Algorithm:
Step 1: Start
Step 2: Accept a 4*4 matrix from the user
Step 3: Print the matrix
Step 4: Initialize int k = 3
Step 5: Start a for loop from i=0 to i<4
Print num[i] [i] to print the left diagonal and
num[i] [k] to print the right diagonal
Decrease k by 1
End for loop
Step 6 : Stop

Answer
import java.util.*;
class diagonal{
public static void main(){
Scanner sc=new Scanner(System.in);
int a[][]=new int[4][4];
System.out.println("ENTER THE ELEMENTS");
for(inti=0;i<4;i++){
for(int j=0;j<4;j++){

72
a[i][j]=sc.nextInt();
}
}
for (inti = 0; i< 4; i++) {
for (int j = 0; j < 4; j++) {
// Condition for principal or left diagonal
if (i == j) {
System.out.print(a[i][j] + ", ");
}
}
}
System.out.println("");
// Function to print the Secondary or right Diagonal
for(inti = 0; i< 4; i++)
{
for (int j = 0; j < 4; j++) {
// Condition for secondary diagonal
if ((i + j) == (4 - 1)) {
System.out.print(a[i][j] + ", "); }}}}
}

73
Output
ENTER THE ELEMENTS
1234
5678
9123
4567
1, 6, 2, 7
4, 7, 1, 4

Variable Description Table


Variable Name Variable Type Purpose
a[][] Int For storing elements
of array
i,j int Loop variable

74
Question 19
Write a program to store ten numbers each in two different Single
Dimensional Arrays. Merge the numbers of both the arrays in a Single
Dimensional Array. After merging, sort the numbers in ascending order.
Display the sorted array.

Algorithm:
Step 1: Start
Step 2: Accept two single dimensional array both of size 10
Step 3: Merge the elements of both the array in a third array ar3[]
Step 4: Print the merged array ar3[] in an unsorted way
Step 5: Sort the merged array using selection sort. In every iteration
of selection sort, the minimum element (considering ascending
order) from the unsorted subarray is picked and moved to the
sorted subarray.
Step 6: Print the sorted array
Step 7: Stop

Answer
importjava.util.*;//importing the package
class array
{
public static void main() {
Scanner sc=new Scanner(System.in);
int a[]=new int[10];

75
int b[]=new int[10];
int i1=0;
System.out.println("ENTER THE NUMBERS");
for(inti=0;i<10;i++)//taking input fromuser
{
a[i]=sc.nextInt();
}
for(inti=0;i<10;i++)
{
b[i]=sc.nextInt();
}
int c[]=new int[20];
for(i1=0;i1<10;i1++)//merging the two arrays
{
c[i1]=a[i1];
}
for(int j=0;j<b.length;j++)
{
c[i1++]=b[j];
}for(inti=0;i<20;i++)
{
System.out.println(c[i]);
}

76
intpos=0;int temp=0;
for(inti=0;i<20;i++)
{
pos=i;//doing selection sort
for(int j=i+1;j<20;j++)
{
if(c[j]<c[pos])
pos=j;
}
temp=c[pos];//swapping the elements
c[pos]=c[i];
c[i]=temp;
}
System.out.println("THE SORTED ARRAY IS ");
for(inti=0;i<20;i++)//printing the elements of array
{
System.out.println(c[i]);} }
}

77
Output
1234567 8912345678912
THE SORTED ARRAY IS 1 1 1 2 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9

Variable Description Table


Variable Name Variable Type Purpose
a[],b[] int For storing elements
of array
i,j,i1 int Loop variable
pos int For storing position
temp int For storing temporary
value

78
Question 20
Write a program by using method overloading technique to compute
the area of:
a) a square
b) a rectangle
c) a circle using formula 22/7*r*r

Display the menu and area as per the user’s choice.


Algorithm:
Step 1: Start
Step 2: Create three methods of void area with different parameters
Step 3: In the main class , create an object of the class
Step 4: Accept a choice from the user
Step 5: If the user enters 1, then accept sides of the square and call
the first method to print the area . If the user enters 2, then
accept the length and breadth of the rectangle and call the
second method to the its area. If the user enters 3, accept the
radius of the circle and call the third method to print its area. If
the user enters any other choice then , default part gets
executed.
Step 6: Stop

79
Answer
Importjava.util.*;//importing package
class overload{
public static void main() {
Scanner sc=new Scanner(System.in);
System.out.println("ENTER 1 FOR AREA OF CIRCLE 2 FOR AREA OF
SQUARE AND 3 FOR AREA OF RECTANGLE");
int n=sc.nextInt();
switch(n){
case 1://taking input from the user
System.out.println("ENTER THE RADIUS");
double r=sc.nextInt();
System.out.println("THE AREA IS "+area(r));
break;
case 2:
System.out.println("ENTER THE SIDE");
int s=sc.nextInt();
System.out.println("THE AREA IS "+area(s));
break;
case 3:
System.out.println("ENTER THE LENGTH");
int l=sc.nextInt();
System.out.println("ENTER THE BREATH");

80
int b=sc.nextInt();
System.out.println("THE AREA IS "+area(l,b));
break;
default:
System.out.println("WRONG CHOICE");
}
}
static double area(double r) {
double a=(22/7)*r*r;//finding area of the circle
return a;
}
staticintarea(int s) {
int a=s*s;
return a;
}
staticint area(intl,int b){
int a=l*b;//finding the area of rectangle
return a;
}
}

81
Output
ENTER 1 FOR AREA OF CIRCLE 2 FOR AREA OF SQUARE AND 3 FOR
AREA OF RECTANGLE
1
ENTER THE RADIUS
5
THE AREA IS 75.0

Variable Description Table


Variable Name Variable Type Purpose
n int For storing choice of
user
R int For storing radius
l,b int For storing length and
breath
S int For storing side
a double.int For storing area

82
Question 21
Describe a class Security having the following description:
DATA MEMBERS/ INSTANCE VARIABLES
String n: to store name
double r: to store the rate
int h: to store the number of hours worked
double w: to store wage
Member functions/methods:
security () : A parameterized constructor to initialize the
data members viz. name, rate and number of
hours.
voidcalwage() : Calculate the wage of an employee.
void display() : Output details of an employee.
The security is not allowed to work for more than 70 hours per week.
Write a program to compute according to the given condition and
display the output as per the given format.
Number of hours Rate
Up to 40 hours Rs. r per hour
For next 20 hours Rs. 1.5r per hour
For next 20 hours Rs. 2r per hour

OUTPUT:
NAME HOURS WAGES
XXXX XXXX XXXXX

83
Algorithm:
Step 1: Start
Step 2: Create a parameterized constructor to initialize name , rate
and number of hours
Step 3: A function void calwage() is executed to calculate the wage of
the employee
Step 4: A function void display() is executed to diplay the name of the
employee , number of hours worked by him/her and the
wage of the employee
Step 5: A main class is executed to accept the name , number of
hours worked and the rate of the employee
Step 6: Call the above methods by creating an object of the class
Step 7: Stop

Answer
importjava.util.*;//importing package
class security
{
String n;
int h;
double r;
double w;
security(String n1,int h1,int r1)//initializing the Global variable
{

84
n=n1;
h=h1;
r=r1;
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NAME");
String name=sc.nextLine();
System.out.println("ENTER THE NUMBER OF HOURS THE WAGE IS TO
BE PAID");
inthr=sc.nextInt();//inputting from the user
System.out.println("ENTER THE RATE");
int r=sc.nextInt();
securityob=new security(name,hr,r);
ob.calwage();
ob.display();
}
voidcalwage()
{
if(h<=40)
w=r*h;
else if(h>40)

85
w=r*40+1.5*r+h-40;
else
w=r*40+1.5*r*20+2*r*h-40-20;
}

void display()
{
System.out.println("NAME \t HOURS \t WAGES");
System.out.println(n+"\t"+h+"\t"+w);
}//end of main
}//end of class

86
Output
ENTER THE NAME
test
ENTER THE NUMBER OF HOURS THE WAGE IS TO BE PAID
13
ENTER THE RATE
5
NAME HOURS WAGES
test 13 65.0

Variable Description Table


Variable Name Variable Type Purpose
n String For storing name
h int To store the number
of hours worked
w double To store the number
of hours worked
name String To store name
r int For storing rate
hr int To store the number
of hours worked

87
Question 22
An Emirp number is a number which is prime backwards and forwards .
Write a program to check whether a given number is Emirp number or
not.

Algorithm:
Step 1: Start
Step 2: Accept a number to be checked
Step 3: Store the number in another variable
Step 4: Starting a while loop, which will initialize only if the entered
number is more than 0, to reverse the entered number and
store it in t
End while
Step 5: Starting a for loop from (i=1 to i<=m) to find the multiple of m
If a multiple is present then the value of variable c will
increase by 1
End for loop
Step 6: Starting a for loop from (i=1 to i<=t) to find the multiple of t
If a multiple is present then the value of variable ct will
increase by 1
End for loop
Step 7: Starting an if else loop that will print the number is an emirp
number if the value of both c and ct are 2, else it will print
that the number is not an emirp number

88
End if-else loop
Step 8: Stop

Answer
importjava.util.*;//importing package
classemirp
{
public static void main() {
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NUMBER");//inputting the number
int n=sc.nextInt();
int n1=n;
int n2=n;int rev=0;int f=0;
while(n!=0)
{
int r=n%10;//extracting the digits
rev=rev*10+r;//reversing the number
n=n/10;
}for(inti=2;i<n1;i++)
{
if(n1%i==0)
f++;
if(rev%i==0)
f++;

89
}
if(f==0)
System.out.println("IT IS A EMIRP NUMBER");
else
System.out.println("IT IS NOT A EMIRP NUMBER"); }
}
Output
ENTER THE NUMBER
13
IT IS A EMIRP NUMBER

Variable Description Table


Variable Name Variable Type Purpose
n int For storing input
n1,n2 int For storing copy of n
rev int For storing reverse of
the number
i int Loop variable
f int For storing the
number of factors

90
Question 23
A class Employee contains employee details and another class Salary
calculates the employee’s net salary.
The details of the two classes are given below:
Class name : Employee Data members
empNo : stores the employee number.
empName : stores the employee name
empDesig : stores the employee’s designation.
Member functions:
Employee() : default constructor.
Employee(…) : parameterized constructor to assign values to data members.
void display() : display the employee details.
Class name : Salary
Data members basic : float variable to store the basic pay.
Member functions Salary(…) : parameterized constructor to assign values to
data 7 members.
void calculate() : calculates the employee’s net salary according to the
following rules:
DA = 10% of basic
HRA = 15% of basic Salary = basic + DA +H RA
PF= 8 % of Salary Net Salary = Salary –PF
Display the employee details and the Net salary. Specify the class Employee
giving details of the constructors and member function void display(). Using
the concept of inheritance specify the class Salary giving details of the
constructor and the member function void calculate().

91
Algorithm:

92
Answer:
import java.util.*;
class Employee
{
int empno;String empname,empdesig;
Employee()
{
empno=0;
empname=null;
empdesig=null;
}
Employee(int a,String b,String c)
{
empno=a;
empname=b;
empdesig=c;
}
void display()
{
System.out.println("Employee name:"+empname);
System.out.println("Employee number:"+empno);
System.out.println("Employee designation:"+empdesig);
}
}
class Salary extends Employee
{
float basic;
Salary(float b,int n,String name,String d)
{
super(n,name,d);
basic=b;
}
void calculate()

93
{

double da=0.1*basic, hra=0.15*basic,gross=basic+da+hra,


pf=0.08*gross,netpay=gross-pf;
System.out.println("\nEmployee Details");
System.out.println(" --------------- ");
super.display();
System.out.println("\nPayment Details");
System.out.println(" --------------- ");
System.out.println("Basic="+basic+"\nDA="+da+"\nHRA="+hra+"\nGross
Pay="+gross+"\nNet Pay="+netpay);
}
public static void main(String arg[])
{
Scanner ob=new Scanner(System.in);
System.out.print("Enter employee name:");
String name=ob.nextLine ();
System.out.print("Enter employee number:");
int n=ob.nextInt();
System.out.print("Enter employee designation:");
String d=ob.next();
System.out.print("Enter basic pay:");
float b=ob.nextFloat ();
Salary call=new Salary(b,n,name,d);
call.calculate();
}
}

94
Output:

95
Question 24
A superclass Perimeter has been defined to calculate the perimeter of a
parallelogram. Define a subclass Area to compute the area of the
parallelogram by using the required data members of the superclass. The
details are given below:
Class name: Perimeter
Data members/instance variables:
a: to store the length in decimal
b: to store the breadth in decimal
Member functions:
Perimeter (…): parameterized constructor to assign values to data members
double Calculate(): calculate and return the perimeter of a parallelogram is 2*
(length + breadth)
void show(): to display the data members along with the perimeter of the
parallelogram
Class name: Area
Data members/instance variables:
h: to store the height in decimal
area: to store the area of the parallelogram
Member functions:
Area(…): parameterized constructor to assign values to data members of both
the classes
void doarea(): compute the area as (breadth * height)
void show(): display the data members of both classes along with the area and
perimeter of the parallelogram.
Specify the class Perimeter giving details of the constructor (…), double
Calculate and void show (). Using the concept of inheritance, specify the class
Area giving details of the constructor (…), void doarea () and void show ().

96
Algorithm:

97
Answer:
//Code for base class
class Perimeter
{
double a,b;
Perimeter(double aa, double bb)
{
a=aa;
b=bb;
}
double Calculate()
{
double z;
z=2*(a+b);
return (z);
}
void show()
{
System.out.print("\n Length = " + a);
System.out.print("\n Breadth = " + b);
System.out.print("\n Perimeter =" + Calculate());
} // End of base class
// code for derived class
class Area extends Perimeter
{
double h;
double area;
Area(double aa, double bb, double cc)
{
super(aa, bb);
h=cc;
98
}
void doarea()
{
area=b*h;
}
void show()
{ super.show();
System.out.print("\n Height = " + h);
System.out.print("\n Area = " + area);
}

Output:

99
Question 25:
To Decode the Entered String

ALGORITHM:

STEP 1 - START
STEP 2 - INPUT name, n
STEP 3 - l=name.length()
STEP 4 - PRINT original string is "+name
STEP 5 - IF i=0 THEN GOTO STEP 6
STEP 6 - char c1=name.charAt(i)
STEP 7 - c=(int)c1
STEP 8 - IF n>0 THEN GOTO STEP 9 THERWISE GOTO
STEP 12
STEP 9 - IF (c+n)<=90 THEN GOTO STEP 10
OTHERWISE GOTO STEP 11
STEP 10 - PRINT (char)(c+n)
STEP 11 - c=c+n;c=c%10,c=65+(c-1) & PRINT
(char)(c)
STEP 12 - ELSE IF n<0 THEN GOTO STEP 13
OTHERWISE GOTO STEP 19
STEP 13 - n1=Math.abs(n)
STEP 14 - IF (c-n1) >=65 THEN GOTO STEP 15
OTHERWISE GOTO STEP 16
STEP 15 - DISPLAY (char) (c-n1)
STEP 16 - IF c>65 THEN GOTO STEP 17 OTHERWISE
GOTO STEP 18
STEP 17 - c=c-65,
STEP 18 - c=n1 & PRINT (char)(90-(c-1))
STEP 19 - ELSE IF n==0

100
STEP 20 - DISPLAY "no change "+name
STEP 21 - END

SOLUTION:

import java.io.*;
class Decode
{public void compute()throws IOException
//compute() function
{BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(“Enter name:”);
String name=br.readLine();
System.out.println(“Enter number:”);
int n=Integer.parseInt(br.readLine());
int j,i,l,c=0,y,n1;
l=name.length();
System.out.println("original string is "+name);
for(i=0;i<l;i++)
{char c1=name.charAt(i);
try //trying for NumberFormatException
{c=(int)c1 ;
}
catch(NumberFormatException e)
{}
if(n>0)
{if((c+n)<=90)
/Decoding String/
System.out.print((char)(c+n));
else {c=c+n;
c=c%10;
c=65+(c-1);
System.out.print((char)(c));
}}
101
else if(n<0)
{n1=Math.abs(n);
if((c-n1) >=65)
System.out.print((char) (c-n1));
else {if(c>65)
c=c-65;
else c=n1;
System.out.print((char)(90-(c-1)));
}}
else if (n==0)
{System.out.println("no change "+name);
break;
}}}}

Variable Description Table:


No. Name Type Method Description
1 br BufferedReader compute() BufferedReader object
2 name String compute() input string
3 n int compute() decode number
4 j int compute() loop variable
5 i int compute() loop variable
6 l int compute() length of string
7 c int compute() ASCII of c1
8 y int compute()
9 n1 int compute()
10 c1 char compute() character at index i
11 e NumberFormatException compute() NumberFOrmatException object

102
Output

103
Question 26:

Write an application-based program to show the working of an Automatic


Teller Machine.

Algorithm:

104
Answer:
import java.util.Scanner;

//create ATMExample class to implement the ATM functionality


public class ATMExample
{
//main method starts
public static void main(String args[] )
{
//declare and initialize balance, withdraw, and deposit
int balance = 100000, withdraw, deposit;

//create scanner class object to get choice of user


Scanner sc = new Scanner(System.in);

while(true)
{
System.out.println("Automated Teller Machine");
System.out.println("Choose 1 for Withdraw");
System.out.println("Choose 2 for Deposit");
System.out.println("Choose 3 for Check Balance");
System.out.println("Choose 4 for EXIT");
System.out.print("Choose the operation you want to perform:");

//get choice from user


int choice = sc.nextInt();
switch(choice)
{

105
case 1:
System.out.print("Enter money to be withdrawn:");

//get the withdrawl money from user


withdraw = sc.nextInt();

//check whether the balance is greater than or equal to the withdrawal


amount
if(balance >= withdraw)
{
//remove the withdrawl amount from the total balance
balance = balance - withdraw;
System.out.println("Please collect your money");
}
else
{
//show custom error message
System.out.println("Insufficient Balance");
}
System.out.println("");
break;

case 2:

System.out.print("Enter money to be deposited:");

//get deposite amount from te user


deposit = sc.nextInt();

//add the deposit amount to the total balanace


balance = balance + deposit;
System.out.println("Your Money has been successfully depsited");
System.out.println("");
break;

106
case 3:
//displaying the total balance of the user
System.out.println("Balance : "+balance);
System.out.println("");
break;

case 4:
//exit from the menu
System.exit(0);
}
}
}
}

Output:

107
Variable Description Table:

Variable Name Variable Type Purpose


balance int To store the balance of account
holder
withdraw, deposit int To store the input of withdrawn
money or deposited money
Choice int To store the choice account
holder
withdraw, deposit int To store the input of withdrawn
money or deposited money

108
Question 27:
Write an application based program to show the basic working of a calculator.

Algorithm:

Step 1:Start
Step 2:Take input from the user for the choice operation
Step 3:take two input from user
Step 4:start switch statement
Step 5:based on choice case +, case -, case *,case /or default will be executed
Step 6: case + , to add two number ,case - , to subtract two numbers, case * to
multiply two numbers case / to divide two numbers
Step 7: Print the result after operation.
Step 8:stop

109
Answer:
import java.util.Scanner;

class Calculator {
public static void main(String[] args) {

char operator;
Double number1, number2, result;

// create an object of Scanner class


Scanner input = new Scanner(System.in);

// ask users to enter operator


System.out.println("Choose an operator: +, -, *, or /");
operator = input.next().charAt(0);

// ask users to enter numbers


System.out.println("Enter first number");
number1 = input.nextDouble();

System.out.println("Enter second number");


number2 = input.nextDouble();

switch (operator) {

// performs addition between numbers


case '+':

110
result = number1 + number2;
System.out.println(number1 + " + " + number2 + " = " + result);
break;

// performs subtraction between numbers


case '-':
result = number1 - number2;
System.out.println(number1 + " - " + number2 + " = " + result);
break;

// performs multiplication between numbers


case '*':
result = number1 * number2;
System.out.println(number1 + " * " + number2 + " = " + result);
break;

// performs division between numbers


case '/':
result = number1 / number2;
System.out.println(number1 + " / " + number2 + " = " + result);
break;

default:
System.out.println("Invalid operator!");
break;
}

input.close();
}
}

111
Output:

Variable Description table:

Variable Variable Purpose


Name Type
Operator Char To store the choice of
user
Number1 int To store the input of
number to be
operated
Number2 int To store the number
to
be operated

112
QUESTION 28
To Display Calendar of Any Month of Any Year
ALGORITHM
STEP 1 - START
STEP 2 - INPUT int month,int
year
STEP 3 - int
i,count=0,b,c,d=1 & String
w="SMTWTFS"
STEP 4 - IF (year%100==0
&& year%400==0) ||
(year%100!=0 &&
year%4==0) STEP 5 -
days[1]=29
STEP 6 - PRINT
"================The
Calendar
of"+month1[month-1]+"
"+year+"is==============
====")
STEP 7 - IF i=0 THEN GOTO
STEP 8 STEP 8 - PRINT
(i)+"\t" & " "
STEP 9 - IF i=1 GOTO STEP
10
STEP 10 - IF (year%100==0
&& year%400==0) ||
(year%100!=0 &&
year%4==0)THEN GOTO
STEP 11OTHERWISE GOTO
STEP 12
STEP 11 - count+=2 STEP 12
113
- count+=1
STEP 13 - IF i=0 GOTO STEP
14
STEP 14 - count+=days[i] ,
count+=1, count%=7 & b=7-
count STEP 15 - IF b!=1 ||
b!=7 GOTO STEP 16
STEP 16 - IF count>0 GOTO
STEP 17,18 STEP 17 - PRINT '
'+"\t")
STEP 18 - count--
STEP 19 - IF i=1 GOTO STEP
20
STEP 20 - IF b>0 && IF
d<=days[month-1] GOTO
STEP 21,22 STEP 21 - PRINT
d+"\t"
STEP 22 - d++ & b-- STEP 23
- b=7
STEP 24 - i++ & IF i<MONTH
GOTO STEP14 STEP 25 -
PRINT " "
STEP 26 – END

114
Solution
import java.io.*;
class Calendar
{public void dee()throws IOException
//dee() function
{int i,count=0,b,d=1;
BufferedReader br=new
BufferedReader(new
InputStreamReader(System.in));
System.out.println(“Enter month”);
//accepting month and year int
month=Integer.parseInt(br.readLine()
);
System.out.println(“Enter Year”);
int
year=Integer.parseInt(br.readLine());
/* Computing and displaying
calendar*/ String w="SMTWTFS";
int
days[]={31,28,31,30,31,30,31,31,30,3
1,30,31};
String
month1[]={"January","February","Mar
ch","April","May","June","July","Augu
st","September","October","Novemb
er","December"};
if((year%100==0 && year%400==0) ||
(year%100!=0 && year%4==0))
days[1]=29;
System.out.println("==============
==The Calendar of"+month1[month-
1]+"
"+year+"is==================");
for(i=0;i<w.length();i++)
System.out.print(w.charAt(i)+"\t");
System.out.println(" ");
115
for(i=1;i<year;i++)
if((year%100==0 && year%400==0) ||
(year%100!=0 && year%4==0))
count+=2;
else count+=1; for(i=0;i<month;i++)
count+=days[i]; count+=1; count%=7;
b=7-count; if(b!=1 || b!=7)
while(count>0)
{System.out.print(' '+"\t"); count--;
}
for(i=1;i<7;i++)
{while(b>0 && d<=days[month-1])
{System.out.print(d+"\t"); d++;
b--;
} b=7;
System.out.println(" ");
}}}

116
Variable Description Table
No. Name Type Method Description
1 br BufferedReader dee() BufferedReader object
2 i int dee() loop variable
3 count int dee() counter
4 b int dee() week counter
5 d int dee() day counter
6 month int dee() input month
7 year int dee() input year
8 w String dee() week days
9 days String[] dee() array storing days
10 month1 String[] dee() array storing months

Output

117
QUESTION 29
To Calculate GCD Using Recursion
ALGORITHM
STEP 1 -
START STEP 2
- INPUT p,q
STEP 3 - IF(q=0) THEN return p OTHERWISE return calc(q,p%q)
STEP 4 – END

Solution
import
java.io.*;
class GCD
{public static void main(String args[]) throws IOException //main
function
{BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)); System.out.println("enter the
numbers =");
int p = Integer.parseInt(br.readLine());
//accepting
nos. int q = Integer.parseInt(br.readLine());
GCD obj = new
GCD(); int g =
obj.calc(p,q);
System.out.println("GCD ="+g);
}
public int calc(int p,int q) //recursive function calculating GCD
{if(q==
0)
return
p;
else return calc(q,p%q);
}}

118
Variable Description Table
No. Name Type Method Description
1 br BufferedReader main() BufferedReader object
2 p int main() ,calc() input number
3 q int main() ,calc() input number
4 obj GCD main() GCD object
5 g int main() variable storing the GCD

Output

119
QUESTION 30
To create a string and replace all vowels with *
ALGORITHM
STEP 1 - START
STEP 2 - a = "Computer Applications" STEP 3 - x= 0
STEP 4 - FROM z =0 to z<a.length() REPEAT STEP 5
STEP 5 -
if(a.charAt(z)=='a'||a.charAt(z)=='e'||a.charAt(z)=='i'||a.charAt(z)=='
o'||a.charAt(z)=='u’) THEN a.setCharAt(z,'*')
STEP 6 - PRINT "New String -"+a STEP 7 – END

Solution
import
java.io.*;
class
VowelRe
place
{public static void main(String args[])throws IOException //main
function
{BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(“Enter a String”);
StringBuffer a=new StringBuffer(br.readLine());
//accepti
ng a string System.out.println("Original String -"+a);
int z=0;
for(z=0;z<a.length();z++) //loop for replacing vowels with "*"
{if(a.charAt(z)=='a'||a.charAt(z)=='e'||a.charAt(z)=='i'||a.charAt(z)==
'o'||a.charAt(z)=='u') a.setCharAt(z,'*');
}System.out.println("New String -"+a); //displaying the result
}}

120
Variable Description Table
No. Name Type Method Description
1 br BufferedReader main() BufferedReader object
2 a StringBuffer main() StringBuffer object of input string
3 z int main() loop variable

Output

121

You might also like