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

NAME:Kshitij Jha SUBJECT:Mathematics INDEX NO.:038

Uploaded by

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

NAME:Kshitij Jha SUBJECT:Mathematics INDEX NO.:038

Uploaded by

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

MA129

NAME :Kshitij Jha


SUBJECT :Mathematics
INDEX NO. :038

Page 1
CERTIFICATE

This project work entered has been


satisfactorily performed by
Master/Miss Kshitij Jha studying in N.
L. Dalmia High School, Mira Road
(East), during the academic year
2020-2021.

CLASS: XII DIV: A


INDEX NO. : 038

Page 2
Page 3
COMPUTER
SCIENCE
PROJECT

29/9/2020 ISC CS Project (JAVA)

.
Class:12 Name : Kshitij Jha
Div:A
School : N.L. Dalmia High School

Page 4
Table of Contents:
Sr. Topic No. Of Page sign.
No. Name Programs Number
1 Methods 8 6
2 Recursion 7 30
Data 5
3 52
Structures
4 Arrays 15 76
Number 15
5 131
Programs
String 8
6 164
Programs
Exception 6
7 178
Handling
Board 4
8 189
Programs

External Examiner’s
Signature:
________________

Page 5
Topic-1: Methods
Question 1: Write a class in JAVA with a function void area()
which finds the area of circle, triangle, square and rectangle
using function overloading.

Algorithm:
1. Define the class OverloadDemo.
2. Now create three void return type functions with the name “area” to
implement polymorphism.
3. In the first function, the parameter is a float integer. This function
will take side of square as parameter and will print the area of the
square as a result. Formula used: A=side *side.
4. In the second function, take the length and breadth of the rectangle
as parameter and use A= l*b to find the area of the rectangle.
5. In the third function input radius and use the formula
A = pi*r*r to find Area of the circle.
6. Implement the main function to pass values to the function to get the
value of area of the figures.

Page 6
Code:
class OverloadDemo
{
void area(float x)
{
System.out.println("the area of the square is
"+Math.pow(x, 2)+" sq units");
}
void area(float x, float y)
{
System.out.println("the area of the rectangle is "+x*y+"
sq units");
}
void area(double x)
{
double z = 3.14 * x * x;
System.out.println("the area of the circle is "+z+" sq
units");
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
ob.area(5);
ob.area(11,12);
ob.area(2.5);
}}

Page 7
Variable Description Table:
Variable Name Variable Type Use
x float Parameter of function
“area” for finding the
Area of Square. This
parameter passes the
side of the square to the
function
x,y float Parameters of function
“area” for finding area of
rectangle. These pass the
length & breadth of the
rectangle to the function.
x doublt Parameter of function
“area” for finding area of
circle. This passes the
value of radius to the
function.

Page 8
Output:

Page 9
Question 2: Write a Program in JAVA to demonstrate use of
call by value.

Algorithm:
1. Create the class called Tester.
2. Write a function called swapFunction() which swaps the values of
the integers passed to it as Parameters using a third variable as
temporary variable.
3. In the main function, define two integer type variables ‘a’=30 and
‘b’=50.
4. Print the values of the the variables before running swapFunction()
and after running the function.

Page 10
Code:
public class Tester{
public static void main(String[] args){
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b =
" + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping
values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is
" + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + "
b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + "
b = " + b);
}
}

Variable Description Table:


Variable Name Variable Type Use
a Integer Test value for function
b Integer Test value for function

Page 11
Output:

Page 12
Question 3: To find roots of the quadratic equation of the
type ax 2 + bx +c =0 when the values of a, b, c are known.

Algorithm:
1. Import java.util.scanner and define the public class
RootsOfQuadraticEquation.
2. Input the values of a, b, c using Scanner.
3. Check whether the value of discriminant(b2-4ac>0) greater or equal
zero or not. If not greater or equal to 0. Print the equation has not
roots and stop execution.
4. If discriminant is not 0, use the formula ,
to find roots of the equation.

Page 13
Code:
import java.util.Scanner;
public class RootsOfQuadraticEquation {
public static void main(String args[]){
double secondRoot = 0, firstRoot = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of a ::");
double a = sc.nextDouble();

System.out.println("Enter the value of b ::");


double b = sc.nextDouble();

System.out.println("Enter the value of c ::");


double c = sc.nextDouble();

double determinant = (b*b)-(4*a*c);


double sqrt = Math.sqrt(determinant);
findroots(a,b,c,determinant,sqrt);}
public static void findroots(Double a, Double b,Double c,Double
determinant,Double sqrt){
if(determinant>0){

Double firstRoot = (-b + sqrt)/(2*a);


Double secondRoot = (-b - sqrt)/(2*a);
System.out.println("Roots are :: "+ firstRoot +" and
"+secondRoot);
}else if(determinant == 0){
System.out.println("Root is :: "+(-b + sqrt)/(2*a));}
}}

Page 14
Variable descriptor Table:

Variable Name Variable Type Use


a double To store coefficient of
x2
b double To store coefficient of x
c double To store the constant of
the equation
discriminant double To store the
discriminant

Page 15
Output:

Page 16
Question 4: Write a program in JAVA to find the vertex of the
parabola of the form y=ax 2 +bx+c.

Algorithm:
1. Import java.util.scanner and define the class Vertex.
2. Input values of a, b, c using Scanner class.
3. Use the formula Discriminant=b2-4ac to find the discriminant.
4. Find the vertex using formula “x=-b/2a” and
“y=discriminant/4a”.

Page 17
Code:
import java.util.Scanner;
public class Vertex {
public static void main(String args[]){
double secondRoot = 0, firstRoot = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of a ::");
double a = sc.nextDouble();

System.out.println("Enter the value of b ::");


double b = sc.nextDouble();

System.out.println("Enter the value of c ::");


double c = sc.nextDouble();

double determinant = (b*b)-(4*a*c);


double sqrt = Math.sqrt(determinant);
findvertex(a,b,c,determinant,sqrt);}
public static void findvertex(Double a,Double b,Double c,Double
determinant,Double sqrt){
Double x=((-(b)/2*a));
Double y= (determinant/4*a);
System.out.println("Y Coordinate:"+x);
System.out.println("X Coordinate:"+y);
}}

Page 18
Variable descriptor Table:
Variable Name Variable Type Use
a double To store coefficient of
x2
b double To store coefficient of x
c double To store the constant of
the equation
discriminant double To store the
discriminant

Page 19
Output:

Page 20
Question 5: To solve “linear equation in one variable” of the
form:ax=b+c.

Algorithm:
1. Import java.util.scanner and define the class eq.
2. Input values of a, b, c using Scanner class.
3. Use formula x=b+c/a to find value o f ‘x’.
4. Print the value using System.out.println() function.

Page 21
Code:
import java.util.*;
public class eq{
public static void main(){
double a,b,c;
System.out.println("Enter the value of a");
a=new Scanner(System.in).nextDouble();
System.out.println("Enter the value of b");
b=new Scanner(System.in).nextDouble();
System.out.println("Enter the value of c");
c=new Scanner(System.in).nextDouble();
System.out.println("The roots of the equation are:"+((b+c)/a));
}
}

Variable descriptor Table:


Variable Name Variable Type Use
a Double To store coefficient of x
b Double To store constant 1
c Double To store constant 2

Page 22
Output:

Page 23
Question 6: To check whether two lines of the form ax+by+c=0
intersect at a unique point or not.

Algorithm:
1. Import java.util.scanner and define the class intersect.
2. Input values of a1, b1, c1,a2,b2,c2 using Scanner class.
3. If a1/a2=b1/b2=c1/c2 then the lines are non intersecting and
parallel. a1/a2=b1/b2!=c1/c2 then lines are coinciding if
a1/a2!=b1/b2 then lines are coinciding.
4. Print the result using System.out.println().

Page 24
Code:
import java.util.*;
public class intersect{
public static void main(){
double a1,b1,c,a2,b2,c2;
System.out.println(“Enter values of a1,b1 and c1”);
int a1=new Scanner(Systen.in).nextDouble();
int b1=new Scanner(Systen.in).nextDouble();
int c1=new Scanner(Systen.in).nextDouble();
System.out.println(“Enter values of a2,b2 and c2”);
int a2=new Scanner(Systen.in).nextDouble();
int b2=new Scanner(Systen.in).nextDouble();
int c2=new Scanner(Systen.in).nextDouble();
if((a1/a2)!=(b1/b2)){
System.out.println(“The lines intersect at unique point”);
}else if((a1/a2)==(b1/b2)==(c1/c2))
{System.out.println(“The lines are parallel and don’t intersect”);}
else
{System.out.println(“The lines are coinciding”);}
}
}

Variable descriptor Table:


Variable Name Variable Type Use
a Double To store coefficient of x
b Double To store constant 1
c Double To store constant 2

Page 25
Output:

Page 26
Question 7: To calculate the sum, product , difference
,quotient is of two nos. using function arguments.

Algorithm:
1. Import java.util.scanner and define the class KJ.
2. Write the functions to calculate sum, product, difference, quotient
which return the answer.
3. Implement main function to display the answer using
System.out.println() function.

Code:
public class KJ{
public static void main(){
int a=10,b=10;
System.out.println("Sum="+sum(a,b)+" difference="+difference(a,b)+"
product="+product(a,b)+" division="+div(a,b));
}
public static int sum(int a,int b){
return (a+b);}
public static int product(int a,int b){
return (a*b);}
public static int difference(int a,int b){
return (a-b);}
public static int div (int a,int b){return(a/b);}}

Variable descriptor Table:


Variable Name Variable Type Use
a int To store value of
operator 1
b int To store value of
operator 2

Page 27
Output:

Page 28
Question 8: To check whether a point lies on the line of the form
ax+by+c=0.
Code:
import java.util.*;
public class linepoint{
public static void main(){
int a,b,c,x,y;
System.out.prnintln(“Enter value of a:”);
a=new Scanner(System.in).nextInt();
System.out.prnintln(“Enter value of b:”);
b=new Scanner(System.in).nextInt();
System.out.prnintln(“Enter value of c:”);
c=new Scanner(System.in).nextInt();
System.out.prnintln(“Enter value of x:”);
x=new Scanner(System.in).nextInt();
System.out.prnintln(“Enter value of y:”);
y=new Scanner(System.in).nextInt();
if((a*x+b*y+c)==0){
System.out.println(“The point lies on the line.”);
}else{System.out.println(“The point doesn’t lie on the line.”)}}
}

Algorithm:
1. Import java.util.scanner and define the class linepoint.
2. Input the required variables a,b,c,x,y.
3. If the value of a*x+b*y+c=0 the print the message “The given point
lies on the given line” if not equal to 0, display “The given point
doesn’t lie on the given line”

Page 29
Topic-2: Recursion
Question 1: To print a right angled triangle using recurision.

Algorithm:
1. Create a class and create a main function, and two recursive
functions. One to recursively print ‘n’ stars and one to call the
the first function ‘n’ times.
2. A function printn(int num) prints ‘n’ stars recursively using
(n==0) as base case and print a star every time in the
recursive case. Call the function recursively as printn(num-1)
3. A function pattern is to be defined with the base n==0. The
recursive case calls the function with parameters n-1 and i+1
after calling printn() function which prints n stars.

Code:
import java.io.*;
class KJ
{
static void printn(int num)
{
if (num == 0)
return;
System.out.print ("* ");
printn(num - 1);
}

// function to print the pattern


static void pattern(int n, int i)
{
// base case
if (n == 0)
return;
printn(i);
System.out.println();

// recursively calling pattern()


pattern(n - 1, i + 1);
}

// Driver code
public static void main (String[] args)
{

int n = 5;pattern(n, 1); } }

Page 30
Variable descriptor Table:
Variable Name Variable Type Use
n int To store the size of
triangle
num int Parameter of
printn(int num)
i int To store the number of
times the star is to be
printed.

Page 31
Output:

Page 32
Question 2: To print a pyramid of ‘*’ using recurision.

Algorithm:
1. Create a class,main function, a function to recursively
print spaces, recursively print stars and to recursively call
the function which prints stars and spaces.
2. Each line in a pyramid is generated by a series of spaces
and stars.
3. A function named print_space(int space) will recursively
print spaces. The base case of recursion will be space==0,
where space is the function parameter. The recursive
function call will be print_space(space-1) which will be
called after printing a Space using System.out.println(“ ”)
4. A function named print_asterisk(int asterisk) will
recursively print *. The base case of recursion will be
asterisk==0, where asterisk is the function parameter. The
recursive function call will be print_asterisk(asterisk-1)
which will be called after printing a Space using
System.out.println(“ *”)
5. Another function called pattern(int n,int num) with two
parameters of type int will call print_space with
parameter(n-1) and print_asterisk with parameter (n-
1,num). The total number of characters in each line of the
pyramid will thus remain constant.

Code:
import java.util.*;

class KJ
{

// function to print spaces


static void print_space(int space)
{
// base case
if (space == 0)
return;
System.out.print(" ");

// recursively calling print_space()


print_space(space - 1);
}

Page 33
// function to print asterisks
static void print_asterisk(int asterisk)
{
// base case
if (asterisk == 0)
return;
System.out.print("* ");

// recursively calling asterisk()


print_asterisk(asterisk - 1);
}

// function to print the pattern


static void pattern(int n, int num)
{
// base case
if (n == 0)
return;
print_space(n - 1);
print_asterisk(num - n + 1);
System.out.println("");

// recursively calling pattern()


pattern(n - 1, num);
}

// Driver code
public static void main(String[] args)
{
int n = 5;
pattern(n, n);
}
}

Variable descriptor Table:


Variable Name Variable Type Use
n int To store the size of
pyramid
num int To store the size of
pyramid

Page 34
Output:

Page 35
Question 3: To print a hollow square using recursion in JAVA.

Algorithm:
1. Create a class and write the main function to drive the
recursive functions.
2. The function “repeatMiddleLine(int lineCount,int
lineLength)” will recursively print the two vertical sides
of the square containing (n-2) stars. where n is the
number of stars in one side of the square. Using the
recursive function repeatChar(char c,int count). Base
case of repeatMiddleLine() is linezCount>0 And the
function is again called recursively using
parameters(lineCount-1,lineLength). line length is the
number of character in one row. line count is the number
of rows.
3. The function repeatChar(char c,int count) recursively
prints the character obtained from the parameter ‘c’
count times where count is a function parameter.
4. In the main function To draw the Horizontal lines
repeatChar() is used directly. And to print the vertical
line of stars, repeatMiddleLine() is used.The parameter
used for repeatMiddleLine() is max-2 for no. of rows and
max for no. of characters in one row.
5. This way a square is drawn.

Code:
import java.util.*;
public class asquare{

private static final char squareChar = '*';


private static final char holeChar = ' ';

public static void main(String[] args) {


try (Scanner ma = new Scanner(System.in)) {
System.out.print("Enter the number:");
int max = ma.nextInt();
repeatChar(squareChar, max);
System.out.println();
repeatMiddleLine(max - 2, max);
repeatChar(squareChar, max);
System.out.println();
}

Page 36
}

private static void repeatMiddleLine(int lineCount, int


lineLength) {
if (lineCount > 0) {
System.out.print(squareChar);
repeatChar(holeChar, lineLength - 2);
System.out.println(squareChar);
repeatMiddleLine(lineCount- 1, lineLength);
}
}

private static void repeatChar(char c, int count) {


if (count > 0) {
System.out.print(c);
repeatChar(c, count - 1);
}
}}

Variable descriptor Table:


Variable Name Variable Type Use
squareChar char To store the constant
character ‘*’
holeChar char To store the constant
character “ ”(Space)
max int To store the number of
stars in one side of the
square.
lineCount int The number of rows of
stars in the vertical line
lineLength int The number of
chatacters(stars +
spaces) in one row.
c char Parameter of
repeatChar() which is
to be printed again and
again
count int Parameter of
repeatChar() which
decides how many
times the character will
be printed.

Page 37
Output:

Page 38
Question 4: To print a hollow rectcangle pattern of m rows
and n columns using stars (*) using recursion.

Algorithm:
1. Create a class and write the main function to drive the
recursive functions.The main function has variables “l”
and “h” for the length and the breadth of the rectangle
respectively.
2. The function “repeatMiddleLine(int lineCount,int
lineLength)” will recursively print the two vertical sides
of the square containing (n-2) stars. where n is the
number of stars in one side of the square. Using the
recursive function repeatChar(char c,int count). Base
case of repeatMiddleLine() is linezCount>0 And the
function is again called recursively using
parameters(lineCount-1,lineLength). line length is the
number of character in one row. line count is the number
of rows.
3. The function repeatChar(char c,int count) recursively
prints the character obtained from the parameter ‘c’
count times where count is a function parameter.
4. In the main function To draw the Horizontal lines
repeatChar() is used directly with parameter l. And to
print the vertical line of stars, repeatMiddleLine() is
used.The parameter used for repeatMiddleLine() is “h-2”
for no. of rows and “l” for no. of characters in one row.
5. This way a rectangle of dimensions l by h is drawn.

Code:

import java.util.*;
public class rect{

private static final char squareChar = '*';


private static final char holeChar = ' ';

public static void main(String[] args) {


try (Scanner ma = new Scanner(System.in)) {
System.out.print("Enter the length and breadth (numbers
greater than 1):");
int l = ma.nextInt();

Page 39
int h = ma.nextInt();
repeatChar(squareChar, l);
System.out.println();
repeatMiddleLine(h - 2, l);
repeatChar(squareChar, l);
System.out.println();
}
}

static void repeatMiddleLine(int lineCount, int lineLength) {


if (lineCount > 0) {
System.out.print(squareChar);
repeatChar(holeChar, lineLength - 2);
System.out.println(squareChar);
repeatMiddleLine(lineCount- 1, lineLength);
}
}

static void repeatChar(char c, int count) {


if (count > 0) {
System.out.print(c);
repeatChar(c, count - 1);
}
}
}

Page 40
Variable descriptor Table:
Variable Name Variable Type Use
squareChar char To store the constant
character ‘*’
holeChar char To store the constant
character “ ”(Space)
l int To store the number of
stars in one lentgh of
the rectangle.
h int To store the number of
stars in the height of the
rectangle.
lineCount int The number of rows of
stars in the vertical line
lineLength int The number of
chatacters(stars +
spaces) in one row.
c char Parameter of
repeatChar() which is
to be printed again and
again
count int Parameter of
repeatChar() which
decides how many
times the character will
be printed.

Page 41
Output:

Page 42
Question 5: To find the GCD of two numbers using recursion.

Algorithm:
1. Create a class and write the main function to drive the
recursive function.
2. GCD or HCF of a number is a number which is the
greatest common factor of the two numbers.
3. To find the HCF we will write a recursive function and a
main function.
4. The name of the recursive function is hcf() it returns the
hcf.
5. Now by euclid’s division lemma, any two whole numbers
a and b can be expressed in the form, a=bq+r.
6. The function applies the division lemma again and again
to find the hcf. After each step, the value of a is reset to
the value of b and the value of b is taken to be equal to r.
7. The same is recurisively repeated until the value of r
turns out to be 0. When the value of r is 0, then the value
of b obtained is the hcf of the two initial numbers.
8. Here in our program a is n1, b is n2 and r is n1%n2.
9. This is how GCD is calculated.

Code:
public class GreatestCommonFactor {

public static void main(String[] args) {


int n1 = 120, n2 = 60;
int gcd = hcf(n1, n2);

System.out.println();
}

public static int hcf(int n1, int n2)


{

Page 43
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
}

Variable descriptor Table:


Variable Name Variable Type Use
n1 int To store the firsrt
number whose hcf is to
be found
n2 int To store the second
number whose hcf is to
be found
hcf int to store the value of hcf

Page 44
Output:

Page 45
Question 6: To print array elements using recursion.

Algorithm:
1. Create a class and write the main function to drive the
recursive function.
2. Create and array and initialize the array directly during
the declaration in the main function
3. Create a function recarray(int a[],int index,int size)
which will print the array.The return type will be int.
4. The base case of recurision here is index>size. When
index is larger than size the function will return 0.
5. If index is not larger than size then a[index] will be
printed and the function will be recursively called with
the parameters as follows, recarray(a[],index+1,size)
6. Thus the function will keep on running and will print all
the elements of the array.
7. In the main function, array will be declared and
initialized.

Code:
public class arrayrec{
public static void main(){
int arr[]={1,2,3,100,45,9999};
recarray(arr,0,arr.length-1);
}
public static int recarray(int a[],int index,int size){
if(index>size){return 0;
}
System.out.println(a[index]);
return recarray(a,index+1,size);
}
}

Page 46
Variable descriptor Table:
Variable Name Variable Type Use
arr int array The array to work on
a int array The array passed as
parameter to
recarray()
index int to store the the index of
the array currently
being printed
size int to store the value of
greatest index of the
array

Page 47
Output:

Page 48
Question 7: To print the largest element of an integer array
using recursion.

Algorithm:
1. Create a class and write the main function to drive the
recursive function.
2. In the main function declare and initialize the array. The
main function also calls the recursive function.
3. Declare a recursive function recarray(int a[],int
index,int size,int large) with return type int. Here a[] is
the array to work on, size is the largest index, index is the
current index for which the function has been called and
large stores the largest number found in the array.
4. The base of recursion is index>size. Thus the function will
stop execution when index will exceed the value of largest
index. Then large will be compared with the integer in
the array at the current index. If large is smaller than the
integer at the current index, then the value of large will
be set to the value of the integer at current index. After
the comparison the function will be recursively called
with the parameters as follows,
recarray(a[],index+1,size+,large).
5. If we reach the end of the array ie. index=size. Then the
value of large will be printed using System.out.println().
6. Then after the next recursive call the value of index will
exceed size. And thus according to base case the function
will return large.
7. Thus we will get the largest number in the array.

Code:
public class arrayrec1{
public static void main(){
int arr[]={1,2,3,100,45,10000,9999};
recarray(arr,0,arr.length-1,0);
}

public static int recarray(int a[],int index,int size,int large){


if(index>size){return 0;
}
if(a[index]>large)
{large=a[index];}
if(index==size){

Page 49
System.out.println("Largest number in the array
is:"+large);
}
return recarray(a,index+1,size,large);
}
}

Variable descriptor Table:


Variable Name Variable Type Use
arr int array The array to work on
a int array The array passed as
parameter to
recarray()
index int to store the the index of
the array currently
being printed
size int to store the value of
greatest index of the
array
large int to store the value of the
greatest integer in the
array.

Page 50
Output:

Page 51
Topic-3: Data Structures
Question 1: To implement a static stack data structure using
array.

Algorithm:
1. Create a class DynamicStack with the following data
members:
 int arr[] :the array we will use to implement the
stack.
 int size : to store the size of the array.
 int bottom : to store the index of the bottom of the
stack. The element at the bottom will be removed
first and elements will be added at the bottom of
the stack
2. Create a parameterized constructor
public DynamicStack(int intisize) to initialize the
data members of the object.The constructor will perform
the following operations:
 Initialize the array with arr=new int[initsize]
 set the value of size using size=initsize
 Set the value of each element of the array to:
-99999(in our program the value -99999 means
empty)
 In our program if the value of an array element is
-99999 it means that that space is empty in the
stack. This has been done to avoid confusion
between empty spaces in the stack and spaces
where data is present.
3. Now we will create the member functions :
 private static void push(int value): It will push
the values to the stack. As we are implementing the
stack in an array the bottom part of the stack will
keep moving down until the space in the array is
over. The elements will be popped from the
bottom..This function will push value in the
following way :
i. arr[bottom+1]=value;

Page 52
ii. bottom=bottom+1;
 private static int pop(): It will pop the values
out of the stack from the bottom of the stack. It wil
first check whether the stack is empty by checking
whether bottom<0.If the stack is empty an error
message is displayed.It will set the value at the
bottom index to -99999(empty value) and the then
it will reduce the value of bottom by the statement:
bottom=bottom-1. It will return the value popped
out if the stack was not empty. If it was empty, it
will return the error code -999.
 private static void printElements(): This
function will use a for loop. In the for loop if the
value of arr[i]==-99999 nothing will be printed as
the element is empty. If the value arr[i]!=-99999
then the value of arr[i] will be printed using
System.out.println()
4. Then write a main function to run test the code using all
the functions after class creation.

Code:
public class StaticStack{
private static int arr[];
private static int size;
private static int bottom=-1;

public StaticStack(int initsize){


arr=new int[initsize];
size=initsize;
for(int i=0;i<size;i++){
arr[i]=-99999;
}
}

private static void push(int value){


if(bottom==size-1){
System.out.println("Stack Overflow");
}
arr[bottom+1]=value;
bottom=bottom+1;
}

private static int pop(){

Page 53
if(bottom<0){
System.out.println("Cannot Pop elements as DynamicStack is
empty");
}
else if(arr[bottom]==-99999){

}
else{
int temp= arr[bottom];
arr[bottom]=-99999;
bottom=bottom-1;
return temp;
}
System.out.print("Error Code Returned:");
return -999;
}

private static void printElements(){


for(int i=0;i<size;i++){if(arr[i]!=-99999){
System.out.println("INDEX:"+(i+1)+" = "+arr[i]);}
}
}
public static void main(){
StaticStack a = new StaticStack(7);
a.push(10);
a.push(20);
a.push(30);
a.push(40);
a.push(50);
a.push(60);
a.push(70);
a.printElements();
a.pop();
a.pop();
a.pop();
a.pop();
a.pop();
a.pop();
a.pop();}
}

Page 54
Variable descriptor Table:
Variable Name Variable Type Use
arr int array The array to be used as
stack
bottom int The bottom index of
stack
size int The size of the stack
value int the value to be pushed
into the stack
temp int the value which has
been popped and will
now be returned by the
pop function

Page 55
Output:

Page 56
Question 2: To implement a dynamically sized stack using
array.

Algorithm:
i. Create a class DynamicStack with the following data
members:
 int arr[] :the array we will use to implement the
stack.
 int size : to store the size of the array.
 int bottom : to store the index of the bottom of the
stack. The element at the bottom will be removed
first and elements will be added at the bottom of
the stack
ii. Create a parameterized constructor
public DynamicStack(int intisize) to initialize the
data members of the object.The constructor will perform
the following operations:
 Initialize the array with arr=new int[initsize]
 set the value of size using size=initsize
 Set the value of each element of the array to:
-99999(in our program the value -99999 means
empty)
 In our program if the value of an array element is
-99999 it means that that space is empty in the
stack. This has been done to avoid confusion
between empty spaces in the stack and spaces
where data is present.
iii. Now we will create the member functions :
 private static void increaseSize() : This
function will increase the size of the array and thus
will add more memory to the stack. This will be
called when the stack runs out of space. It will
create a temporary array to store the values of the
original array temporarily. Then it will redefine
the original array as follows: arr=new
int[temp.length+size]. Then the values stored in
temp will be transferred to our original array
using for loop and all the empty spaces will be set
to -99999 (it signifies empty space)

Page 57
 private static void push(int value): It will push
the values to the stack. As we are implementing the
stack in an array the bottom part of the stack will
keep moving down until the space in the array is
over. The elements will be popped from the bottom.
The function will first check whether there is space
in the stack by checking whether bottom==size.If
there is no space, increaseSize() is called and then
the value is pushed.This function will pop value in
the following way :
a. arr[bottom+1]=value;
b. bottom=bottom+1;
 private static int pop(): It will pop the values
out of the stack from the bottom of the stack. It wil
first check whether the stack is empty by checking
whether bottom<0.If the stack is empty an error
message is displayed.It will set the value at the
bottom index to -99999(empty value) and the then
it will reduce the value of bottom by the statement:
bottom=bottom-1. It will return the value popped
out if the stack was not empty. If it was empty, it
will return the error code -999.
 private static void printElements(): This
function will use a for loop. In the for loop if the
value of arr[i]==-99999 nothing will be printed as
the element is empty. If the value arr[i]!=-99999
then the value of arr[i] will be printed using
System.out.println()
iv. Then write a main function to run test the code using all
the functions after class creation.

Page 58
Code:
public class DynamicStack{
private static int arr[];
private static int size;
private static int bottom=-1;

public DynamicStack(int initsize){


arr=new int[initsize];
size=initsize;
for(int j=0;j<size;j++){
arr[j]=-99999;
}
}

private static void increasesize(){


System.out.println("DynamicStack OverFlow Error has occured");
System.out.println("Adding more Memory to DynamicStack");
int temp[] = arr;
arr=new int[temp.length+size];
for(int i=0;i<size;i++){
arr[i]=temp[i];
}
size=temp.length+size;
for(int j=bottom+1;j<size;j++){
arr[j]=-99999;
}
temp=null;
}

private static void push(int value){

Page 59
if(bottom==size-1){
increasesize();
}
arr[bottom+1]=value;
bottom=bottom+1;
}

private static int pop(){


if(bottom<0){
System.out.println("Cannot Pop elements as DynamicStack is
empty");
}
else if(arr[bottom]==-99999){

}
else{
int temp= arr[bottom];
arr[bottom]=-99999;
bottom=bottom-1;
return temp;
}
System.out.print("Error Code Returned:");
return -999;
}

private static void printElements(){


for(int i=0;i<size;i++){if(arr[i]!=-99999){
System.out.println("INDEX:"+(i+1)+" = "+arr[i]);}
}
}
public static void main(){

Page 60
DynamicStack a = new DynamicStack(3);
a.push(12);
a.printElements();
System.out.println(" ");
a.push(13);
a.printElements();
System.out.println(" ");
a.push(14);
a.printElements();
System.out.println(" ");
a.push(15);
a.printElements();
System.out.println(" ");
a.push(16);
a.printElements();
System.out.println(" ");
System.out.println(a.pop());
System.out.println(a.pop());
System.out.println(a.pop());
System.out.println(a.pop());
System.out.println(a.pop());
System.out.println(a.pop());

Page 61
Variable descriptor Table:
Variable Name Variable Type Use
arr int array The array to be used as
stack
bottom int The bottom index of
stack
size int The size of the stack
value int the value to be pushed
into the stack
temp int the value which has
been popped and will
now be returned by the
pop function
temp int array The temporary array
used to store the stack
temporarily when
increasing the size of
the array.

Page 62
Output:

Page 63
Question 3: To implement a Queue whose size can be increased
while execution.

Algorithm:
1. Create a class Queue which contains the following
data members:
 int arr[] :the array we will use to implement
the Queue.
 int size : to store the size of the array.
 int last : to store the index of the laste element
of the Queue.
 int first : to store the index of the first element
of the Queue.

2. Create a parameterized constructor


public Queue(int intisize) to initialize the data
members of the object.The constructor will perform
the following operations:
 Initialize the array with arr=new int[initsize]
 set the value of size using size=initsize
 Set the value of each element of the array to:
-99999(in our program the value -99999
means empty)
 In our program if the value of an array
element is -99999 it means that that space is
empty in the queue. This has been done to
avoid confusion between empty spaces in the
queue and spaces where data is present.
3. Now we will create the member functions :
 private static void add(int value): It will
push the values to the queue. As we are
implementing the queue in an array the
bottom part of the queue will keep moving
down until the space in the array is over. The
elements will be removed from the top.This
function will push value in the following way :
i. arr[last+1]=value;
ii. last=last+1;

Page 64
 private static int remove(): It will pop the
values out of the queue from the first index of
the queue. It will first check whether the queue
is empty by checking whether first<0.If the
queue is empty an error message is displayed
.It will store the value at the first index and
shift all the other values one index backward.
Thus the first value will be removed according
to the FIFO philosophy and the function will
return the value removed from the queue.
 private static void increaseSize() : This
function will increase the size of the array and
thus will add more memory to the queue. This
will be called when the queue runs out of space.
It will create a temporary array to store the
values of the original array temporarily. Then
it will redefine the original array as follows:
arr=new int[temp.length+size]. Then the
values stored in temp will be transferred to our
original array using for loop and all the empty
spaces will be set to -99999 (it signifies empty
space)
 private static void printElements(): This
function will use a for loop. In the for loop if
the value of arr[i]==-99999 nothing will be
printed as the element is empty. If the value
arr[i]!=-99999 then the value of arr[i] will be
printed using System.out.println()
4. Then write a main function to run test the code using
all the functions after class creation.

Page 65
Code:
public class Queue{
private static int arr[];
private static int size;
private static int last=-1;
private static int first=-1;
public Queue(int initsize){
arr=new int[initsize];
size=initsize;
for(int j=0;j<size;j++){
arr[j]=-99999;
}
first=0;
}

private static void increasesize(){

int temp[] = arr;


arr=new int[temp.length+size];
for(int i=0;i<size;i++){
arr[i]=temp[i];
}
size=temp.length+size;
for(int j=last+1;j<size;j++){
arr[j]=-99999;
}
temp=null;
}

private static void add(int value){


if(last==size-1){
increasesize();
}
arr[last+1]=value;
last=last+1;
}

private static int remove(){


if(first<0){
System.out.println("Cannot Pop elements as Queue is empty");
}
else if(arr[first]==-99999){

}
else{int i=0;
while(i<last+1){
arr[i]=arr[i+1];
i++;
}last--;first=0;
}
System.out.print("Error Code Returned:");

Page 66
return -999;
}

private static void printElements(){


for(int i=0;i<size;i++){if(arr[i]!=-99999){
System.out.println("INDEX:"+(i+1)+" = "+arr[i]);}
}

}
public static void main(){
Queue a = new Queue(5);
a.add(5);
a.add(6);
a.add(7);
a.add(8);
a.add(9);
a.printElements();
a.increasesize();
a.add(10);
a.printElements();
a.remove();
System.out.println();
a.printElements();
a.remove();
System.out.println();
a.printElements();
a.remove();
System.out.println();
a.printElements();
a.remove();
System.out.println();
a.printElements();
a.remove();
System.out.println();
a.printElements();
a.remove();
System.out.println();
a.printElements();

Page 67
Variable descriptor Table:
Variable Name Variable Type Use
arr int array The array to be used as
queue
bottom int The bottom index of
queue
size int The size of the queue
value int the value to be added
into the queue
temp int the value which has
been removed from the
queue and will now be
returned by the remove
function
temp int array The temporary array
used to store the queue
temporarily when
increasing the size of
the array.

Page 68
Output:

Page 69
Question 4: To implement a Queue whose size can not be
increased while execution.

Algorithm:
1. Create a class Queue which contains the following
data members:
 int arr[] :the array we will use to implement
the Queue.
 int size : to store the size of the array.
 int last : to store the index of the laste element
of the Queue.
 int first : to store the index of the first element
of the Queue.

2. Create a parameterized constructor


public Queue(int intisize) to initialize the data
members of the object.The constructor will perform
the following operations:
 Initialize the array with arr=new int[initsize]
 set the value of size using size=initsize
 Set the value of each element of the array to:
-99999(in our program the value -99999
means empty)
 In our program if the value of an array
element is -99999 it means that that space is
empty in the queue. This has been done to
avoid confusion between empty spaces in the
queue and spaces where data is present.
3. Now we will create the member functions :
 private static void add(int value): It will
push the values to the queue. As we are
implementing the queue in an array the
bottom part of the queue will keep moving
down until the space in the array is over. The
elements will be removed from the top.This
function will push value in the following way :
i. arr[last+1]=value;
ii. last=last+1;

Page 70
 private static int remove(): It will pop the
values out of the queue from the first index of
the queue. It will first check whether the queue
is empty by checking whether first<0.If the
queue is empty an error message is displayed
.It will store the value at the first index and
shift all the other values one index backward.
Thus the first value will be removed according
to the FIFO philosophy and the function will
return the value removed from the queue.
 private static void printElements(): This
function will use a for loop. In the for loop if
the value of arr[i]==-99999 nothing will be
printed as the element is empty. If the value
arr[i]!=-99999 then the value of arr[i] will be
printed using System.out.println()
4. Then write a main function to run test the code using
all the functions after class creation.

Page 71
Code:
public class Queue1{
private static int arr[];
private static int size;
private static int last=-1;
private static int first=-1;
public Queue1(int initsize){
arr=new int[initsize];
size=initsize;
for(int j=0;j<size;j++){
arr[j]=-99999;
}
first=0;
}

private static void add(int value){


if(last==size-1){
System.out.println("Cannot add more elements!!");
}
arr[last+1]=value;
last=last+1;
}

private static int remove(){


int value;
value=arr[first];
if(first<0){
System.out.println("Cannot Pop elements as Queue is empty");
}
else if(arr[first]==-99999){

}
else{int i=0;
while(i<last){

arr[i]=arr[i+1];

i++;
}arr[last]=-99999;last--;first=0;
return value;
}
System.out.print("Error Code Returned");
return -999;
}

private static void printElements(){


for(int i=0;i<size;i++){if(arr[i]!=-99999){
System.out.println("INDEX:"+(i+1)+" = "+arr[i]);}
}

Page 72
}
public static void main(){
Queue1 a = new Queue1(5);
a.add(5);
a.add(6);
a.add(7);
a.add(8);
a.add(9);
a.printElements();
System.out.println();
a.printElements();
a.remove();
System.out.println();
a.printElements();
a.remove();
System.out.println();
a.printElements();
a.remove();
System.out.println();
a.printElements();
a.remove();
System.out.println();
a.printElements();
a.remove();
System.out.println();
a.printElements();

Page 73
Variable descriptor Table:
Variable Name Variable Type Use
arr int array The array to be used as
queue
bottom int The bottom index of
queue
size int The size of the queue
value int the value to be added
into the queue
temp int the value which has
been removed from the
queue and will now be
returned by the remove
function
temp int array The temporary array
used to store the queue
temporarily when
increasing the size of
the array.

Page 74
Output:

Page 75
Topic-4: Arrays
Question 1: To store the value of a series of numbers in an
Array and find their Arithmetic Mean(Average).

Algorithm:
1. Create a class and import java.util.*.
2. We will use the Scanner class of java.util to take input from
the user.
3. Ask the user how many values does he need to find the mean
of and input the number of values storing it in an integer and
using scanner to take input from the user.
4. Initialize an array of Double data type for greater precision.
5. Take all the inputs to fill the elements of the array using a for
loop and Scanner class.
6. Arithmetic mean = Sum of all values/no. of values.
7. Find the sum of all the values of the array using a for loop
and a variable sum to store the sum of all the Values.
8. Divide the sum obtained by the number provided by
array.length and store it in the sum variable.
9. The number obtained is the arithmetic mean of all the
numbers which were obtained from the user.
10. Display the mean on the screen using System.out.println().

Page 76
Code:
import java.util.*;
public class NumMeanArray{
public static void main(){
System.out.println("Enter the no. of values to find the mean of:");
int n = new Scanner(System.in).nextInt();
Double array[] = new Double[n];
Double sum =0.0d;
for(int i=0;i<n;i++){
System.out.print("Enter "+(i+1)+"th" +" Value: ");
array[i]=new Scanner(System.in).nextDouble();
System.out.println("");
sum=sum+array[i];
}
System.out.println("The mean of the values enetered is :"+(sum/n));
}
}

Page 77
Variable descriptor Table:
Variable Name Variable Type Use
array Double array The array to be used to
store the values
sum double To store the sum of all
values
n int The size of the array
i int Iteration variable.

Page 78
Output:

Page 79
Question 2: To reverse a number using an array.

Algorithm:
1. Create a class and import java.util.*.
2. Create the main function and input a number form the user
using the scanner class.
3. Now find the number of digits in the number using a while
loop. Declare an integer variable i=0. In every iteration of
the loop, divide the number by 10, increment I and keep in
iterarting till the number>0. Before performing these
operation on the number store the number on a temporary
variable.
4. Next define an array with ‘ i ‘ elements. and using a for loop
add digits of the number from the back and perform the
operation arr.length times. The last digit of the number can
be obtained by using the % operator. i.e. finding num%10
every time the loop is executed and storing it to the array.
And then dividing the number by 10 and storing it in the
same number. Number=number/10.
5. Declare another integer. We will store our reversed integer
in this variable. This will be done with the help of another for
loop. in each iteration the following operation will occur:
a. rev=rev*10+arr[i];
6. Now print the reversed number ant the original number
using System.out.println();

Page 80
Code:
import java.util.*;
public class IntRevArray
{
public static void main(){
int a;
a= new Scanner(System.in).nextInt();
int b=a;
int tmp=a;
int i=0;
while(b!=0){
b=b/10;
++i;
}

int ar[] = new int[i];


for(int j=0;j<i;j++){
ar[j]=a%10;

a=a/10;
}
int rev=0;
for(int k=0;k<i;k++){
rev=rev*10+ar[k];
}
System.out.println("Original number:"+tmp);
System.out.println("Reversed Number using array:"+rev);
}
}

Variable descriptor Table:


Variable Name Variable Type Use
array int array The array to be used to
store the digits
a int To store the number
input by user
rev int To store the reversed
number
i int Iteration variable.
b,c int temporary variables to
store the value of the
value input by the user

Page 81
Output:

Page 82
Question 3: To Bubble Sort an array in ascending order.

Algorithm:
1. Create a class and import java.util.*.
2. Declare an array and initialize the array using random
values.
3. Create a function named bubble sort
4. The bubble sort algorithm works by comparing each array
element to the next element and swapping them if the next
one is smaller.
5. Implement the bubble sort by using two for loops.
6. The outer loop will cause the comparing of the consecutive
values to happen n times. where n is the number of array
elements.
7. The inner loop will compare each consecutive pair of
elements in the entire array and will swap them accordingly.

Code:
public class BubbleSortAscending {
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}

}
}

}
public static void main(String[] args) {
int arr[] ={3,60,35,2,45,320,5};

System.out.println("Array Before Ascending Bubble


Sort");
for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
System.out.println();

Page 83
bubbleSort(arr);

System.out.println("Array After Ascending Bubble


Sort");
for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}

}
}

Variable descriptor Table:


Variable Name Variable Type Use
arr int array The array to be used to
store the values.
i int iteration variable of the
outer loop
j int iteration variable of the
inner loop
tmp int temporaray variable
for swapping the values

Page 84
Output:

Page 85
Question 4: To Bubble Sort an array in descending order.

Algorithm:
1. Create a class and import java.util.*.
2. Declare an array and initialize the array using random
values.
3. Create a function named bubble sort
4. The bubble sort algorithm works by comparing each array
element to the next element and swapping them if the next
one is smaller.
5. Implement the bubble sort by using two for loops.
6. The outer loop will cause the comparing of the consecutive
values to happen n times. where n is the number of array
elements.
7. The inner loop will compare each consecutive pair of
elements in the entire array and will swap them accordingly
8. After the sorting we will reverse the array to make it in
descending order.

Code:
public class BubbleSortDescending {
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}

}
}

}
public static void main(String[] args) {
int arr[] ={3,60,35,2,45,320,5};

System.out.println("Array Before Descending Bubble


Sort");
for(int i=0; i < arr.length; i++){

Page 86
System.out.print(arr[i] + " ");
}
System.out.println();

bubbleSort(arr);
int temp[]=new int[arr.length];
for(int i=0;i<arr.length;i++){
temp[i]=arr[arr.length-1-i];
}
System.out.println("Array After Descending Bubble
Sort");
for(int i=0; i < arr.length; i++){
System.out.print(temp[i] + " ");
}

}
}

Variable descriptor Table:


Variable Name Variable Type Use
arr int array The array to be used to
store the values.
i int iteration variable of the
outer loop
j int iteration variable of the
inner loop
tmp int temporary variable for
swapping the values
tmp int array Temporary array for
reversing the array

Page 87
Output:

Page 88
Question 5: To Selection Sort an array in ascending
order.
Algorithm:
1. Create a class and import java.util.*.
2. Declare an array and initialize it with random values in the
main function.
3. Selection sort works by dividing the array in to subarrays
and finding the smallest element in that sub array and
putting it at the first position.
4. The first index will be first compared with all the values and
thus the smallest value will be placed at the first index.
5. Then the second index will be compared with all the values
and thus the second array will be placed at the second index
and the same with all the elements will take place.
6. This will be done with the help of two for loops. One nested
within the another. They will work as follows:
i. for (int i = 0; i < arr.length - 1; i++)
ii. {
iii. int index = i;
iv. for (int j = i + 1; j < arr.length;
j++){
v. if (arr[j] < arr[index]){
vi. index = j;//searching for
lowest index
vii. }
viii. }
ix. int smallerNumber = arr[index];
x. arr[index] = arr[i];
xi. arr[i] = smallerNumber;
xii. }
7. The array will be sorted by calling the selection sort function
which will contain the above code.

Page 89
Code:
public class SelectionSortAscending {
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}

public static void main(String a[]){


int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();

selectionSort(arr1);//sorting array using


selection sort

System.out.println("After Selection Sort");


for(int i:arr1){
System.out.print(i+" ");
}
}
}

Page 90
Variable descriptor Table:
Variable Name Variable Type Use
arr int array The array to be used to
store the values.
i int iteration variable of the
outer loop
j int iteration variable of the
inner loop
tmp int temporary variable for
swapping the values
smaller int stores the smallest
value in the subarray

Page 91
Output:

Page 92
Question 6: To Selection Sort an array in descending
order.
Algorithm:
1. Create a class and import java.util.*.
2. Declare an array and initialize it with random values in the
main function.
3. Selection sort works by dividing the array in to subarrays
and finding the smallest element in that sub array and
putting it at the first position.
4. The first index will be first compared with all the values and
thus the smallest value will be placed at the first index.
5. Then the second index will be compared with all the values
and thus the second array will be placed at the second index
and the same with all the elements will take place.
6. This will be done with the help of two for loops. One nested
within the another. They will work as follows:
i. for (int i = 0; i < arr.length - 1; i++)
ii. {
iii. int index = i;
iv. for (int j = i + 1; j < arr.length;
j++){
v. if (arr[j] < arr[index]){
vi. index = j;//searching for
lowest index
vii. }
viii. }
ix. int smallerNumber = arr[index];
x. arr[index] = arr[i];
xi. arr[i] = smallerNumber;
xii. }
7. The array will be sorted by calling the selection sort function
which will contain the above code.
8. The array will be reversed using a temporary array temp.
Thus we will get the array elements in descending order.

Page 93
Code:
public class SelectionSortDescending{
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}

public static void main(String a[]){


int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();

selectionSort(arr1);//sorting array using selection sort


int temp[]=new int[arr1.length];
for(int i=0;i<arr1.length;i++){
temp[i]=arr1[arr1.length-1-i];
}
System.out.println("After Selection Sort");
for(int i:temp){
System.out.print(i+" ");
}
}
}

Page 94
Variable descriptor Table:
Variable Name Variable Type Use
arr int array The array to be used to
store the values.
i int iteration variable of the
outer loop
j int iteration variable of the
inner loop
tmp int temporary variable for
swapping the values
smaller int stores the smallest
value in the subarray
temp int array temporary array to
store the value of the
original array .

Page 95
Output:

Page 96
Question 7: Vectors are physical quantities(like force,
momentum,velocity) whose representation requires
both magnitude and direction for complete expression
of information. They are of the form
where x,y,z are the magnitudes of the quantity along
x, y and z respectively. And i,j,k express the direction
along x,y,z respectively.Take two inputs from the user
and add them. Display the resultant vector and it’s
magnitude.

Algorithm:
1. Create a class and import java.util.*.
2. Create three integer arrays of size 3.
3. One will be the first vector.
4. Another will the second vector and the last one will be the
resultant.
5. Input the first two vectors using for loop and Scanner
class.
6. The x component of the resultant vector can be found by
adding the x components of the input vectors.
7. Same will be done for all the components(x,y and z) of
the resultant vector.
8. The magnitude of the resultant vector can be found using
the formula:
magnitude=√{(x component)2 + (y component)2+ (z component)2}
9. Display the result using System.out.println();

Page 97
Code:
import java.util.*;
public class vectadd{
public static void main(){
Double v1[]=new Double[3];
//the three array elements are the magnitudes of the array along x,y
and z axes respectively
Double v2[]=new Double[3];
inputarr(v1);
inputarr(v2);
Double res[] = new Double[3];
res[0]=v1[0]+v2[0];
res[1]=v1[1]+v2[1];
res[2]=v1[2]+v2[2];

printvect(v1,"V1");
printvect(v2,"V2");
printvect(res,"Result");
Double mag=Math.sqrt(res[0]*res[0]+res[1]*res[1]+res[2]*res[2]);
System.out.println("Magnitude of resultanty is:"+mag);
}

public static void inputarr(Double arr[]){


for(int i=0;i<3;i++){
System.out.println("Enter the x,y and z coordinates for the
vector=>");
arr[i]=new Scanner(System.in).nextDouble();
}
}
public static void printvect(Double arr[],String nameOfVector){
System.out.println("The value of vector "+nameOfVector+" is:
"+arr[0]+"i+"+arr[1]+"j+"+arr[2]+"k");;
}
}

Page 98
Variable descriptor Table:
Variable Name Variable Type Use
v1 Double array The array to be used to
store the first vector
v2 Double array The array to be used to
store the second vector
res Double array The array to be used to
store the resultant
vector
i int iteration variable
mag Double stores the magnitude of
resultant vector

Page 99
Output:

Page 100
Question 8: Vectors are physical quantities(like force,
momentum,velocity) whose representation requires
both magnitude and direction for complete expression
of information. They are of the form
where x,y,z are the magnitudes of the quantity along
x, y and z respectively. And i,j,k express the direction
along x,y,z respectively.Subtract the vector and show
the resultant vector and its magnitude.

Algorithm:
1. Create a class and import java.util.*.
2. Create three integer arrays of size 3.
3. One will be the first vector.
4. Another will the second vector and the last one will be the
resultant.
5. Input the first two vectors using for loop and Scanner
class.
6. The x component of the resultant vector can be found by
Subtracting the x components of the input vectors.
7. Same will be done for all the components(x,y and z) of
the resultant vector.
8. The magnitude of the resultant vector can be found using
the formula:
magnitude=√{(x component)2 + (y component)2+ (z component)2}
9. Display the result using System.out.println();

Page 101
Code:
import java.util.*;
public class vectsub{
public static void main(){
Double v1[]=new Double[3];
//the three array elements are the magnitudes of the array along x,y
and z axes respectively
Double v2[]=new Double[3];
inputarr(v1);
inputarr(v2);
Double res[] = new Double[3];
res[0]=v1[0]-v2[0];
res[1]=v1[1]-v2[1];
res[2]=v1[2]-v2[2];

printvect(v1,"V1");
printvect(v2,"V2");
printvect(res,"Result");
Double mag=Math.sqrt(res[0]*res[0]+res[1]*res[1]+res[2]*res[2]);
System.out.println("Magnitude of resultanty is:"+mag);
}
public static void inputarr(Double arr[]){
for(int i=0;i<3;i++){
System.out.println("Enter the x,y and z coordinates for the
vector=>");
arr[i]=new Scanner(System.in).nextDouble();
}
}
public static void printvect(Double arr[],String nameOfVector){
System.out.println("The value of vector "+nameOfVector+" is:
"+arr[0]+"i+"+arr[1]+"j+"+arr[2]+"k");;
}
}

Page 102
Variable descriptor Table:
Variable Name Variable Type Use
v1 Double array The array to be used to
store the first vector
v2 Double array The array to be used to
store the second vector
res Double array The array to be used to
store the resultant
vector
i int iteration variable
mag Double stores the magnitude of
resultant vector

Page 103
Output:

Page 104
Question 9: To convert a string to char Array.
Algorithm:
1. Create a class and import java.util.*.
2. In the main function input the String from the user using
Scanner Class
3. The String will be converted to char array using a for loop
and using the chartAt() function. During every iteration the
following statement will be executed: ch[i]=str.charAt(i);
4. The size of the char Array will be equal to str.length();
5. The elements of the char Array will be printed using for loop
and System.out.print();
Code:
import java.util.*;

public class StringToCharArray {

public static void main(String args[])


{ System.out.print("Enter a String: ");
String str = new Scanner(System.in).nextLine();
char[] ch = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
ch[i] = str.charAt(i);
}
for (char c : ch) {
System.out.print(c+",");
}
}
}

Page 105
Variable descriptor Table:
Variable Name Variable Type Use
ch char array The array to store the
characters of the string
str String The String to work on.
i int iteration variable

Page 106
Output:

Page 107
Question 10: To create a 2D array and accept input from
user to fill the array. After that add 56 to each element of
the
Algorithm:
1. Create a class and import java.util.*.
2. Create a scanner object to take inputs from the user
3. Use two for loops one nested in the other to take inputs from
the user using the function Scanner(System.in).nextInt() and
assign the values to the elements of the 2D array.
4. After assigning the values in the loop itself , in each iteration
add 56 to the elements.
5. Print the original array and the previous array using nested
for loops and System.out.println();

Code:
import java.util.Scanner;

public class Matrix1 {

public static void readMatrixByUser()


{
int m, n, i, j;
Scanner in = null;
try {
in = new Scanner(System.in);
System.out.println("Enter the number "
+ "of rows of the matrix");
m = in.nextInt();
System.out.println("Enter the number "
+ "of columns of the matrix");
n = in.nextInt();

// Declare the matrix


int first[][] = new int[m][n];

// Read the matrix values


System.out.println("Enter the elements of the matrix");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
first[i][j] = in.nextInt()+56;

// Display the elements of the matrix

Page 108
System.out.println("Elements of the matrix are");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++)
System.out.print(first[i][j] + " ");
System.out.println();
}
}
catch (Exception e) {
}
finally {
in.close();
}
}

// Driver code
public static void main(String[] args)
{
readMatrixByUser();
}
}

Variable descriptor Table:


Variable Name Variable Type Use
first int array The 2D array to work
on
i,j int iteration variables
m int To store the no. of rows
in the matrix
n int To store the number of
columns in the matrix.

Page 109
Output:

Page 110
Question 11: To create a 2D array and accept input from
user to fill the array. After that subtract 34 from each
element of the
Algorithm:
1. Create a class and import java.util.*.
2. Create a scanner object to take inputs from the user
3. Use two for loops one nested in the other to take inputs from
the user using the function Scanner(System.in).nextInt() and
assign the values to the elements of the 2D array.
4. After assigning the values in the loop itself , in each iteration
subtract from the elements.
5. Print the original array and the previous array using nested
for loops and System.out.println();

Code:
import java.util.Scanner;

public class Matrix2 {

public static void readMatrixByUser()


{
int m, n, i, j;
Scanner in = null;
try {
in = new Scanner(System.in);
System.out.println("Enter the number "
+ "of rows of the matrix");
m = in.nextInt();
System.out.println("Enter the number "
+ "of columns of the matrix");
n = in.nextInt();

// Declare the matrix


int first[][] = new int[m][n];

// Read the matrix values


System.out.println("Enter the elements of the matrix");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
first[i][j] = in.nextInt()-34;

// Display the elements of the matrix

Page 111
System.out.println("Elements of the matrix are");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++)
System.out.print(first[i][j] + " ");
System.out.println();
}
}
catch (Exception e) {
}
finally {
in.close();
}
}

// Driver code
public static void main(String[] args)
{
readMatrixByUser();
}
}

Variable descriptor Table:


Variable Name Variable Type Use
first int array The 2D array to work
on
i,j int iteration variables
m int To store the no. of rows
in the matrix
n int To store the number of
columns in the matrix.

Page 112
Output:

Page 113
Question 12: To create two 2D arrays and check whether
the two matrices are equal.

Algorithm:
1. Create a class and import java.util.*.
2. Create two 2d arrays and assign arbitrary values to the
elements of the two 2D arrays.
3. To check whether the matrices are equal check whether each
element of first matrix is equal to the corresponding elements
of the other matrix using a nested for loop in other nested for
loop.(For horizontal and vertical elements)
4. Print the results using System.out.println();

Page 114
Code:
public class EqualMatrix
{
public static void main(String[] args) {
int row1, col1, row2, col2;
boolean flag = true;

//Initialize matrix a
int a[][] = {
{1, 2, 3},
{8, 4, 6},
{4, 5, 7}
};

//Initialize matrix b
int b[][] = {
{1, 2, 3},
{8, 4, 6},
{4, 5, 7}
};

//Calculates the number of rows and columns present in the


first matrix

row1 = a.length;
col1 = a[0].length;

//Calculates the number of rows and columns present in the


second matrix

row2 = b.length;
col2 = b[0].length;

//Checks if dimensions of both the matrices are equal


if(row1 != row2 || col1 != col2){
System.out.println("Matrices are not equal");
}
else {
for(int i = 0; i < row1; i++){
for(int j = 0; j < col1; j++){
if(a[i][j] != b[i][j]){
flag = false;
break;
}
}
}

if(flag)
System.out.println("Matrices are equal");
else
System.out.println("Matrices are not equal");

Page 115
}
}
}

Variable descriptor Table:


Variable Name Variable Type Use
a int array The first 2D array to
work on
b int The second 2D array to
work on
row1,col1 int To store the no. of rows
and columns of the first
matrix
row2,col2 int To store the no. of rows
and columns of the
second matrix

Page 116
Output:

Page 117
Question 13: To create two arrays and check whether the
two arrays are equal.

Algorithm:
1. Create a class and import java.util.*.
2. Create two arrays and assign arbitrary values to the
elements of the two arrays.
3. To check whether the arrays are equal check whether each
element of first array is equal to the corresponding elements
of the other array using a for-loop.
4. Print the results using System.out.println();

Code:
import java.io.*;
import java.util.*;

class ArrayEquals{
// Returns true if arr1[0..n-1] and arr2[0..m-1]
// contain same elements.
public static boolean areEqual(int arr1[], int arr2[])
{
int n = arr1.length;
int m = arr2.length;

// If lengths of array are not equal means


// array are not equal
if (n != m)
return false;

// Sort both arrays


Arrays.sort(arr1);
Arrays.sort(arr2);

// Linearly compare elements


for (int i = 0; i < n; i++)
if (arr1[i] != arr2[i])
return false;

// If all elements were same.


return true;
}

// Driver code
public static void main(String[] args)
{

Page 118
int arr1[] = { 3, 5, 2, 5, 2 };
int arr2[] = { 2, 3, 5, 5, 2 };

if (areEqual(arr1, arr2))
System.out.println("Yes");
else
System.out.println("No");
}
}

Variable descriptor Table:


Variable Name Variable Type Use
arr1 int array The first array to work
on
arr2 int The second array to
work on
m int To store the no. of
elements the in first
matrix
n int To store the no.
elements in the second
matrix

Page 119
Output:

Page 120
Question 13: To create an array of 10 elements take input
from to fill it, and multiply each element of the array by the
fifth element.

Algorithm:
1. Create a class and import java.util.*.
2. Create a Scanner Class to take inputs from the user.
3. Fill the array with inputs from the user by using a for loop
and traversing through the entire array and assigning the
values using the Scanner(System.in).nextInt();
4. Store the value of fifth variable in a temporary variable.
5. Multiply all the elements of the array by the temporary
variable using a for-loop similar to the one used in Step 3.
6. Display the results using a for-loop and System.out.println()
function.

Code:
import java.util.*;
public class ArrayMult{
public static void main(){
int arr[]=new int[10];
for(int i=0;i<10;i++){
arr[i]=new Scanner(System.in).nextInt();
}
System.out.println("Before multiplying");
System.out.println("");
for(int i=0;i<10;i++){
System.out.print(arr[i]+",");
}
int mul = arr[4];
for(int j=0;j<10;j++){
arr[j]=arr[j]*mul;//arr[4] is the fifth element
}
System.out.println("");
System.out.println("After multiplying every element with the 5th
element");
System.out.println("");
for(int i=0;i<10;i++){
System.out.print(arr[i]+",");
}
}}

Page 121
Variable descriptor Table:
Variable Name Variable Type Use
arr int array The array to work on
mul int The temporary value
which stores the value
of the fifth element for
multiplying each
element by the fifth
element.
i int iteration variable
j int iteration variable

Page 122
Output:

Page 123
Question 14:To implement an array whose size can be
increased during runtime.

Algorithm :
1. Create a class and import java.util.*.
2. Declare an array as the data member of the class.
3. The class will have a function increaseSize(int n). Here ‘ n’ is
the number of elements to be added to the array.
4. The increase size function will create a temporary array
temp. Then the temporary array will be set equal to original
array. This will store all the values of the original array in
the temporary array. Then the original array will be
reinitialized to an array with the size=previous size+n(
where n is the parameter of the function )
5. Now the size of the array has been increased but the data has
been lost. Using a for loop transfer all the data from the
temporary array to the original resized array.
6. The array has been resized properly now.
7. Write a main function to drive the functionalities of the class

Code:
import java.util.*;
public class DynamicArray
{ static int size;
static int arr[];
public static void main(){
arr=new int[4];
int i=0;
for(i=0;i<arr.length;i++){
arr[i]=new Scanner(System.in).nextInt();}
size=arr.length;
//adding more elements to the array...
increasesize(2);
//adding more values to the newly expanded array
arr[4]=999;
arr[5]=9999;
System.out.println("");
for(int j=0;j<arr.length;j++){
System.out.print(arr[j]+",");
}

Page 124
private static void increasesize(int n){

int temp[] = arr;

arr=new int[temp.length+n];
for(int i=0;i<size;i++){
arr[i]=temp[i];
}
size=temp.length+n;

temp=null;
}
}

Variable descriptor Table:


Variable Name Variable Type Use
arr int array The array to work on
temp int array The temporary array to
store the data when the
original array is being
reinitialized
i int iteration variable
n int No. of extra elements to
be added to the array.

Page 125
Output:

Page 126
Question 15: To check whether a null matrix. A null matrix
mathematics is 2D array of real numbers in which each
number is 0.

Algorithm :
1. Create a class and import java.util.*.
2. Create an instance of scanner class.
3. Create a function readMatrixByUse() which will take the
inputs from the user to fill the array. First take the number of
rows and the number of columns. Then input all the elements
using two for-loops one nested within the another loop and
during the input itself check whether each of the elements are
0 or not.
4. If an element is not zero set the flag to 5. flag is an integer
declared with the initial value 0.
5. In the main function after calling the readMatrixByUser()
function, check whether flag is 5 or 0 and then display the
results accordingly using System.out.println().

Code:
import java.util.Scanner;

public class nullmat {


static int flag;

public static void readMatrixByUser()


{
int m, n, i, j;
Scanner in = null;
try {
in = new Scanner(System.in);
System.out.println("Enter the number "
+ "of rows of the matrix");
m = in.nextInt();
System.out.println("Enter the number "
+ "of columns of the matrix");
n = in.nextInt();

Page 127
// Declare the matrix
int first[][] = new int[m][n];

// Read the matrix values


System.out.println("Enter the elements of the matrix");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
first[i][j] = in.nextInt();
for (i = 0; i < m; i++){
for (j = 0; j < n; j++){
if(first[i][j]!=0){
flag=5;
}
}
}
// Display the elements of the matrix
System.out.println("Elements of the matrix are");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++)
System.out.print(first[i][j] + " ");
System.out.println();
}
}
catch (Exception e) {
}
finally {
in.close();
}
}

// Driver code
public static void main(String[] args)
{

readMatrixByUser();
if(flag!=5){
System.out.println("The matrix obtained is a null matrix");
}else{System.out.println("The matrix obtained is not a null
matrix");}
}
}

Page 128
Variable descriptor Table:
Variable Name Variable Type Use
first int array The 2D array to work
on
i,j int iteration variables
m int To store the no. of rows
in the matrix
n int To store the number of
columns in the matrix.
flag int flag variable whose
value is 5 if the matrix
is not a null matrix and
the value is 0 if the
matrix is null matrix.

Page 129
Output:

Page 130
Topic-5: Number Programs
Question 1: Write a program to find the value of e(Euler’s
number) using Java.
Code:
public class EulerNumber {

public static void main(String[] args) {


System.out.println("e = " + Euler());
}

private static double Euler() {


double e=1;
double f=1;
for ( int i=1; i <= 1000; i++) {
f = f * (1.0 / i);
if ( f == 0 ) break;
e += f;
}
return e;
}
}

Algorithm:
1. Create the class EulerNumber containing the main function and a
function named Euler with return type double.
2. Use the series expansion of Euler’s number in a function named
Euler. Implement this using a for loop.
3. In the main function call euler function and print the integer that is
returned by the function euler.

Page 131
Variable descriptor Table:
Variable Name Variable Type Use
e Double To store value of euler’s
number
f Double To store the value of
1/n!

Output:

Page 132
Question 2: Write a program to find the value of π (Pi) using
Java.

Algorithm:
1. Create the class pi and write the main function.
2. Pi is defined by the series
3. Implement the above formula in the form of a “for-loop” updating
the value of pi every time the program is executed. Run the loop a
large number of times for a more accurate value of (Say 9,999
times.) The more number of times, the loop is executed , the greater
will be the accuracy of the value of obtained.
4. Display the value of pi after every iteration to verify if the profram
is running correctly using System.out.println().
5. Finally display the final value of using System.out.println().

Code:
public class pi
{
public static void main(){
double pi=0;
double sign=2;

for(double a=1;a<99999;a++){
if(sign%2==0){
pi=pi+(1/((2*a)-1));
}else
{pi=pi-(1/((2*a)-1));}
System.out.println("The value of pi after "+a+" steps is:
"+(pi*4));
sign++;
}
System.out.println("");

Page 133
System.out.println("");
System.out.println("");
System.out.println("The final value of pi is :"+(pi*4));

}
}

Variable descriptor Table:


Variable Name Variable Type Use
a Double Iteration variable to
generate consecutive
odd numbers for the
series to work.
pi Double To store the value of

Page 134
Output:

Page 135
Question 3: Write a program in Java to check wheter a number
is Circular Prime Number or not.

Algorithm:
1. Create a class with three functions, boolean isPrime(int n), boolean
checkCricular(int n) and the main function.
2. A circular prime number is a number which is prime and the
circular permutations of its digits are also prime. The function
isPrime(int n) will use a for loop to generate all the numbers smaller
than the test number to check whether the number entered as the
parameter of the function is Prime or Composite number using a”
for-loop” construct.
3. The function boolean checkCircular(int n) will create all the
permutations if the digits of the number entered by the user to check
whether they are prime by calling the isPrime(int n) function.
4. The main function will drive the entire program by calling the
checkCircular(int n) function.
5. The final result will be displayed using System.out.println()
function.

Code:

class KJ
{

static boolean isPrime(int n)


{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;

// This is checked so that we can skip


// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;

for (int i = 5; i * i <= n; i = i + 6)


if (n % i == 0 || n % (i + 2) == 0)
return false;

return true;

Page 136
}

// Function to check if the number is circular


// prime or not.
static boolean checkCircular(int N)
{
// Count digits.
int count = 0, temp = N;
while (temp>0) {
count++;
temp /= 10;
}

int num = N;
while (isPrime(num)) {

// Following three lines generate the next


// circular permutation of a number. We
// move last digit to first position.
int rem = num % 10;
int div = num / 10;
num = (int)((Math.pow(10, count - 1)) * rem)
+ div;

// If all the permutations are checked and


// we obtain original number exit from loop.
if (num == N)
return true;
}

return false;
}

// Driver Program
public static void main (String[] args)
{
int N = 1193;
if (checkCircular(N))
System.out.println("Yes");
else
System.out.println("No");
}
}

Page 137
Variable descriptor Table:
Variable Name Variable Type Use
n int Parameter for the
function boolean
isPrime(int n)
N int Parameter for the
function boolean
checkCircular(int N)
temp int Temporary variable
count int To store the number the
digits.
rem int To store remainder
div int To store the result of
division

Page 138
Output:

Page 139
Question 4: Swap two integer type variables without using a
third temporary variable.

Algorithm:
1. Create a class Swap with the main function.
2. Declare and initialize two integers x and y.
3. x=x+y ….. Eqn 1
4. y=x-y This will put the value of x in y.
5. x=x-y This will put the value of y in x.

Code:
class KJ{

public static void main(String a[])


{
int x = 10;
int y = 5;
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swaping:"
+ " x = " + x + ", y = " + y);
}
}

Variable descriptor Table:


Variable Name Variable Type Use
x int First test number to
swap
y int Second test number to
swap

Page 140
Output:

Page 141
Question 5: Convert decimal number to binary.

Algorithm:
1. Create a class DecimalB
2. Divide the number to convert by the base of the binary system ie.
2 again and again until 0 is obtained and store the remainders
obtained in an integer array.
3. Display the remainders in reverse order in the form of a number
4. The number thus obtained is the binary equivalent of the original
number

Code:
public class DecimalB{
public static void toBinary(int decimal){
int binary[] = new int[40];
int index = 0;
while(decimal > 0){
binary[index++] = decimal%2;
decimal = decimal/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
System.out.println();//new line
}
public static void main(String args[]){
System.out.println("Decimal of 10 is: ");
toBinary(10);
System.out.println("Decimal of 21 is: ");
toBinary(21);
System.out.println("Decimal of 31 is: ");
toBinary(31);
}}

Variable descriptor Table:


Variable Name Variable Type Use
decimal int To store the value of the
decimal number
Binary[] Int array To store the value of the
binary number in the
form of an array

Page 142
Output:

Page 143
Question 6: Convert decimal number to octal number.

Algorithm:
1. Create a class DecimalO.
2. Divide the decimal number by 8 again and again until you get 0
as the result of division.
3. Store the remainders obtained in an Array
4. Display the numbers in the array in reverse order.(MSB to LSB)
5. The number obtained is the octal representation of the original
number

Code:
class DecimalO
{

static void decToOctal(int n)


{
// array to store octal number
int[] octalNum = new int[100];

// counter for octal number array


int i = 0;
while (n != 0)
{
// storing remainder in octal array
octalNum[i] = n % 8;
n = n / 8;
i++;
}

for (int j = i - 1; j >= 0; j--)


System.out.print(octalNum[j]);
}

// driver program
public static void main (String[] args)
{
int n = 33;
decToOctal(n);
}
}

Page 144
Variable descriptor Table:
Variable Name Variable Type Use
n int To store the value of the
decimal number
octalNum[] Int array To store the value of the
binary number in the
form of an array

Output:

Page 145
Question 7: Program to check for a valid IMEI number.

Algorithm:
1. Starting from the rightmost digit, double the value of every second digit
(e.g., 7 becomes 14).
2. If doubling of a number results in a two digits number i.e greater than
9(e.g., 7 × 2 = 14), then add the digits of the product (e.g., 14: 1 + 4 = 5),
to get a single digit number.
3. Now take the sum of all the digits.
4. Check if the sum is divisible by 10 i.e.(total modulo 10 is equal to 0) then
the IMEI number is valid; else it is not valid.

Code:
import java.io.*;
class IMEI
{
// Function for finding and returning
// sum of digits of a number
static int sumDig(int n)
{
int a = 0;
while (n > 0)
{
a = a + n % 10;
n = n / 10;
}
return a;
}

static boolean isValidIMEI(long n)


{
// Converting the number into String
// for finding length
String s = Long.toString(n);
int len = s.length();

if (len != 15)
return false;

int sum = 0;
for (int i = len; i >= 1; i--)
{
int d = (int)(n % 10);

// Doubling every alternate digit


if (i % 2 == 0)
d = 2 * d;

Page 146
// Finding sum of the digits
sum += sumDig(d);
n = n / 10;
}

return (sum % 10 == 0);


}

// Driver code
public static void main(String args[]) throws IOException
{
// 15 digits cannot be stored in 'int' data type
long n = 490154203237518L;

if (isValidIMEI(n))
System.out.println("Valid IMEI Code");
else
System.out.println("Invalid IMEI Code");

}
}

Variable descriptor Table:


Variable Name Variable Type Use
n int
octalNum[] Int array To store the value of the
binary number in the
form of an array

Page 147
Question 8: Program to check whether a number is a pronic
number or not. A pronic number is number which is the product
of any two consecutive numbers. For Eg.
20=4*5;30=5*6;12=3*4 etc.

Algorithm:
1. Create a class and write down the main function.
2. Define an integer and initialize it with some positive arbitrary value.
3. Create a for loop and iterate a number i(iteration variable) from o
to the number which needs to be checked.
4. During every iteration check whether i*(i+1) is equal to the integer
we are checking for.
5. If some value of I satisfying the above condition is found then the
number is a pronic number. Otherwise the number is not a pronic
number.
6. Display the results using System.out.println();

Code:
public class pronicnumber{
public static void kj(){
int a =30;int check =0;
for(int i=2;i<a;i++){
if((i*(i-1))==a){
System.out.println("Pronic number found"+" Factors are"+i+"and"+(i-
1));check =1;}
}
if(check==0){System.out.println("Not pronic number");}
}

Page 148
Variable descriptor Table:
Variable Name Variable Type Use
a int the number to be
checked
check Int flag variable. If it is set
to one by the loop, then
th number is pronic. If
it is zero then the
number is not pronic

Output:

Question 9: To check whether a number is a palindrome. A


palindrome number is a number which remains the same even
when its digits are reversed.

Page 149
Algorithm:
1. Create a class and write down the main function.
2. Declare an integer an initialize it with some random positive value.
3. Create two temporary variables which will store the value of the
original number. We will work on the temporary variables to
privent the original number from being modified.
4. To count the number of digits in the number. The following while
loop is to be used:
i. while(temporaryvariable1>0){
ii. temporaryvariable1=temporaryvariable1/10;
iii. ++countervariable;
iv. }
5. Now reverse the number using and store it in an integer type
variable rev. Use the following algorithm for the reversal:
i. for(int i=0;i<countervariable;i++){
ii. rev=rev*10+(temporaryvariable2%10);
iii. temporaryvariable2=temporaryvariable/10;
iv. }
6. Compare the values of the original unmodified number and the
reversed number.
7. If the values are equal, then the number is a palindrome number.

Code:
public class Palindromint
{
public static void main(){
int a =122231;
int b=a;int c=a;
int rev=0;
int count=0;
while(b!=0){
b=b/10;
++count;
}
for(int i=0;i<count;i++){
rev=rev*10+(c%10);
c=c/10;
}
if(rev==a){
System.out.println("The Number is palidrome ");
}else{System.out.println("The number is not palindrome");}
}
}

Page 150
Variable descriptor Table:
Variable Name Variable Type Use
a int the number to be
checked
b,c Int temporary variables to
perform calculations
on.
rev int to store the reversed the
number.

Output:

Page 151
Question 10: To check whether a number is a magic naumber.
A magic number is a number whose sum of the digit till only
one digit left is 1. For eg 37,28,55 etc.

Algorithm:
1. Create a class and write down the main function.
2. (Any Magic number – 1) is always a multiple of 9. This happens
because when a number’s digits are recursively added to obtain a
single digit number and the number is a multiple of 9 ,then the
recursive sum is always 9. And 10 is a magic number. Thus every
number of the form (9*m+1) is a magic number according to the
Euclid’s division lemma.
3. Thus for a number if (Number%9==1) is true, then the number is a
magic number.
4. This is the shortest way to solve a program of magic number.
5. Magic number can also be checked by finding the recursive sum of
the digits but finding remainder after division by 9 is a smaller
method.
6. Display the results using System.out.println();

Code:
import java.util.*;
public class magicmint{
public static void main(){
int a = new Scanner(System.in).nextInt();
if(a%9==1){System.out.println("The number enetered is a Magic
number");}
else{
System.out.println("Not a magic Number");
}
}
}
Variable descriptor Table:
Variable Name Variable Type Use
a int the number to be
checked

Page 152
Output:

Page 153
Question 11: To check whether a number is a Harshad
Number. Harshada means “Joy Giving” in Sanskrit. They
were invented by Indian Mathematician D. R. Kaprekar.
These are numbers divisible by the sum of their digits. Write
a program in JAVA to check whether a number is a Harshad
Number.
Algorithm:
1. Create a class and write down the main function.
2. Create an integer type variable and assign some arbitrary value to
it. Create a temporary variable to store the value of our original
number for calculation purposes.
3. Find the sum of the digits of the number than using a for loop and
the % operator.
4. Now Use the % operator to check whether Originalnumber%sum is 0
or not.
5. If it is 0 then the number is harshad number.
6. If it is not zero then it is not harshad number.

Code:

public class HarshadNumber


{
public static void main(String[] args) {
int num = 156;
int rem = 0, sum = 0, n;

//Make a copy of num and store it in variable n


n = num;

//Calculates sum of digits


while(num > 0){
rem = num%10;
sum = sum + rem;
num = num/10;
}

//Checks whether number is divisible by sum of digits


if(n%sum == 0)
System.out.println(n + " is a harshad number");

Page 154
else
System.out.println(n + " is not a harshad number");
}

Variable descriptor Table:


Variable Name Variable Type Use
num int the number to be
checked
sum int to store the sum of the
digits
rem int to store the remainder.

Output:

Page 155
Question 11: Write a program to count the number of digits in
a number.

Algorithm:
1. Create a class and write down the main function.
2. Create an integer type variable and assign some arbitrary value to
the variable.
3. To find the number of digits we will use a while loop. We will define
a variable count which will store the no. of digits.It will be
incremented each time the loop is executed .The array will be as
follows:
i. while(num!=0){
ii. num=num/10’
iii. ++count;
iv. }
4. Print the final answer using System.out.println();

Page 156
Code:
public class numdigit{
public static void main(){
int a =2333313;int b=a;
int count=0;
while(a!=0){
a=a/10;
++count;
}
System.out.println("The number of digits in "+b+" is: "+count);
}
}

Variable descriptor Table:


Variable Name Variable Type Use
a int the number to be
checked
b int temporary variable to
store the value of the
original number for
calcualations
count int to store the number of
digits.

Output:

Page 157
Question 12: Write a program to store a number in array .

Algorithm:
1. Create a class and write down the main function.
2. Create an integer type variable and assign some arbitrary value to
the variable.
3. Write the code to find the number of digits in the number using a
while loop and a counter variable as follows:
i. while(num!=0){
ii. num=num/10’
iii. ++count;
iv. }
4. Store the digits of the number in a array of the size count. Use for-
loop and % function to transfer the digits of the number to the array.
5. Use the following code in the loop:
i. for(int i=(count-1);i>-1;i--){
ii. arr[i]=c%10;
iii. c=c/10;
iv. }
6. Display the results using for loop and System.out.println() function.

Code:
public class arrmint
{
public static void main(){
int a=1231123;
int b=a;int c=a;
int count=0;
while(b!=0){
b=b/10;
++count;
}
int arr[]=new int[count];
for(int i=(count-1);i>-1;i--){
arr[i]=c%10;
c=c/10;
}
for(int i=0;i<count;i++){
System.out.print(arr[i]+",");
}
}
}

Page 158
Variable descriptor Table:
Variable Name Variable Type Use
a int the number to be
checked
b,c int temporary variable to
store the value of the
original number for
calcualations
count int to store the number of
digits.
arr int array integer array to store
the digits of the number
i int iteration variable for
the loops

Output

Page 159
Question 13: Write a program to multiply two numbers
WITHOUT using the * operator.
Algorithm:
1. Create a class and write down the main function
2. Now we know that multiplication is repeated addition
3. If the two numbers to be multiplied are “a” and “b”, using a for loop
add “a” to itself “b” times and the store the result in a variable called
prod.
4. The value of prod is the value which will be obtained after
multiplying a and b.
5. Display the results using System.out.println();

Code:

public class multimint


{ public static void main(){
int a=10;
int b=12;
int prod=0;
for(int i=0;i<b;i++){
prod=prod+a;
}
System.out.println(a+"x"+b+"="+prod);
}}

Page 160
Variable descriptor Table:
Variable Name Variable Type Use
a int The first operand for
multiplication
b int The second operand for
multiplication
prod int the result of
multiplication
i int iteration variable

Output

Page 161
Question 14: Write a program to divide two numbers
without using the / operator.
Algorithm:
1. Create a class and write down the main function
2. Now we know that division is repeated subtraction
3. A loop will be created and the second number should be subtracted
from the first number till the first number becomes less than 0.
4. The answer of division is the no. of times the second number was
subtracted from the first number
5. Display the results using System.out.println();
Code:
public class divimint{
public static void main(){
int a =12;
int c=a;
int b=6;
int qoutient=0;
while(c>0){
c=c-b;
++qoutient;
}
System.out.println(a+"/"+b+"="+qoutient);
}
}

Variable descriptor Table:


Variable Name Variable Type Use

Page 162
a int The first operand for
division
b int The second operand for
division
quotient int the result of division
i int iteration variable

Output

Page 163
Topic-6: String Program
Question 1: To convert a string to char Array.
Algorithm:

1. Create a class and import java.util.*.


2. In the main function input the String from the user using
Scanner Class
3. The String will be converted to char array using a for loop
and using the chartAt() function. During every iteration the
following statement will be executed: ch[i]=str.charAt(i);
4. The size of the char Array will be equal to str.length();
5. The elements of the char Array will be printed using for loop
and System.out.print();
Code:
import java.util.*;

public class StringToCharArray {

public static void main(String args[])


{ System.out.print("Enter a String: ");
String str = new Scanner(System.in).nextLine();
char[] ch = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
ch[i] = str.charAt(i);
}
for (char c : ch) {
System.out.print(c+",");
}
}
}

Page 164
Variable descriptor Table:
Variable Name Variable Type Use
ch char array The array to store the
characters of the string
str String The String to work on.
i int iteration variable

Output:

Page 165
Question 2: To reverse a string using char Array.
Algorithm:
1. Create a class and import java.util.*.
2. In the main function input the String from the user using
Scanner Class
3. The String will be converted to char array using a for loop
and using the chartAt() function. During every iteration the
following statement will be executed: ch[i]=str.charAt(i);
4. The size of the char Array will be equal to str.length();
5. Create a temporary array and fill it from backward of the
original array using a loop to obtain a reversed char array
6. Print the result using a for loop and System.out.println();

Code:
import java.util.*;

public class StringReverseCharArray {

public static void main(String args[])


{ System.out.print("Enter a String: ");
String str = new Scanner(System.in).nextLine();
char[] ch = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
ch[i] = str.charAt(i);

}
char temp[]=new char[ch.length];
for(int i=0;i<temp.length;i++){
temp[i]=ch[temp.length-1-i];}

for (char c : temp) {


System.out.print(c+",");
}
}
}

Page 166
Variable descriptor Table:
Variable Name Variable Type Use
ch char array The array to store the
characters of the string
str String The String to work on.
i int iteration variable

Output:

Page 167
Question 3: To reverse a string without using char
Array.
Algorithm:
1. Create a class and import java.util.*.
2. Write the main function
3. In the main function input the String from the user using
Scanner Class
4. Now convert the string to a string builder object.
5. Use the stringbuiler’s reverse() function top reverse the
function.

Code:
import java.lang.*;
import java.io.*;
import java.util.*;

// Class of ReverseString
class ReverseString {
public static void main(String[] args)
{
String input = new Scanner(System.in).nextLine();

StringBuilder input1 = new StringBuilder();

// append a string into StringBuilder input1


input1.append(input);

// reverse StringBuilder input1


input1 = input1.reverse();

// print reversed String


System.out.println(input1);
}
}

Page 168
Variable descriptor Table:
Variable Name Variable Type Use
input1 String The string to store the
input form the user.

Output

Page 169
Question 4: To check whether a string is palindrome or
not.
Algorithm:
1. Create a class and import java.util.*.
2. Write the main function
3. In the main function input the String from the user using
Scanner Class.
4. Reverse the string using a for loop and the charAt(int a)
function and check whether the initial and final strings are
equal or not
5. If the initial and the final strings are equal then the string is
a palindrome.
Code:

import java.util.*;

public class Palindroma {

public static void main(String[] args)


{
String a=new Scanner(System.in).nextLine();
String rev="";
a=a.toUpperCase();
for(int i=0;i<a.length();i++){
rev=rev+a.charAt(a.length()-i-1);
}
System.out.println(rev);
if(a.equals(rev)){System.out.print("The string entered was
Palindrome");}else{System.out.print("The string entered was NOT
Palindrome");}

Page 170
Variable descriptor Table:
Variable Name Variable Type Use
a String The string to be checked
i int iteration variable
rev String The reversed string

Output:

Page 171
Question 5: To extract words from a sentence input
from the user in the form of a string.
Algorithm:
1. Create a class and import java.util.*.
2. Write the main function.
3. Use the Scanner class to take input String from the user.
4. Use the String.split() to split the string by the spaces in the
string and store the result in a String Array.
5. The String Array contains an array of all the words of the
sentence.
6. Display the results using a for loop and System,out.println()
function

Code:
import java.util.*;
public class SentenceToWordArray
{
public static void main(){
String sentence= new Scanner(System.in).nextLine();
String[] wordarray = sentence.split("\\s");
System.out.print("The array of words is: {");
for(int i=0;i<wordarray.length;i++){
System.out.print(wordarray[i]+",");
}System.out.print("}");
}
}

Page 172
Variable descriptor Table:
Variable Name Variable Type Use
sentence String The string to store the
sentence
wordarray String array The array to store the
words of the sentence
separately
i int iteration variable

Output

Page 173
Question 6: To extract words from a sentence input
from the user in the form of a string. After extracting
the words store them in an array and short them in
alphabetical order.
Algorithm:
1. Create a class and import java.util.*.
2. Write the main function.
3. Input a string sentence from the user using the Scanner class.
4. Convert the string sentence into an array of words using
string.split() function.
5. Now use the Selection short algorithm which works on
dividing the array into sub arrays and finding the smallest
value in the subarray.
6. To compare the strings use the String1.compare(String2) to
compare the strings while sorting.
7. Display the results using for loop and System.out.println()

Code:
import java.util.*;
public class StringShot{
public static void main(){
String sent = new Scanner(System.in).nextLine();
String[] a = sent.split("\\s");
sort(a);
System.out.print("Sorted Array::");
for(int k=0;k<a.length;k++)System.out.print(a[k]+",");
}
public static void sort(String[] a) {
for(int i=0;i<(a.length-1);i++){
for(int j=i+1;j<a.length;j++){
if(a[i].compareTo(a[j])>0){

Page 174
String tmp = a[i]; a[i]=a[j];a[j]=tmp;
}
}
}
}
}

Variable descriptor Table:


Variable Name Variable Type Use
sent String The string to store the
sentence
a String array The array to store the
words of the sentence
separately
i,j,k int iteration variable

Output:

Page 175
Question 7: To extract words from a sentence input
from the user in the form of a string. After extracting
the words store them in an array and short them in
REVERSE alphabetical order.
Algorithm:
1. Create a class and import java.util.*.
2. Write the main function.
3. Input a string sentence from the user using the Scanner class.
4. Convert the string sentence into an array of words using
string.split() function.
5. Now use the Selection short algorithm which works on
dividing the array into sub arrays and finding the smallest
value in the subarray.
6. To compare the strings use the String1.compare(String2) to
compare the strings while sorting.
7. Createb another String array and revrerse the sorted array
using a for loop and filling the new array from backwards.
8. The new array will contain the words of the sentence in
reverse alpahabetical order.
9. Display the results using a for loop and System.out.println()

Code:
import java.util.*;
public class StringShot{
public static void main(){
String sent = new Scanner(System.in).nextLine();
String[] a = sent.split("\\s");
sort(a);
String b=new String[a.length];
for(int i=0;i<b.length;i++){
b[i]=a[b.lentgh-1-i];
}
System.out.print("Sorted Array::");
for(int k=0;k<a.length;k++)System.out.print(b[k]+",");
}

public static void sort(String[] a) {


for(int i=0;i<(a.length-1);i++){
for(int j=i+1;j<a.length;j++){
if(a[i].compareTo(a[j])>0){
String tmp = a[i]; a[i]=a[j];a[j]=tmp;

Page 176
}
}
}
}
}

Variable descriptor Table:


Variable Name Variable Type Use
sent String The string to store the
sentence
a String array The array to store the
words of the sentence
separately
i,j,k int iteration variable
b String array The new array to store
the elements of the
sorted array in reverse
order.

Output:

Page 177
Topic-7: Exception Handling
Question 1: To demonstrate unhandled exception in
JAVA.
Algorithm:
1. Create a class and import java.util.*.
2. Create the main fiunction.
3. Create an array with size 5.
4. Try to access array element with an index greater than 5.
5. The Execution of the program will stop and Java Virtual
Machine will display ArrayOutOfBounds Exception

Page 178
Code:
public class Exc1{
public static void main(){
int arr[]={1,1,1,1,1}; //size is 5
arr[6]=100;
}}

Variable descriptor Table:


Variable Name Variable Type Use
arr int array The array to work on

Output:

Page 179
Question 2: To demonstrate handle basic Exception
handling.
Algorithm:
1. Create a class and import java.util.*.
2. Create the main fiunction.
3. Create an array with size 5.
4. Try to access array element with an index greater than 5.
5. Place the statement which will cause the exception in a try
catch block.
6. In the catch block, display the error message to the user.

Page 180
Code:
public class Exc2{
public static void main(){
int arr[]={1,1,1,1,1}; //size is 5
try{arr[6]=100;}catch(Exception e){
System.out.println("Array Out oF bounds Exception has been handled by
this piece of code");
}
}}

Page 181
Variable descriptor Table:
Variable Name Variable Type Use
arr int array The array to work on

Output:

Page 182
Question 3: To demonstrate handle basic Exception
handling with the finally block.
Algorithm:
1. Create a class and import java.util.*.
2. Create the main fiunction.
3. Create an array with size 5.
4. Try to access array element with an index greater than 5.
5. Place the statement which will cause the exception in a try
catch block.
6. In the catch block, display the error message to the user.
7. The finally block is executed irrespective of whether an
exception takes place or not.
8. In the finally block also display some message.

Page 183
Code:
public class Exc2{
public static void main(){
System.out.println("This won't cause exception");
arrexc(4);
System.out.println("Exception will now happen");
arrexc(78);
}
static void arrexc(int n){
int arr[]={1,1,1,1,1}; //size is 5
try{arr[n]=100;}catch(Exception e){
System.out.println("Array Out oF bounds Exception has been handled by
this piece of code");

}
finally{
System.out.println("This is the finally block..");
System.out.println("It is always executed irrespective of whether an
exception occurs or not.");
}
}
}

Page 184
Variable descriptor Table:
Variable Name Variable Type Use
arr int array The array to work on

Output:

Page 185
Question 4: To demonstrate and handle the
InputMismatchException.
Algorithm:
1. Create a class and import java.util.*.
2. Create the main fiunction.
3. Take the input of an integer from the user using Scanner
Class and while running the program enter a String when
prompted for input.
4. Put the exception causing code in a try catch block
5. Display the error message when exception occurs.

Page 186
Code:
import java.util.*;
public class exc2{
public static void main(){
try{
int a = new Scanner(System.in).nextInt();
}catch(InputMismatchException E){
System.out.println("A Input MIsmatch exception has occured");
}
}
}

Page 187
Variable descriptor Table:
Variable Name Variable Type Use
a int The integer to take
input from the user

Output:

Page 188
Topic-8: Board Programs
Question 1: To print all the prime Adam numbers from
0 to a number inputted by the user. A prime adam
number is a number which is both prime and adam
number. A number a is adam number when the square of
it’s reverse is equal to the reverse of its square.
(COMPUTER SCIENCE PRACTICAL ISC 2020 Q1. )
Algorithm:
1. Create a class and import java.util.*.
2. Create a function primecheck(int a) to check whether a
number is prime or not. It will do so by checking the
remainder on dividing the parameter a by every number
greater than 1 and less than a using a for loop. The function
will return 1 if the number is prime and will return 0 if the
number is not prime. If the parameter is 1 the function will
return 0.
3. Create a function to reverse a number which takes the
number to reverse as function parameter and returns the
reversed number. It will do so by using a for loop.
4. Create a function to check whether a number is adam or not.
This will be done by calling the reverse() function squaring
both the original and reversed number and then again
reversing one of the squared numbers and check whether it is
equal to the other one.
5. In the main function, call the adamcheck() and primecheck()
functions and if both of them return 1 then the number is
PrimeAdam.
6. Generate numbers from 0 to inp(the input by user) using a
for loop.
7. Check for each of these numbers whther they are PrimeAdam
or not. Print the numbers which are prime adam
.

Page 189
Code:
import java.util.*;
public class primeadam{
public static void main(){
int inp = new Scanner(System.in).nextInt();
System.out.println("Prime Adam Numbers are::");
for(int i=0;i<inp;i++){
if(primecheck(i)==1 && adamcheck(i)==1){
System.out.print(i+" ");
}
}
}
static int adamcheck(int c){
int res=0;
int rev=reverse(c);
if(c*c==reverse(rev*rev)){res=1;}

return res;
}
static int reverse(int a){
int res=0;
int tmp1=a,tmp2=a;
int count=0;
while(tmp1>0){
tmp1=tmp1/10;

Page 190
count++;
}
for(int i=0;i<count;i++){
res=res*10+tmp2%10;
tmp2=tmp2/10;
}
return res;
}

static int primecheck(int b){


int res=1;
for(int i=2;i<b;i++){
if(b%i==0){res=0;}
}
if(b==1){res=0;}
return res;
}
}

Page 191
Variable descriptor Table:
Variable Name Variable Type Use
a,b,c int parameters for the
reverse() , primecheck()
and adamcheck()
functions
inp int to take the input from
user
res int the number returned
by the functions
tmp1,tmp2 int temporary variables

Output:

Page 192
Question 2: Write a program in Java to check wheter a number
is Circular Prime Number or not.(ISC practical 2016)

Algorithm:
1. Create a class with three functions, boolean isPrime(int n), boolean
checkCricular(int n) and the main function.
2. A circular prime number is a number which is prime and the
circular permutations of its digits are also prime. The function
isPrime(int n) will use a for loop to generate all the numbers smaller
than the test number to check whether the number entered as the
parameter of the function is Prime or Composite number using a”
for-loop” construct.
3. The function boolean checkCircular(int n) will create all the
permutations if the digits of the number entered by the user to check
whether they are prime by calling the isPrime(int n) function.
4. The main function will drive the entire program by calling the
checkCircular(int n) function.
5. The final result will be displayed using System.out.println()
function.

Code:

class KJ
{

static boolean isPrime(int n)


{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;

// This is checked so that we can skip


// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;

for (int i = 5; i * i <= n; i = i + 6)


if (n % i == 0 || n % (i + 2) == 0)
return false;

return true;

Page 193
}

// Function to check if the number is circular


// prime or not.
static boolean checkCircular(int N)
{
// Count digits.
int count = 0, temp = N;
while (temp>0) {
count++;
temp /= 10;
}

int num = N;
while (isPrime(num)) {

// Following three lines generate the next


// circular permutation of a number. We
// move last digit to first position.
int rem = num % 10;
int div = num / 10;
num = (int)((Math.pow(10, count - 1)) * rem)
+ div;

// If all the permutations are checked and


// we obtain original number exit from loop.
if (num == N)
return true;
}

return false;
}

// Driver Program
public static void main (String[] args)
{
int N = 1193;
if (checkCircular(N))
System.out.println("Yes");
else
System.out.println("No");
}
}

Page 194
Variable descriptor Table:
Variable Name Variable Type Use
n int Parameter for the
function boolean
isPrime(int n)
N int Parameter for the
function boolean
checkCircular(int N)
temp int Temporary variable
count int To store the number the
digits.
rem int To store remainder
div int To store the result of
division

Page 195
Output:

Page 196
Question 3: Write a program in Java to take the input of year
and day number and print the output in the form of words. For
eg. When Year is 2000 and day number is 1, the otput will be 1
JANUARY 2000.

Algorithm:
1. Create class and write the main function. Create another function
which is static and returns a string taking two integers, year and
day number as parameter.
2. Import the library java.util.* for taking input using the scanner
class.
3. Name the second function finddate(int year,int day). In the function
create an array of 12 elements containing the number of days of all
months in the correct order.
4. Check for a leap year by dividing year by 4 and finding the
remainder. If the remainder is 0 then the year is leap year. If a the
year is leap year set the number of days in February as 29 otherwise
set it as 28.
5. Start subtracting the array elements from the day number in a while
loop till day is greater than 31.
6. When the execution of the loop stops the value of day will be the
date,using switch assign the string of the month to a temporary
variable . For example 1 will assign JANUARY, 12 will assign
DECEMBER and so on.
7. Create the final string in the following way:
a. date = Integer.toString(day)+ " " +month+"
"+Integer.toString(year);

Page 197
Code:
import java.util.*;
public class YearProcessor
{
public static void main(){
System.out.println("Enter Year:");
int y=new Scanner(System.in).nextInt();
System.out.println("Enter Day Number:");
int d=new Scanner(System.in).nextInt();
System.out.println(finddate(y,d));

static String finddate(int year,int day){


int montharr[]={31,28,31,30,31,30,31,31,30,31,30,31};
int t=0;
String date="";
if(year%4==0){
montharr[1]=29;
while(day>=31){
day=day-montharr[t];
t++;

}else{while(day>=31){

Page 198
day=day-montharr[t];
t++;

}
if(day==0){
if(t==12){day=montharr[11];}
else{day=montharr[t];}
}
String month="";
switch(t){
case 0: month="JANUARY"; break;
case 1: month="FEBRUARY"; break;
case 2: month="MARCH"; break;
case 3: month="APRIL"; break;
case 4: month="MAY"; break;
case 5: month="JUNE"; break;
case 6: month="JULY"; break;
case 7: month="AUGUST"; break;
case 8: month="SEPTEMBER"; break;
case 9: month="OCTOBER"; break;
case 10: month="NOVEMBER"; break;
case 11: month="DECEMBER"; break;
case 12: month="DECEMBER"; break;
default: month="Something wrong"; break;

Page 199
}
date = Integer.toString(day)+ " " +month+"
"+Integer.toString(year);
return date;
}
}

Page
200
Variable descriptor Table:
Variable Name Variable Type Use
y int to store the year
d int to store the day number
day int to store the day number
year int to store the year
montharr int array to store the array of the
number of days in
month
month string to store the name of
month calculated
date string to store the date on
words

Output:

Page 201
Question 4:To input a matrix of dimesniosn 3 by 3 and input
the integers form the user. Sort all the rows of the matrix and
display the original matrix and the sorted matrix.

Algorithm:
1. Create a class and write the main function.
2. Import java.util.* for taking input from the user using the scanner
class.
3. Declare a 3x3 matrix and and input a the elements of the matrix
using a two for loops one nested within the other and the scanner
class.
4. Print the original value of the matrix using a similar loop to the one
used in step3.
5. Now sort the individual rows using Selection sort.
6. Take the first element and traverse through all the elements ahead of
it. Replace the first element with the other elements during the
traversal if the value of the first element is greater than any other
element.
7. Thus we have the smallest element at the first index. Repeat the
same for all the indexes and for all the rows.
8. This method will sort in ascending order.
9. Display the results using a loop similar to the one used in step 4.

Page 202
Code:
import java.util.*;
public class MatrixRowSorter
{
public static void main(){
int arr[][]=new int[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.println("Enter Element ["+i+","+j+"] :");
arr[i][j]=new Scanner(System.in).nextInt();
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
} System.out.println("");
}
for(int p=0;p<arr.length;p++){
for(int s=0;s<(arr.length-1);s++){
int d=0;
for(d=s+1;d<arr.length;d++){
if(arr[p][s]>arr[p][d]){
int temp=arr[p][d];
arr[p][d]=arr[p][s];
arr[p][s]=temp;
}
}
}
}

Page 203
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
} System.out.println("");
}
}
}

Page 204
Variable descriptor Table:
Variable Name Variable Type Use
i,j,p,d int iteration varibles
temp int temporary variable for
swapping values of
array elements.
arr int array the matrix to work on.

Page 205
Output:

Page 206
Bibliography
1. Java, A primer by Balaguruswamy, Tata McGrawHill Publications
2. ISC Computer Science with JAVA XI by Sumita Arora, Dhanpat Rai publications
3. ISC Computer Science with JAVA XII by Sumita Arora, Dhanpat Rai publications

Page 207

You might also like