Ahmed Habib's Computer Applications Project Certificate
Ahmed Habib's Computer Applications Project Certificate
for the academic year 2023 - 2024 in fulfilment of the board requirement.
1. Special Numbers 1
2. Strings 19
4. Recursions 87
5. Inheritance 97
1
Question: Write a program to input a number and check if it is a palindrome number or not.
Source Code:
import java.util.*;
public class prime
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the number"); // accepting the number
int x = sc.nextInt();
int c=0;
for(int i=1; i<=x; i++) // checking for prime condition
if(x%i == 0)
c++;
if(c==2)
System.out.println("prime"); // printing prime
else
System.out.println("not prime"); // printing not prime
}
}
Output:
enter the number
17
prime
Question: Write a program to input a number and check if it is a magic number or not.
Source Code:
import java.util.*;
public class magic
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter a number"); // accepting the number
int x = sc.nextInt();
int z = x;
while(z>9) // checking for magic condition
{
x=z;z=0;
while(x>0)
{
int a = x/10;
2
int b = a*10;
int c = x-b;
z += c;
x=a;
}
}
if(z == 1)
System.out.println("magic"); // printing magic
else
System.out.println("not magic"); // printing not magic
}
}
Output:
enter a number
1729
magic
Question: Write a program to input two numbers and check if they are twin prime numbers or
not.
Source Code:
import java.util.*;
public class twinprime
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter 2 numbers");
int x = sc.nextInt(); // user input
int y = sc.nextInt(); // user input
if(x-y == 2 || y-x == 2) {
int a=0, b=0;
for(int i=1; i<=x; i++) // checking for prime condition
if(x%i == 0)
a++;
3
else
System.out.println("not twin prime"); // printing not twin prime
}
}
Output:
enter 2 numbers
17 19
twin prime
Question: Write a program to input a number and check if it is a kaprekar number or not.
Source Code:
import java.util.*;
public class kaprekar
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
int x = sc.nextInt(); // user input
int sqr = x*x, digit, s=0;
while(sqr!=0) {
digit = sqr%10;
s += digit;
sqr /= 10;
}
if(x == s) // kaprekar condition check
System.out.println("it is a kaprekar number"); // printing result
else
System.out.println("it isn't a kaprekar number"); // printing result
}
}
Output:
enter a number
45
it is a kaprekar number
4
Question: Write a program to input two numbers and check if they are amicable numbers or
not.
Source Code:
import java.util.*;
public class amicable
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter two numbers");
int n1 = sc.nextInt(), n2 = sc.nextInt(), s1=0, s2=0; // user input
for(int i=1; i<=n1; i++)
if(n1%i == 0)
s1 += i;
Output:
enter two numbers
1184 1210
amicable numbers
Question:
Class Name: Unique
Data Members:
n - integer variable to store the input number
Member Functions:
Unique() - Default constructor to initialize the data member
void readNum() - function to accept the value of n from the user
int unique(int x) - function to check if the digits of x are unique
void display() - function to print whether the number is unique or not
Source Code:
5
import java.util.*;
public class Unique
{
int n; // data member initialisation
Unique() // default constructor
{
n = 0;
}
public static void main(String[]args) // drive method
{
Unique in = new Unique();
in.readNum();
in.display();
}
void readNum() // function for accepting value of n
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the value of n");
n = sc.nextInt();
}
int unique(int x) // function for checking if unique
{
int c=0;
for(char ch='1'; ch<='9'; ch++)
{
c=0;
String num = Integer.toString(x);
for(int i=0; i<num.length(); i++)
if(num.charAt(i) == ch)
c++;
if(c > 1)
break;
}
return c;
}
void display() // function for printing if unique
{
int x = unique(n);
if(x <= 1)
System.out.println("Unique Number");
else
System.out.println("Not An Unique Number");
}
}
6
Output:
enter the value of n
9863
Unique Number
Question: Write a program to input a range from m to n, where both m and n are integers
greater than 99 and less than 10000. Print the fascinating numbers between m and n and their
frequency.
Source Code:
import java.util.*;
public class Fascinating
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the value of m");
int m = sc.nextInt(); // user input
System.out.println("enter the value of n");
int n = sc.nextInt(); // user input
if(m<n && m>99 && m<10000 && n>99 && n<10000) // validation
{
int c=0;
for(int i=m; i<=n; i++) {
int a = i*2, b = i*3, con;
String num = "" + i + a + b;
char ch;
for(ch='1'; ch<='9'; ch++) {
con=0;
for(int j=0; j<num.length(); j++)
if(num.charAt(j) == ch)
con++;
if(con != 1)
break;
}
if(ch > '9') {
c++;
System.out.print(i+" "); // printing number
}
}
if(c>0)
System.out.println("\nFrequency = "+c); // printing frequency
}
else
System.out.println("Invalid Input !!!!");
7
}
}
Output:
enter the value of m
100 1000
enter the value of n
192 219 273 327
Frequency = 4
Question:
Class Name: Composite
Data Members:
arr[][] - integer 2D array to store composite numbers
m - integer variable to store the number of rows of the array
n - integer variable to store the number of columns of the array
Member Functions:
Composite(int mm, int nn) - parameterized constructor to assign mm to m and nn to n
int isComposite(int p) - function to check whether a number is composite or not
void fill() - function to fill the array with composite numbers
void display() - function to print the array in column-wise matrix form with composite numbers
Source Code:
import java.util.*;
public class Composite
{
int arr[][], m, n;
Composite(int mm, int nn)
{
m = mm;
n = nn;
arr = new int[m][n];
}
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the value of m");
int x = sc.nextInt();
System.out.println("enter the value of n");
int y = sc.nextInt();
Composite in = new Composite(x, y);
in.fill();
in.display();
8
}
int isComposite(int p)
{
int c=0;
for(int i=1; i<=p; i++)
if(p%i == 0)
c++;
if(c>2)
return 1;
else
return 0;
}
void fill()
{
int c = m*n, num=1;
int x[] = new int[c];
while(c>0) {
if(isComposite(num) == 1) {
x[c-1] = num;
c--;
}
num++;
}
9
Output:
Question:
Class Name: Armstrong
Data Members:
num - long variable to store the input number
cube - long variable to store the cube of digits
Member Functions:
Armstrong(long nx) - parameterized constructor to assign nx to num
long RecCubeDigit(long q) - function to calculate the cube of a digit recursively
long RecGetDigitSum(long N) - function to calculate the sum of the cubes of digits recursively
boolean isArmstrong() - function to check if the number is an Armstrong number
void display() - function to print whether the number is an Armstrong number or not
Source Code:
import java.util.*;
public class Armstrong {
long num, cube;
Armstrong(long nx) {
num = nx;
}
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
int x = sc.nextInt();
Armstrong in = new Armstrong(x);
in.display();
}
long RecCubeDigit(long q) {
return (q*q*q);
}
long RecGetDigitSum(long N) {
if(N==0)
10
return 0;
return RecCubeDigit(N%10) + RecGetDigitSum(N/10);
}
boolean isArmstrong() {
if(num == RecGetDigitSum(num))
return true;
else
return false;
}
void display() {
if(isArmstrong() == true)
System.out.println("Armstrong Number");
else
System.out.println("Not An Armstrong Number");
}
}
Output:
enter the number
153
Armstrong Number
Question:
Class Name: Disarium
Data Members:
num - integer variable to store the input number
size - integer variable to store the count of digits in the number
Member Functions:
Disarium(int nn) - parameterized constructor to assign nn to num and initialize size to 0
void CountDigit() - function to count the number of digits in the number
int SumOfDigits(int n, int p) - function to calculate the sum of the digits each raised to the
respective position's power
void check() - function to check if the number is a Disarium number
Source Code:
import java.util.*;
public class Disarium
{
int num, size;
Disarium(int nn)
{
num = nn;
size = 0;
}
11
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
int x = sc.nextInt();
Disarium in = new Disarium(x);
in.CountDigit();
in.check();
}
void CountDigit()
{
int n = num;
while(n>0) {
size++;
n/=10;
}
}
int SumOfDigits(int n, int p)
{
if(n>0)
return (int) Math.pow(n%10, p) + SumOfDigits(n/10, p-1);
return 0;
}
void check()
{
if(SumOfDigits(num, size) == num)
System.out.println("Disarium Number");
else
System.out.println("Not A Disarium Number");
}
}
Output:
enter the number
89
Disarium Number
Question:
Data Members:
n - integer variable to store the input number
rev - integer variable to store the reversed form of the number
f - integer variable used for checking primality
Member Functions:
12
Emirp(int nn) - parameterized constructor to assign nn to num and initialize rev to 0 and f to 2
int isprime(int x) - function to check if x is a prime number recursively
void isEmirp() - function to check if the number is an Emirp number
Source Code:
import java.util.*;
public class Emirp
{
int n, rev, f;
Emirp(int nn)
{
n = nn;
rev = 0;
f = 2;
}
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
int x = sc.nextInt();
Emirp in = new Emirp(x);
in.isEmirp();
}
int isprime(int x)
{
if(n==x)
return 1;
else if(n%x == 0)
return 0;
else
return isprime(x+1);
}
void isEmirp()
{
int x=n;
while(x>0) {
rev = rev * 10 + (x%10);
x/=10;
}
int t1 = isprime(f);
n = rev;
f = 2;
int t2 = isprime(f);
if(t1 == 1 && t2 == 1)
System.out.println("Emirp Number");
else
System.out.println("Not An Emirp Number");
13
}
}
Output:
enter the number
13
Emirp Number
Question:
Class Name: Evil
Data Members:
num: private integer to store a positive integer
bin: private integer to store the binary representation of the positive integer
Member Functions:
Evil(): Default constructor to initialize num and bin to 0
acceptNum(int n): Function to accept a positive integer and assign it to num if it is greater than
0
rec_bin(int x): Recursive function to convert a decimal number x to binary and store it in bin
check(): Function to check if the binary representation of num is an Evil number (has an even
number of 1s)
main(String[] args): Main method to create an instance of Evil, accept a positive integer (19 in
this case), and check if it is an Evil number
Source Code:
14
rec_bin(num);
int count = 0;
int temp = bin;
while (temp > 0) {
if (temp % 10 == 1) {
count++;
}
temp /= 10;
}
if (count % 2 == 0) {
System.out.println(bin + " is not an Evil number.");
} else {
System.out.println(bin + " is an Evil number.");
}
}
public static void main(String[] args) {
Evil evilNumber = new Evil();
evilNumber.acceptNum(19);
evilNumber.check();
}
}
Output:
enter a number
17
17 is an Evil number.
Question:
Class Name: Mobius
Data Members:
x - integer to store a number
Member Functions:
mobius(int x) - function to calculate the Mobius function for a given integer x. The function
returns 0 if x is divisible by the square of a prime number, 1 if x has an even number of distinct
prime factors, and -1 if x has an odd number of distinct prime factors.
operate() - function to interactively take user input, calculate the Mobius function, and display
the output. It continues to prompt the user for input until the user decides to stop.
Source Code:
import java.util.*;
public class Mobius {
int mobius(int x) {
int p=0;
if(x%2 == 0) {
15
x /= 2;
p++;
if(x%2 == 0)
return 0;
}
for(int i=3; i<=Math.sqrt(x); i+=2) {
if(x%i == 0) {
x /= i;
p++;
if(x%i == 0)
return 0;
}
}
return (p%2 == 0) ? -1 : 1;
}
void operate() {
Scanner sc = new Scanner(System.in);
String num;
while(true) {
System.out.println("Enter the number:");
num = sc.next();
System.out.println("Output: "+mobius(Integer.valueOf(num)));
System.out.println("Do you want to continue? (yes/no)");
num = sc.next();
if(!num.equals("yes"))
break;
}
}
public static void main(String[]args) {
Mobius in = new Mobius();
in.operate();
}
}
Output:
Enter the number:
49
Output: 0
Question:
Class Name: Vampire
Data Members:
n - integer variable to store the input number
Member Functions:
Vampire() - Default constructor to initialize the data member
16
void accept() - function to accept the number from the user
char[] bubbleSort(char[] arr) - function to perform bubble sort on a character array
boolean isVampire() - function to check if the number is a Vampire Number
void check() - function to display whether the number is a Vampire Number or not
Source Code:
import java.util.*;
public class Vampire {
int n;
public static void main(String[]args) {
Vampire in = new Vampire();
in.accept();
in.check();
}
void accept() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number:");
n = sc.nextInt();
}
char[] bubbleSort(char[]arr) {
for(int i=0; i < arr.length-1; i++)
for(int j=0; j < (arr.length-1-i); j++)
if(arr[j] > arr[j+1]) {
char t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;
}
return arr;
}
boolean isVampire() {
String num = String.valueOf(n);
if(n<=0 || String.valueOf(n).length()%2 != 0) {
System.out.println(n+" is not a Vampire Number");
System.exit(0);
}
int f1 = i, f2 = n/i;
17
for(int j=0; j<num.length(); number[j] = num.charAt(j), j++);
for(int j=0; j<f.length(); factors[j] = f.charAt(j), j++);
number = bubbleSort(number);
factors = bubbleSort(factors);
if(flag) {
System.out.println("Factors are "+f1+" and "+f2);
return true;
}
}
}
return false;
}
void check() {
if(isVampire())
System.out.println(n+" is a Vampire Number");
else
System.out.println(n+" is not a Vampire Number");
}
}
Output:
Enter the number:
6880
Factors are 80 and 86
6880 is a Vampire Number
18
STRING-BASED
PROGRAMS
19
Question:
Class Name: theString
Data Members:
main(String[] args): The main function where an object of the class is created, and methods for
input and display are called.
Accept(): Accepts a string input from the user and assigns it to the Str data member.
Recursive_fn(int x): A recursive function that counts the number of capital and small letters in
the string using the cap and sm data members.
display(): Calls the Recursive_fn method to calculate the counts and displays the results.
Source Code:
import java.util.*;
public class theString {
String Str;
int cap, sm;
theString() {
Str = "";
cap = 0;
sm = 0;
}
public static void main(String[]args) {
theString in = new theString();
in.Accept();
in.display();
}
void Accept() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String");
Str = sc.nextLine();
}
void Recursive_fn(int x) {
if(x>0) {
if(Character.isUpperCase(Str.charAt(x-1)) && Character.isLetter(Str.charAt(x-1)))
cap++;
else if(Character.isLowerCase(Str.charAt(x-1)) && Character.isLetter(Str.charAt(x-1)))
sm++;
Recursive_fn(x-1);
20
}
}
void display() {
Recursive_fn(Str.length());
System.out.println("Number of capital letters: "+cap);
System.out.println("Number of small letters: "+sm);
}
}
OUTPUT:
Enter a String
ComputerScience
Number of capital letters: 2
Number of small letters: 13
Question:
Class Name: StrPalindrome
Data Members:
main(String[] args): The main function where an object of the class is created, and methods for
input and palindrome check are called.
accept(): Accepts a string input from the user and assigns it to the str data member.
RevStr(int len): A recursive function that reverses the given string.
check(): Checks whether the input string is a palindrome or not and prints the result.
Source Code:
import java.util.*;
public class StrPalindrome {
String str;
StrPalindrome() {
str = "";
}
public static void main(String[]args) {
StrPalindrome in = new StrPalindrome();
in.accept();
in.check();
}
void accept() {
Scanner sc = new Scanner(System.in);
21
System.out.println("Enter a String");
str = sc.nextLine();
}
String RevStr(int len) {
if ((len) >= 0)
return str.charAt(len) + RevStr(len-1);
return "";
}
void check() {
if(str.equals(RevStr(str.length()-1)))
System.out.println("Palindrome String");
else
System.out.println("Not a Palindrome String");
}
}
OUTPUT:
Enter a String
dad
Palindrome String
Question:
Class Name: Spaces
Data Members:
main(String[] args): The main function where an object of the class is created, and methods for
input, processing, and display are called.
accept(): Accepts input for the sentence, checks if it's terminated properly, and accepts the word
and position.
space_up(): Replaces consecutive spaces with a single space and inserts the given word at the
specified position.
show(): Displays the modified sentence.
Source Code:
import java.util.*;
public class Spaces {
String s, w;
int pos;
public static void main(String[]args) {
22
Spaces in = new Spaces();
in.accept();
in.space_up();
in.show();
}
void accept() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence in uppercase terminated with'.', ',' or '!'");
s = sc.nextLine();
if(".,!".indexOf(s.charAt(s.length()-1)) == -1) {
System.out.println("INVALID INPUT! SENTENCE NOT TERMINATED WITH '.', ',' OR
'!'");
System.exit(0);
}
for(int i=0; i<s.length()-1; i++)
if(!Character.isUpperCase(s.charAt(i))) {
System.out.println("INVALID INPUT! SENTENCE NOT IN UPPERCASE");
System.exit(0);
}
System.out.println("Enter a word to be inserted:");
w = sc.next();
System.out.println("Enter position of the word to be inserted:");
pos = sc.nextInt();
}
void space_up() {
s = s.replaceAll("\\s+", " ");
for(int i=0, c=0; i<s.length(); i++) {
if(c == pos-1) {
s = s.substring(0, i) + w + " " + s.substring(i, s.length());
break;
}
if(s.charAt(i) == ' ')
c++;
}
}
void show() {
System.out.println("Sentence: "+s);
}
}
OUTPUT:
Enter a sentence in uppercase terminated with '.', ',' or '!'
HELLO HOW ARE YOU.
Enter a word to be inserted:
DOING
Enter position of the word to be inserted:
3
Sentence: HELLO HOW DOING ARE YOU.
23
Question:
Class Name: PalindromeWords
Data Members:
main(String[] args): The main function where an object of the class is created, and methods for
input, processing, and display are called.
accept(): Accepts input for the sentence and ensures proper termination.
check_split(): Splits the sentence into words and checks whether each word is palindromic or
not.
check(): Checks whether each word in the sentence is palindromic or not.
display(): Displays the palindromic and non-palindromic words along with their counts.
Source Code:
import java.util.*;
public class PalindromeWords {
String s, sp, snp;
int p, np;
PalindromeWords() {
s = "";
sp = "";
snp = "";
p = 0;
np = 0;
}
public static void main(String[]args) {
PalindromeWords in = new PalindromeWords();
in.accept();
in.check();
in.display();
}
void accept() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence: ");
s = sc.nextLine();
if(".,!?".indexOf(s.charAt(s.length()-1)) == -1) {
24
System.out.println("INVALID INPUT!!!!");
System.exit(0);
}
s = s.substring(0, s.length() - 1);
}
void check_split() {
String words[] = s.split(" ");
for(String x : words) {
String w = "";
if(w.equals(x)) {
p++;
sp += x + " ";
}
else {
np++;
snp += x + " ";
}
}
}
void check() {
int len = s.length();
while(s.length() != 0) {
String t = s.substring(0, s.indexOf(" ")), w = "";
if(w.equals(t)) {
p++;
sp += t + " ";
}
else {
np++;
snp += t + " ";
}
25
}
}
OUTPUT:
Enter Sentence:
level civic hello kayak world radar
Palindromic Sentence : level civic kayak radar
Count : 4
Non-Palindromic Sentence : hello world
Count : 2
Question:
Class Name: NRP_Word
Data Members:
main(String[] args): The main function where an object of the class is created, and methods for
input and finding the largest non-repeating subword are called.
Accept(): Accepts input for the string.
reduce(String w): Takes a word as input, reduces it to a new word without repeating letters, and
returns the new word.
LargestSubString(): Splits the input string into words, reduces each word using the reduce
method, and finds the largest non-repeating subword.
Source Code:
import java.util.*;
public class NRP_Word {
String s;
NRP_Word() {
s = "";
}
public static void main(String[]args) {
NRP_Word in = new NRP_Word();
in.Accept();
System.out.println("String: "+in.s);
System.out.println("Largest SubString: "+in.LargestSubString());
}
void Accept() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string:");
s = sc.nextLine();
26
}
String reduce(String w) {
String nw = ""; // this will the new word which will conatin the word without any repeating
letters after reducing w
return nw;
}
String LargestSubString() {
String sarr[] = s.split(" "), lss = "";
for(int i=0; i<sarr.length; i++) {
sarr[i] = reduce(sarr[i]);
lss = lss.length() < sarr[i].length() ? sarr[i] : lss;
}
return lss;
}
}
OUTPUT:
Enter the string:
hello goodbye welcome
Question:
Class Name: Encode
Data Members:
27
Encode() - Constructor to initialize word, new_word, and length.
acceptWord() - Method to accept the word from the user.
nextVowel() - Method to modify the word by replacing each vowel with the next vowel.
display() - Method to display the original word and the modified word.
main(String[] args) - Main method to create an object of the Encode class, accept the word,
modify it, and display the results.
Source Code:
import java.util.*;
public class Encode {
String word, new_word;
int length;
Encode() {
word = "";
new_word = "";
length = 0;
}
public static void main(String[] args) {
Encode in = new Encode();
in.acceptWord();
in.nextVowel();
in.display();
}
void acceptWord() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Word:");
word = sc.next();
length = word.length();
}
void nextVowel() {
String vowels = "AEIOUAaeioua";
for(int i=0; i<length; i++)
new_word = (vowels.indexOf(word.charAt(i)) != -1) ? new_word +
vowels.charAt(vowels.indexOf(word.charAt(i)) + 1) : new_word + word.charAt(i);
}
void display() {
System.out.println("Word: "+word);
System.out.println("New Word: "+new_word);
}
}
OUTPUT:
28
Question:
Class Name: ASCII_crypt
Methods:
main(String[] args): The main function where options for encoding and decoding are presented,
and respective methods are called based on user input.
encode(): Takes user input for a message, converts each character to its ASCII value, and
reverses the resulting string to get the encoded message.
decode(): Takes user input for a code, reverses the code, decodes each ASCII value to the
corresponding character, and reconstructs the original message.
Source Code:
import java.util.*;
public class ASCII_crypt {
public static void main(String[]args) {
System.out.println("Options:\n1: Encode\n2: Decode");
int x = new Scanner(System.in).nextInt();
switch(x) {
case 1:
new ASCII_crypt().encode();
break;
case 2:
new ASCII_crypt().decode();
break;
void encode() {
System.out.println("\nEnter the Message:");
String message = new Scanner(System.in).nextLine();
void decode() {
29
System.out.println("\nEnter the Code:");
String code = new Scanner(System.in).next();
while(s.indexOf("32") != -1) {
String t = s.substring(0, s.indexOf("32"));
OUTPUT:
Options:
1: Encode
2: Decode
1
Enter the Message:
Hello World
Encoded Message: 23001801411111782311180180110127
30
Question:
Class Name: WordNumbers
Data Members:
num - Integer variable to store the input number.
Member Functions:
WordNumbers() - Constructor (not explicitly defined).
main(String[] args) - Main method to create an object of the WordNumbers class, accept the
number, convert it to words, and print the result.
accept() - Method to accept the number from the user and check if it's greater than 9999. If it is,
the program exits.
convert() - Method to convert the numeric representation of the number into words.
print() - Method to display the converted word representation of the number.
Source Code:
import java.util.*;
public class WordNumbers {
int num;
void accept() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Number:");
num = sc.nextInt();
sc.close();
if(num > 9999)
System.exit(0);
System.out.print("\n"+num);
}
String convert() {
String[]TH = {"ONE THOUSAND", "TWO THOUSAND", "THREE THOUSAND", "FOUR
THOUSAND", "FIVE THOUSAND",
"SIX THOUSAND", "SEVEN THOUSAND", "EIGHT THOUSAND", "NINE THOUSAND"};
31
String[]IT = {"ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN",
"SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"};
while(num > 0) {
if(String.valueOf(num).length() == 4) {
num_word += TH[num/1000 - 1] + " ";
num %= 1000;
}
else if(String.valueOf(num).length() == 3) {
num_word += H[num/100 - 1] + " AND ";
num %= 100;
}
else if(String.valueOf(num).length() == 2) {
if(!(String.valueOf(num/10).equals("1") && num != 10)) {
num_word += T[num/10 - 1] + " ";
num %= 10;
}
else {
num_word += IT[num%10 - 1];
num = 0;
}
}
else {
num_word += O[num - 1];
num = 0;
}
}
return num_word;
}
void print() {
System.out.println(" = "+convert());
}
}
OUTPUT:
Enter the Number:
3456
= THREE THOUSAND FOUR HUNDRED FIFTY SIX
3456 = THREE THOUSAND FOUR HUNDRED FIFTY SIX
32
Question:
Class Name: Exchange
Data Members:
sent - String variable to store the input sentence.
newstr - String variable to store the new word with consonants and vowels separated.
size - Integer variable to store the size of the sentence.
Member Functions:
Exchange() - Default constructor to initialize data members.
main(String[] args) - Main method to create an object of the Exchange class, read a sentence,
create a new word, and display the result.
readsentence() - Method to accept a sentence from the user and terminate the program if it's not
terminated with a full stop.
NewWord() - Method to create a new word with consonants and vowels separated based on the
input sentence.
display() - Method to print the original sentence and the new word.
Source Code:
import java.util.*;
public class Exchange
{
String sent, newstr; // data member initialisation
int size; // data member initialisation
Exchange() // default constructor
{
sent = "";
newstr = "";
size = 0;
}
public static void main(String[]args) // drive method
{
Exchange in = new Exchange();
in.readsentence();
in.NewWord();
in.display();
}
void readsentence() // function for accepting a string and terminating program if not entered with a
full stop
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the sentence terminated with a full stop");
sent = sc.nextLine();
size = sent.length();
if(sent.charAt(size-1) != '.')
{
System.out.println("the sentence is not terminated with a full stop");
33
System.exit(0);
}
}
void NewWord() // function for creating new word with consonants and vowels separated
{
for(int i=0; i<size; i++)
{
char ch = sent.charAt(i);
if("aeiouAEIOU .".indexOf(ch) == -1)
{
newstr += ch;
}
}
for(int i=0; i<size; i++)
{
char ch = sent.charAt(i);
if("aeiouAEIOU.".indexOf(ch) != -1 && ch != ' ')
{
newstr += ch;
}
}
}
void display() // function for printing the sentence and new word
{
System.out.println("sentence : "+sent);
System.out.println("word : "+newstr);
}
}
OUTPUT:
sentence : This is a sample sentence.
word : Ths s smlsntnc
Question:
Class Name: Strength
Data Members:
st - String variable to store the original sentence.
Str - String variable to store the upper case version of the sentence.
Member Functions:
Strength() - Default constructor to initialize data members.
main(String[] args) - Main method to create an object of the Strength class, read a sentence,
display the original and upper case sentences, and calculate and display the potential of each
word.
readStr() - Method to accept a sentence from the user and convert it to upper case.
34
show() - Method to print the original sentence and the sentence in upper case.
Potential() - Method to calculate the potential of each word in the sentence. It calculates the sum
of the ASCII values of the characters in each word and displays the word along with its
potential.
Source Code:
import java.util.*;
public class Strength
{
String st, Str; // data member initialisation
Strength() // default constructor
{
st = "";
Str = "";
}
public static void main(String[]args) // drive method
{
Strength in = new Strength();
in.readStr();
in.show();
in.Potential();
}
void readStr() // function for accepting a string
{
Scanner sc = new Scanner(System.in);
System.out.println("enter a sentence");
st = sc.nextLine();
Str = st.toUpperCase();
}
void show() // function for printing the sentence and upper case sentence
{
System.out.println("original sentence = "+st);
System.out.println("sentence in upper case = "+Str);
}
void Potential() // function for calculating potential
{
int l = Str.length(), t=0;
System.out.println("WORD\tPOTENTIAL");
for(int i=0; i<l; i++)
{
int sum=0;
if(Str.charAt(i) == ' ')
{
String s = Str.substring(t, i);
for(int j=t; j<i; j++)
{
sum += (int) Str.charAt(j) - 64;
35
}
System.out.println(s + "\t" + sum);
t = i+1;
}
else if(i == l-1)
{
String s = Str.substring(t, l);
for(int j=t; j<l; j++)
{
sum += (int) Str.charAt(j) - 64;
}
System.out.println(s + "\t" + sum);
}
}
}
}
OUTPUT:
original sentence = The quick brown fox jumps over the lazy dog.
sentence in upper case = THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
WORD POTENTIAL
THE 33
QUICK 71
BROWN 66
FOX 45
JUMPS 74
OVER 60
THE 33
LAZY 58
DOG 40
Question:
Class Name: Fibostring
Data Members:
x - String variable to store the first word.
y - String variable to store the second word.
z - String variable used for generating the Fibonacci series.
n - Integer variable to store the limit.
Member Functions:
Fibostring() - Default constructor to initialize data members.
main(String[] args) - Main method to create an object of the Fibostring class, accept input for
the limit and the first two words, and generate the Fibonacci series of words.
accept() - Method to accept input for the limit and the first two words (x and y) from the user.
36
generate() - Method to generate and print the Fibonacci series of words based on the given limit
(n). It starts with the first two words (x and y) and generates the subsequent words in the series.
Source Code:
import java.util.*;
public class Fibostring
{
String x, y, z; // data member initialisation
int n; // data member initialisation
Fibostring() // default constructor
{
x = "";
y = "";
z = "";
n = 0;
}
public static void main(String[]args) // drive method
{
Fibostring in = new Fibostring();
in.accept();
in.generate();
}
void accept() // function for accepting strings and limit
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the limit");
n = sc.nextInt();
System.out.println("enter the first word");
x = sc.next();
System.out.println("enter the second word");
y = sc.next();
}
void generate() // function for generating fibbonacci series
{
System.out.println("sequence :");
System.out.print(x+" "+y+" ");
for(int i=0; i<(n-2); i++)
{
z = y+x;
System.out.print(z+" ");
x=y; y=z;
}
}
}
37
OUTPUT:
enter the limit
8
enter the first word
A
enter the second word
B
sequence :
A B BA BAB BABBA BABBABAB BABBABABBABBA BABBABABBABBABABBABAB
38
DOUBLE DIMENSIONAL
ARRAYS
39
Question:
Class Name: bsort
Data Members:
x[] - integer array to store elements
l - integer to store the size of the array
t - integer for temporary storage during swapping
Member Functions:
main(String[] args) - Main function to execute the bubble sort algorithm.
Source Code:
import java.util.*;
public class bsort
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the size of the array");
int l = sc.nextInt(), t; // user input
int x[] = new int[l]; // array declaration
System.out.println("enter the elements of the array");
for(int i=0; i<l; i++)
{
x[i] = sc.nextInt(); // user input
}
for(int i=0; i<(l-1); i++) // bubble sorting
{
for(int j=0; j<((l-1)-i); j++)
{
if(x[j] < x[j+1])
{
t = x[j];
x[j] = x[j+1];
x[j+1] = t;
}
}
}
System.out.println("array elements :");
for(int i=0; i<l; i++)
{
System.out.print(x[i]+" "); // printing array
}
}
}
OUTPUT:
40
enter the size of the array
10
enter the elements of the array
6
9
4
2
0
6
9
4
2
0
array elements :
0022446699
Question:
Class Name: ssort
Data Members:
x[] - integer array to store elements
l - integer to store the length of the array
min - integer to store the index of the minimum element during sorting
t - integer for temporary storage during swapping
Member Functions:
main(String[] args) - Main function to execute the selection sort algorithm.
Source Code:
import java.util.*;
public class ssort
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the length");
int l = sc.nextInt(); // user input
int x[] = new int[l], min, t;
System.out.println("enter the elements :");
for(int i=0; i<l; i++)
{
x[i] = sc.nextInt(); // user input
}
System.out.println("elements before sorting :");
for(int i=0; i<l; i++)
{
41
System.out.print(x[i]+" "); // printing array
}
System.out.println();
for(int i=0; i<l-1; i++) // selection sorting
{
min = i;
for(int j=i+1; j<l; j++)
{
if(x[j]<x[min])
{
min = j;
}
}
t = x[i];
x[i] = x[min];
x[min] = t;
}
System.out.println("elements after sorting :");
for(int i=0; i<l; i++)
{
System.out.print(x[i]+" "); // printing array
}
}
}
OUTPUT:
enter the length
10
enter the elements
6
9
4
2
0
6
9
4
2
0
elements before sorting :
6942069420
elements after sorting :
0022446699
Question:
Class Name: bsearch_int
42
Data Members:
x[] - integer array to store elements
p - integer to store the position of the searched number
k - integer flag to determine the success of the search
t - integer for temporary storage during swapping
lb - integer to store the lower bound of the search range
ub - integer to store the upper bound of the search range
Member Functions:
main(String[] args) - Main function to execute the bubble sort and binary search algorithms.
Source Code:
import java.util.*;
public class bsearch_int
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int x[] = new int[10], p, k=0, t, lb=0, ub=9;
System.out.println("enter the elements :");
for(int i=0; i<10; i++)
{
x[i] = sc.nextInt(); // user input
}
for(int i=0; i<9; i++) // bubble sorting
{
for(int j=0; j<(9-i); j++)
{
if(x[j] > x[j+1])
{
t = x[j];
x[j] = x[j+1];
x[j+1] = t;
}
}
}
System.out.println("array :");
for(int i=0; i<10; i++)
{
System.out.print(x[i]+" "); // printing array
}
System.out.println();
System.out.println("enter the number to be searched");
int n = sc.nextInt(); // user input
while(lb<=ub) // binary searching
{
p = (lb+ub)/2;
43
if(x[p]==n)
{
k=1;
break;
}
else if(x[p]<n)
{
lb = p+1;
}
else
{
ub -= 1;
}
}
if(k==1) // number check
{
System.out.println("Search Successful");
}
else
{
System.out.println("the number is not present");
}
}
}
OUTPUT:
enter the elements
6
9
4
2
0
6
9
4
2
0
array :
0022446699
enter the number to be searched:
69
the number is not present
Question:
Class Name: bsearch_str
44
Data Members:
x[] - String array to store elements
p - integer to store the position of the searched number
k - integer flag to determine the success of the search
t - String for temporary storage during swapping
sr - to store the name to be searched
Member Functions:
main(String[] args) - Main function to execute the bubble sort and binary search algorithms on
the string array and find the name.
Source Code:
import java.util.*;
public class bsearch_str
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
String x[] = new String[10], t;
int k=0;
System.out.println("enter the elements :");
for(int i=0; i<10; i++)
{
x[i] = sc.next(); // user input
}
for(int i=0; i<9; i++) // bubble sorting
{
for(int j=(i+1); j<10; j++)
{
if(x[i].compareTo(x[j]) > 0)
{
t = x[i];
x[i] = x[j];
x[j] = t;
}
}
}
System.out.println("array :");
for(int i=0; i<10; i++)
{
System.out.print(x[i]+" "); // printing array
}
System.out.println();
System.out.println("enter the the name to be searched");
char sr= sc.next().charAt(0); // user input
for(int i=0; i<10; i++) // binary searching
{
45
if(x[i].equals(sr)) // number check
{
k=1;
System.out.println(x[i]+" is found");
}
}
if(k==0)
{
System.out.println("the name is not found");
}
}
}
OUTPUT:
enter the elements :
Ahad
Ayaan
Akshitha
Sherin
Jinu
Karan
Shanaia
Ronak
Pratheek
Frank
array :
Ahad Ayaan Akshitha Sherin Jinu Karan Shanaia Ronak Pratheek Jaxx
enter the the name to be searched
Jaxx is found
Question:
Class Name: matrix_sdt
Data Members:
x[][] - integer 2D array for the 1st matrix
y[][] - integer 2D array for the 2nd matrix
s[][] - integer 2D array for the sum of the matrices
d[][] - integer 2D array for the difference of the matrices
st[][] - integer 2D array for the sum of the 1st matrix and its transpose
t1[][] - integer 2D array for the transpose of the 1st matrix
t2[][] - integer 2D array for the transpose of the 2nd matrix
Member Functions:
main(String[] args) - Main function to execute operations on matrices.
Source Code:
46
import java.util.*;
public class matrix_sdt
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int x[][] = new int[3][3], y[][] = new int[3][3], s[][] = new int[3][3], d[][] = new int[3][3], st[][] =
new int[3][3], t1[][] = new int[3][3], t2[][] = new int[3][3];
System.out.println("enter elements for the 1st array");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
x[i][j] = sc.nextInt(); // user input
}
}
System.out.println("enter elements for the 2nd array");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
y[i][j] = sc.nextInt(); // user input
}
}
System.out.println("1st array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
System.out.println("2nd array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(y[i][j] + " "); // printing array
}
System.out.println();
}
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
s[i][j] = x[i][j] + y[i][j]; // sum
47
d[i][j] = x[i][j] - y[i][j]; // difference
t1[i][j] = x[j][i]; // transpose
t2[i][j] = y[j][i]; // transpose
st[i][j] = x[i][j] + t1[i][j]; // sum
}
}
System.out.println("sum of the 1st array and the 2nd array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(s[i][j] + " "); // printing array
}
System.out.println();
}
System.out.println("difference of the 1st array and the 2nd array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(d[i][j] + " "); // printing array
}
System.out.println();
}
System.out.println("transpose of the 1st array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(t1[i][j] + " "); // printing array
}
System.out.println();
}
System.out.println("transpose of the 2nd array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(t2[i][j] + " "); // printing array
}
System.out.println();
}
System.out.println("sum of the 1st array and its transpose :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(st[i][j] + " "); // printing array
48
}
System.out.println();
}
}
}
OUTPUT:
enter elements for the 1st array
6
9
4
2
0
6
9
4
2
enter elements for the 2nd array
0
1
2
3
4
5
6
7
8
1st array
002
244
669
2nd array
012
345
678
sum of 1st and 2nd array
014
589
12 13 17
difference of 1st and 2nd array
0 -1 0
-1 0 -1
0 -1 1
transpose of 1st array
026
046
249
transpose of 2nd array
49
036
147
258
sum of 1st array and its transpose
028
2 8 10
8 10 15
Question:
Class Name: matrix_prod
Data Members:
x[][] - integer 2D array for the 1st matrix
y[][] - integer 2D array for the 2nd matrix
z[][] - integer 2D array for the product of the matrices
Member Functions:
main(String[] args) - Main function to calculate the product of two matrices.
Source Code:
import java.util.*;
public class matrix_prod
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int x[][] = new int[3][3], y[][] = new int[3][3], z[][] = new int[3][3];
System.out.println("enter elements for the 1st array");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
x[i][j] = sc.nextInt(); // user input
}
}
System.out.println("enter elements for the 2nd array");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
y[i][j] = sc.nextInt(); // user input
}
}
System.out.println("1st array :");
for(int i=0; i<3; i++)
{
50
for(int j=0; j<3; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
System.out.println("2nd array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(y[i][j] + " "); // printing array
}
System.out.println();
}
for(int i=0; i<3; i++) // product calculating loop
{
for(int j=0; j<3; j++)
{
z[i][j] = 0;
for(int k=0; k<3; k++)
{
z[i][j] += x[i][k] * y[k][j]; // product calculation
}
}
}
System.out.println("product of the 1st array and the 2nd array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(z[i][j] + " "); // printing array
}
System.out.println();
}
}
}
OUTPUT:
enter elements for the 1st array
6
9
4
2
0
6
9
4
51
2
enter elements for the 2nd array
0
1
2
3
4
5
6
7
8
1st array
002
244
669
2nd array
012
345
678
product of the 1st array and the 2nd array :
12 12 18
36 46 56
72 93 114
Question:
Class Name: matrix_ddasda
Data Members:
m - integer to store the order of the array
x[][] - integer 2D array for the matrix
z[] - integer array to store the resultant single-dimensional array
Member Functions:
main(String[] args) - Main function to take user input, display the matrix, and convert it to a
single-dimensional array.
Source Code:
import java.util.*;
public class matrix_ddasda
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the order of the array");
int m = sc.nextInt(); // user input
52
int x[][] = new int[m][m];
System.out.println("enter elements for the array");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
x[i][j] = sc.nextInt(); // user input
}
}
System.out.println("array :");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
int z[] = new int[m*m], t=0;
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++, t++)
{
z[t] = x[i][j]; // merging into single dimensional array
}
}
System.out.println("resultant array :");
for(int i=0; i<(m*m); i++)
{
System.out.print(z[i] + " "); // printing array
}
}
}
OUTPUT:
enter the order of the array
3
enter elements of the array
6
9
4
2
0
6
9
4
2
array :
53
694
206
942
resultant array :
694206942
Question:
Write a program to accept the integer elements to a DDA of size 3x3 and find the sum of left
diagonal and sum of elements of right diagonal.
Source Code:
import java.util.*;
public class matrix_sumdiag
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int x[][] = new int[3][3], s1=0, s2=0;
System.out.println("enter elements for the array");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
x[i][j] = sc.nextInt(); // user input
}
}
System.out.println("array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
if(i+j == 2)
{
s1 += x[i][j];
}
if(i == j)
{
s2 += x[i][j];
54
}
}
}
System.out.println("sum of right diagonal = "+s1);
System.out.println("sum of left diagonal = "+s2);
}
}
OUTPUT:
enter elements of the array
6
9
4
2
0
6
9
4
2
array :
694
206
942
sum of right diagonal = 13
sum of left diagonal = 8
Question:
Write a program in java to accept the integer elements to a DDA of size 3x3 and print the
elements above the left diagonal.
Source Code:
import java.util.*;
public class matrix_abodiag
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int x[][] = new int[3][3];
System.out.println("enter elements for the array");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
x[i][j] = sc.nextInt(); // user input
}
}
55
System.out.println("array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
System.out.println("array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
if(j>i)
{
System.out.print(x[i][j]+" "); // printing elements above the diagonal
}
else
{
System.out.print(" "); // printing whitespace
}
}
System.out.println();
}
}
}
OUTPUT:
enter elements of the array
6
9
4
2
0
6
9
4
2
array :
694
206
942
array :
94
6
56
Question:
Write a program in java to accept the integer elements to a DDA of size 3x3 and print the
elements below the left diagonal.
Source Code:
import java.util.*;
public class matrix_beldiag
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int x[][] = new int[3][3];
System.out.println("enter elements for the array");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
x[i][j] = sc.nextInt(); // user input
}
}
System.out.println("array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
System.out.println("array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
if(i>j)
{
System.out.print(x[i][j]+" "); // printing elements below the diagonal
}
else
{
System.out.print(" "); // printing whitespace
}
}
System.out.println();
}
}
57
}
OUTPUT:
enter elements of the array
6
9
4
2
0
6
9
4
2
array :
694
206
942
array :
2
94
Question:
Class Name: matrix_beldiag
Data Members:
x[][] - integer 2D array for the matrix
Member Functions:
main(String[] args) - Main function to take user input, display the matrix, and print elements
below the main diagonal.
Source Code:
import java.util.*;
public class matrix_mima
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int x[][] = new int[3][3]; // array declaration
System.out.println("enter elements for the array");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
x[i][j] = sc.nextInt(); // user input
58
}
}
int max = x[0][0], min = x[0][0];
System.out.println("array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(x[i][j] + " "); // array printing
}
System.out.println();
}
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
if(max < x[i][j]) // max check
{
max = x[i][j];
}
if(x[i][j] < min) // min check
{
min = x[i][j];
}
}
}
System.out.println("largest element = "+max);
System.out.println("smallest element = "+min);
}
}
OUTPUT:
enter elements for the array
23
56
1
90
34
72
29
18
61
array :
23 56 1
90 34 72
29 18 61
largest element = 90
smallest element = 1
59
Question:
Class Name: matrix_change
Data Members:
x[][] - integer 2D array for the matrix
t - integer variable used for swapping
Member Functions:
main(String[] args) - Main function to take user input, display the original matrix, interchange
the first and third rows, and display the modified matrix.
Source Code:
import java.util.*;
public class matrix_change
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int x[][] = new int[3][3], t; // array declaration
System.out.println("enter elements for the array");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
x[i][j] = sc.nextInt(); // user input
}
}
System.out.println("array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
for(int i=0; i<3; i++)
{
t = x[0][i];
x[0][i] = x[2][i];
x[2][i] = t;
}
System.out.println("interchanged array :");
for(int i=0; i<3; i++)
{
60
for(int j=0; j<3; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
}
}
OUTPUT:
enter elements for the array
12
33
72
90
14
56
66
32
73
array :
12 33 72
90 14 56
66 32 73
matrix after interchanging the first and last row:
66 32 73
90 14 56
12 33 72
Question:
Class Name: matrix_inousum
Data Members:
x[][] - integer 2D array for the matrix
s1 - integer variable to store the sum of the outer elements
s2 - integer variable to store the sum of the inner elements
Member Functions:
main(String[] args) - Main function to take user input, display the matrix, calculate the sum of
outer and inner elements, and display the sums.
Source Code:
import java.util.*;
public class matrix_inousum
{
61
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int x[][] = new int[3][3], s1=0, s2=0; // array declaration
System.out.println("enter elements for the array");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
x[i][j] = sc.nextInt(); // user input
}
}
System.out.println("array :");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
if(i == 0 || i == 2 || j == 0 || j == 2)
{
s1 += x[i][j]; // calculating sum of the outer elements
}
else
{
s2 += x[i][j]; // calculating sum of the inner elements
}
}
}
System.out.println("sum of the outer elements = "+s1);
System.out.println("sum of the inner elements = "+s2);
}
}
Output:
62
56
66
32
73
array :
12 33 72
90 14 56
66 32 73
sum of the outer elements = 434
sum of the inner elements = 14
Question:
Class Name: matrix_rascend
Data Members:
x[][] - integer 2D array for the matrix
t - integer variable used for swapping elements during sorting
Member Functions:
main(String[] args) - Main function to take user input, display the matrix, sort each row in
ascending order, and display the resultant matrix.
Source Code:
import java.util.*;
public class matrix_rascend
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the order of the array");
int m = sc.nextInt(); // user input
int x[][] = new int[m][m];
System.out.println("enter elements for the array");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
x[i][j] = sc.nextInt(); // user input
}
}
System.out.println("array :");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
63
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
int t=0;
for(int i=0; i<m; i++) // sorting loop
{
for(int j=0; j<(m-1); j++)
{
for(int k=0; k<((m-1)-j); k++)
{
if(x[i][k] > x[i][k+1])
{
t = x[i][k];
x[i][k] = x[i][k+1];
x[i][k+1] = t;
}
}
}
}
System.out.println("resultant array :");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
}
}
Output:
array :
64
1 6 41
5 23 4
5 10 9
resultant array :
1 6 41
4 5 23
5 9 10
Question:
Class Name: matrix_cascend
Data Members:
x[][] - integer 2D array for the original matrix
Member Functions:
main(String[] args) - Main function to take user input, display the original matrix, and display
the matrix after ascending sorting of each column.
Takes user input for the elements of the matrix.
Prints the original matrix.
Sorts each column of the matrix in ascending order.
Prints the matrix after ascending sorting of each column.
Source Code:
import java.util.*;
public class matrix_cascend
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the order of the array");
int m = sc.nextInt(); // user input
int x[][] = new int[m][m];
System.out.println("enter elements for the array");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
x[i][j] = sc.nextInt(); // user input
}
}
System.out.println("array :");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
System.out.print(x[i][j] + " "); // printing array
65
}
System.out.println();
}
int t=0;
for(int i=0; i<(m-1); i++) // sorting loop
{
for(int j=0; j<m; j++)
{
for(int k=0; k<((m-1)-i); k++)
{
if(x[k][j] > x[k+1][j])
{
t = x[k][j];
x[k][j] = x[k+1][j];
x[k+1][j] = t;
}
}
}
}
System.out.println("resultant array :");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
}
}
Output:
array :
1 6 41
66
5 23 4
5 10 9
resultant array :
164
5 10 9
5 23 41
Question:
Class Name: matrix_mirror
Data Members:
x[][] - integer 2D array for the matrix
Member Functions:
main(String[] args) - Main function to take user input, display the original matrix, and display
the mirror image of the matrix.
Source Code:
import java.util.*;
public class matrix_mirror
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the order of the array");
int m = sc.nextInt(); // user input
int x[][] = new int[m][m];
System.out.println("enter elements for the array");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
x[i][j] = sc.nextInt(); // user input
}
}
System.out.println("array :");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
System.out.println("mirror array :");
for(int i=0; i<m; i++)
{
for(int j=m-1; j>=0; j--)
67
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
}
}
Output:
enter the order of the array
3
enter elements for the array
1
2
3
4
5
6
7
8
9
array :
123
456
789
mirror array :
321
654
987
Question:
Class Name: matrix_rot90
Data Members:
x[][] - integer 2D array for the original matrix
y[][] - integer 2D array for the rotated matrix
Member Functions:
main(String[] args) - Main function to take user input, display the original matrix, and display
the rotated matrix.
Source Code:
import java.util.*;
public class matrix_rot90
{
public static void main(String[]args)
68
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the order of the array");
int m = sc.nextInt(); // user input
int x[][] = new int[m][m], y[][] = new int[m][m];
System.out.println("enter elements for the array");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
x[i][j] = sc.nextInt(); // user input
}
}
System.out.println("array :");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
System.out.print(x[i][j] + " "); // printing array
}
System.out.println();
}
for(int i=0; i<m; i++) // transpose of original array
{
for(int j=0; j<m; j++)
{
y[i][j] = x[j][i];
}
}
System.out.println("rotated array :");
for(int i=0; i<m; i++) // mirror of transpose
{
for(int j=m-1; j>=0; j--)
{
System.out.print(y[i][j] + " "); // printing array
}
System.out.println();
}
}
}
Output:
69
3
4
5
6
7
8
9
array :
123
456
789
rotated array :
741
852
963
Question:
Class Name: sort
Data Members:
arr[] - integer array to store elements (size 50)
item - integer to store an element for searching
Member Functions:
sort() - default constructor to initialize arr as a size 50 array, and item as 0
void inpdata() - function for accepting elements for the array
void bubblesort() - function for sorting elements using the bubble sort algorithm
void binsearch() - function for binary searching an element in the sorted array
Source Code:
import java.util.*;
public class sort
{
Scanner sc = new Scanner(System.in);
int arr[], item; // data member initialisation
sort() // default constructor
{
arr = new int[50];
item = 0;
}
public static void main(String[]args) // drive method
{
sort in = new sort();
in.inpdata();
in.bubblesort();
in.binsearch();
70
}
void inpdata() // function for accepting elements
{
System.out.println("enter elements for the array");
for(int i=0; i<50; i++)
{
arr[i] = sc.nextInt();
}
}
void bubblesort() // function for bubble sorting elements
{
int t=0;
for(int i=0; i<49; i++)
{
for(int j=0; j<(49-i); j++)
{
if(arr[j] > arr[j+1])
{
t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;
}
}
}
}
void binsearch() // function for binary searching an element
{
int p=0, k=0, lb=0, ub=49;
System.out.println("enter the number to be searched");
int n = sc.nextInt();
while(lb<=ub)
{
p = (lb+ub)/2;
if(arr[p]==n)
{
k=1;
break;
}
else if(arr[p]<n)
{
lb = p+1;
}
else
{
ub -= 1;
}
}
if(k==1)
71
{
System.out.println("Search Successful, number found at position "+p);
}
else
{
System.out.println("the number is not present");
}
}
}
Output:
Question:
Class Name: matrix_operation
Data Members:
ar[][] - integer 2D array to store elements
m - integer to store the number of rows of the array
n - integer to store the number of columns of the array
x - integer to store the value for changing diagonal elements
Member Functions:
matrix_operation() - constructor to initialize ar as a 10x10 array, and m, n, and x as 0
void getrowcolumn() - function for accepting the number of rows and columns
void getmatrix() - function for accepting elements for the array
void print_mat_and_sum() - function for printing array elements followed by row-wise sum
void change_diagonal() - function for changing elements of the diagonals to x
Source Code:
72
import java.util.*;
public class matrix_operation
{
Scanner sc = new Scanner(System.in);
int ar[][] = new int[10][10], m, n, x; // data member initialisation
public static void main(String[]args) // drive method
{
matrix_operation in = new matrix_operation();
in.getrowcolumn();
in.getmatrix();
in.print_mat_and_sum();
in.change_diagonal();
}
void getrowcolumn() // function for accepting number of rows and colums
{
System.out.println("enter the order of the array");
m = sc.nextInt();
n = sc.nextInt();
}
void getmatrix() // function for accepting elements of the array
{
System.out.println("enter elements for the array");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
ar[i][j] = sc.nextInt();
}
}
}
void print_mat_and_sum() // function for printing array elements followed by row wise sum
{
System.out.println("array :");
for(int i=0; i<m; i++)
{
int s=0;
for(int j=0; j<n; j++)
{
System.out.print(ar[i][j] + " ");
s += ar[i][j];
}
System.out.println(s);
}
}
void change_diagonal() // function for changing elements of the diagonals to x
{
System.out.println("enter the value of x");
x = sc.nextInt();
73
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
if(i == j || i+j == (n-1))
{
ar[i][j] = x;
}
}
}
System.out.println("array after changing diagonals:");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
System.out.print(ar[i][j] + " ");
}
System.out.println();
}
}
}
Output:
74
Question:
Class Name: matrix_image
Data Members:
arr1[][] - integer 2D array to store original elements
arr2[][] - integer 2D array to store mirrored elements
m - integer to store the number of rows of the arrays
n - integer to store the number of columns of the arrays
Member Functions:
matrix_image() - default constructor to initialize arr1 and arr2 as 15x15 arrays, and m and n as
0
matrix_image(int mn, int nn) - parameterized constructor to assign mn to m and nn to n
void acceptMat() - function for accepting elements for the original array
void mirror_image() - function for storing the second array with mirrored elements
void show() - function for printing both the original and mirrored arrays
Source Code:
import java.util.*;
public class matrix_image
{
static Scanner sc = new Scanner(System.in);
int arr1[][], arr2[][], m, n; // data member initialisation
matrix_image() // default constructor
{
arr1 = new int[15][15];
arr2 = new int[15][15];
m = 0;
n = 0;
}
matrix_image(int mn, int nn) // parameterized constructor
{
m = mn;
n = nn;
arr1 = new int[m][n];
arr2 = new int[m][n];
}
void acceptMat() // function for accepting elements of the array
{
System.out.println("enter elements for the array");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
arr1[i][j] = sc.nextInt();
}
75
}
}
void mirror_image() // function for storing second array with mirrored elements
{
arr2 = new int[m][n];
for(int i=0; i<m; i++)
{
for(int j=(n-1), k=0; j>=0; j--, k++)
{
arr2[i][k] = arr1[i][j];
}
}
}
void show() // function for printing the arrays
{
System.out.println("first array :");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
System.out.print(arr1[i][j] + " ");
}
System.out.println();
}
System.out.println("mirrored array :");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
System.out.print(arr2[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[]args) // drive method
{
System.out.println("enter values of m and n");
int x = sc.nextInt();
int y = sc.nextInt();
matrix_image in = new matrix_image(x, y);
in.acceptMat();
in.mirror_image();
in.show();
}
}
Output:
76
enter values of m and n
3
3
enter elements for the array
3
1
2
3
4
5
6
7
8
9
first array :
123
456
789
mirrored array :
321
654
987
Question:
Class Name: DDArray
Data Members:
mat[][] - integer 2D array to store elements
m - integer to store the number of rows of the array
n - integer to store the number of columns of the array
Member Functions:
DDArray(int nr, int nc) - parameterized constructor to assign nr to m and nc to n
void readMatrix() - function for accepting elements for the array
void Sums() - function for calculating and printing the sums of the right and left diagonals and
also boundary elements
void show_Mats() - function for printing the array and inner elements
Source Code:
import java.util.*;
public class DDArray
{
static Scanner sc = new Scanner(System.in);
int mat[][] = new int[50][50], m, n; // data member initialisation
DDArray(int nr, int nc) // parameterised constructor
{
77
m = nr;
n = nc;
}
public static void main(String[]args) // drive method
{
System.out.println("enter values of m and n");
int x = sc.nextInt();
int y = sc.nextInt();
DDArray in = new DDArray(x, y);
in.readMatrix();
in.Sums();
in.show_Mats();
}
void readMatrix() // function for accepting elements of the array
{
System.out.println("enter elements for the array");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
mat[i][j] = sc.nextInt();
}
}
}
void Sums() // function for calculating and printing the sums of the right and left diagonals and also
boundary elements
{
int s1=0, s2=0, s3=0;
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
if(i == j)
{
s1 += mat[i][j];
}
if(i+j == (n-1))
{
s2 += mat[i][j];
}
if(i == 0 || i == (n-1) || j== 0 || j == (n-1))
{
s3 += mat[i][j];
}
}
}
System.out.println("sum of right diagonal = "+s2);
System.out.println("sum of left diagonal = "+s1);
78
System.out.println("sum of boundary elements = "+s3);
}
void show_Mats() // function for printing the array and inner elements
{
System.out.println("array :");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
System.out.println("inner elements :");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
if(i == 0 || i == (n-1) || j== 0 || j == (n-1))
{
System.out.print(" ");
}
else
{
System.out.print(mat[i][j] + " ");
}
}
System.out.println();
}
}
}
Output:
79
sum of right diagonal = 15
sum of left diagonal = 15
sum of boundary elements = 40
array :
123
456
789
inner elements :
Question:
Class Name: Transarray
Data Members:
arr[][] - integer 2D array to store elements
m - integer to store the number of rows of the array
n - integer to store the number of columns of the array
Member Functions:
Transarray() - default constructor to initialize arr as a 20x20 array, and m and n as 0
Transarray(int mm, int nn) - parameterized constructor to assign mm to m and nn to n
void fillarray() - function to accept elements for the array
void Transpose() - function to transpose the array
void displayarray() - function to print both the original and transposed arrays
Source Code:
import java.util.*;
public class Transarray
{
static Scanner sc = new Scanner(System.in);
int arr[][], m, n; // data member initialisation
Transarray() // default constructor
{
arr = new int[20][20];
m = 0;
n = 0;
}
Transarray(int mm, int nn) // parametrised constructor
{
m = mm;
n = nn;
arr = new int[m][n];
}
public static void main(String[]args) // drive method
{
80
System.out.println("enter values of m and n");
int x = sc.nextInt();
int y = sc.nextInt();
Transarray in = new Transarray(x, y);
in.fillarray();
in.Transpose();
in.displayarray();
}
void fillarray() // function for accepting elements of the array
{
System.out.println("enter elements for the array");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
arr[i][j] = sc.nextInt();
}
}
}
void Transpose() // function for transposing
{
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
arr[i][j] = arr[j][i];
}
}
}
void displayarray() // function for printing the arrays
{
System.out.println("Original Array :");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
System.out.print(arr[j][i] + " ");
}
System.out.println();
}
System.out.println("Transpose of the Array:");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
81
}
}
}
Output:
Question:
Class Name: DiagShow
Data Members:
A[][] - Integer 2D array to store elements
M - Integer variable representing the size of the square array
Member Functions:
DiagShow() - Default constructor to initialize the array and size
DiagShow(int mm) - Parameterized constructor to initialize the array with a given size
void read() - Function to accept elements for the array from the user
void show() - Function to print the original array
void upper() - Function to print the upper diagonal elements of the array
void lower() - Function to print the lower diagonal elements of the array
Source Code:
import java.util.*;
public class DiagShow
82
{
static Scanner sc = new Scanner(System.in);
int A[][], M; // data member initialisation
DiagShow() // default constructor
{
A = null;
M = 0;
}
DiagShow(int mm) // parametrised constructor
{
M = mm;
A = new int[M][M];
}
public static void main(String[]args) // drive method
{
System.out.println("enter the value of M");
int x = sc.nextInt();
if(x>2 && x<10)
{
DiagShow in = new DiagShow(x);
in.read();
in.show();
in.upper();
in.lower();
}
}
void read() // function for accepting array elements
{
System.out.println("enter elements for the array");
for(int i=0; i<M; i++)
{
for(int j=0; j<M; j++)
A[i][j] = sc.nextInt();
}
}
void show() // function for printing the original array
{
System.out.println("Original Array :");
for(int i=0; i<M; i++)
{
for(int j=0; j<M; j++)
System.out.print(A[i][j] + " ");
System.out.println();
}
}
void upper() // function for printing the upper diagonal elements
{
System.out.println("Upper Diagonal Array Elements:");
83
for(int i=0; i<M; i++)
{
for(int j=0; j<M; j++)
{
if(i+j <= M-1)
System.out.print(A[i][j] + " ");
}
System.out.println();
}
}
void lower() // function for printing the lower diagonal elements
{
System.out.println("Lower Diagonal Array Elements:");
for(int i=0; i<M; i++)
{
for(int j=0; j<M; j++)
{
if(i+j > M-1)
System.out.print(A[i][j] + " ");
else
System.out.print(" ");
}
System.out.println();
}
}
}
Output:
84
6
Lower Diagonal Array Elements:
5
78
Question:
Class Name: CircularArray
Data Members:
arr[][] - Integer 2D array to store elements in a circular arrangement
n - Integer variable representing the size of the circular array
Member Functions:
CircularArray() - Default constructor to initialize the array and set the initial size
void accept() - Function to accept the size of the circular array (n) from the user and initialize
the array
void arrange() - Function to arrange elements in a circular pattern within the array
void display() - Function to display the elements of the circular array in a formatted manner
Source Code:
import java.util.*;
public class CircularArray {
int arr[][], n;
CircularArray() {
arr = null;
n = 0;
}
void accept() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter value of n:");
n = sc.nextInt();
arr = new int[n][n];
}
void arrange() {
int c=1, left=0, right=n-1, top=0, bottom=n-1;
while(c <= (n*n)) {
for(int i=left; i<=right; i++)
arr[top][i] = c++;
top++;
85
bottom--;
Output:
Enter value of n:
3
1
2
3
4
5
6
7
8
9
Array:
1 2 3
8 9 4
7 6 5
86
RECURSIONS
87
Question:
Class name: factorial
Data members:
n: int variable to store a number
f: int variable to store the factorial
Member functions:
factorial() : default constructor to assign 0 to n and 1 to f
int fact(int num): find and return the factorial of a number using recursion
void getFactorial(): accept the value of n and store the factorial in f by invoking the recursive
function fact() and also print f.
Source Code:
import java.util.*;
class factorial
{
public int fact (int n)
{
if(n==1)
return 1;
else return (n*fact(n-1));
}
public static void main()
{
factorial obj=new factorial();
Scanner sc= new Scanner (System.in);
System.out.println("Enter a number:");
int in=sc.nextInt();
System.out.println("factorial:"+obj.fact(in));
}
OUTPUT:
Enter a number:
5
Factorial:120
Question:
Class name: poweris
Data members:
base: int variable to store a number
expn: int variable to store the exponent/power
p: to store the value of ‘base’ raised to’expn’
Member functions:
88
poweris() : default constructor
int power(int n, int m): find and return n raised to m using recursive technique
void findresults(): accept the value of ‘base’ and ‘expn’ and store base raised to expn in p, by
invoking the recursive function power().
Void printresults():using suitable documentation print value in p
Source Code:
import java.util.*;
class poweris
{
public int pow(int x, int y)
{
if(y==1)
return x;
if(y==0)
return 1;
else
return (x*pow(x,y-1));
}
public static void main()
{
poweris obj=new poweris ();
Scanner sc= new Scanner (System.in);
System.out.println("Enter the base and exponent:");
int x=sc.nextInt();
int y=sc.nextInt();
System.out.println("Power: "+obj.pow(x,y));
}
}
OUTPUT:
Enter the base and exponent:
2
3
Power : 8
Question:
Class Name: RecFact
Data members:
n:int variable to store num
r:double variable to store number
Member functions:
RecFact():Default constructor to initialise data members
int factorial(int v):To find factorial v using recursive technique
89
void result():Compute and print the answer using the above
recursive function
Source Code:
import java.util.*;
class RecFact
{
int n,r;
public RecFact()
{
n=0;
r=0;
}
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of n and r:" );
n=sc.nextInt();
r=sc.nextInt();
}
int factorial(int v)
{
if(v==1)
return 1;
else
return (v*factorial(v-1));
}
void result()
{
double F=(factorial(n))/(factorial(r)*factorial(n-r));
System.out.println("F= " +F);
}
public static void main()
{
RecFact obj=new RecFact();
obj.accept();
obj.result();
}
}
OUTPUT:
Enter the value of n and r:
2
1
F= 2.0
90
Question:
Class Name: series
Data members:
x:int variable to store number
n:int to store limit
f:int to store factorial
p:int to store power
sum:int to store sum
Member functions:
series(): Default constructor to initialise data members
series(int nx, int nn): Parameterized contructor to assign nx to x and nn to n.
intFact(int d): Returns Factorial of d using recursive technique
int power(int a, int b): Returns a to the power of b using recursive technique
voidsumseries(): Finds and displays sum
Source Code:
import java.util.*;
class series
{
int x, n, f, p;
double sum;
series()
{
x=0;n=0;f=0;p=0;
sum=1.0;
}
series(int nx, int nn)
{
x=nx;
n=nn;
}
int Fact(int d)
{
if(d==1)
return 1;
else
return (d*Fact(d-1));
}
int poweris (int a, int b)
{
if(b==1)
return b;
else
return (a*poweris (a,b-1));
}
91
void sumseries()
{
for(int i=2;i<=n;i++)
sum+=(double)poweris (x,i)/(double)(Fact(i+1));
System.out.println("sum: "+sum);
}
public static void main()
{
series obj=new series(2,2);
obj.sumseries();
}
}
OUTPUT:
sum: 0.3333333333333333
Question:
Class Name: Armstrong
Data members:
long num: variable to store number
long cube: variable to store cube
Member functions:
Armstrong(long nx):Parametrized constructor to assign nx to
num
long RecCube_Digit(double m,int n):To find and return q^3
long RecDigitSum(long N):Extract digits of N using recursion and
find the sum of their cubes
void display():To print the result by invoking the function and
checking if the number is armstrong or not
Source Code:
import java.util.*;
class Armstrong
{
long num,cube;
Armstrong(long nx)
{
num=nx;
}
long RecCubeDigit(long q)
{
return (q*q*q);
}
long RecGetDigitSum(long N)
92
{
if(N==0)
return 0;
else
cube=RecCubeDigit(N%10)+ RecGetDigitSum(N/10);
return cube;
}
boolean isArmstrong()
{
if(RecGetDigitSum(num)==num)
return true;
else
return false;
}
void display()
{
if(true)
System.out.println(num+" is an Armstrong number ");
else
System.out.println(num+" is not an Armstrong number ");
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number:" );
int n=sc.nextInt();
Armstrong obj=new Armstrong(n);
obj.display();
}
}
OUTPUT:
Enter a number:
370
370 is an Armstrong number
Question:
Class Name: Disarium
Data members:
int num:int variable to store the no.
int size:int variable to store the no. of digits
Member functions:
Disarium(int nn): Parameterized constructor to initialise data
members
void CountDigit():Counts the total number of digits and assigns
93
it to the variable size
int sumofDigits():Returns the no.n to the power of their
respective position p using recursive technique
void check():checks if the number is disarium and dsiplay
appropriate message
Source Code:
import java.util.*;
class Disarium
{
int num,cube;
Disarium(int nx)
{
num=nx;
}
int RecPowerDigit(int q,int n)
{
return (int)Math.pow(q,n);
}
int RecGetDigitSum(int N)
{
int n=0;
for(int d=N;d>0;d/=10)
n+=1;
if(N==0)
return 0;
return(RecPowerDigit(N%10,n) + RecGetDigitSum(N/10));
}
boolean isDisarium(int x)
{
cube = RecGetDigitSum(x);
if(cube==x)
return true;
return false;
}
void display()
{
for(int i=10;i<=num;i++)
if(isDisarium(i))
System.out.println(i+" is a Disarium number.");
}
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("enter num");
int x = sc.nextInt();
Disarium ob=new Disarium(x);
94
ob.display();
}
}
OUTPUT:
Enter num
89
89 is a Disarium number
Question:
Class Name: Emirp
Data members:
int n:variable to store the number
int rev:variable to the reverse
int f:variable to stote the divisor
Member functions:
Emirp(int nn):assigns nn to n,rev to 0 and f to 2
int isprime(int x):checks if the number is prime using recursion, if prime returns 1 else 0
void isEmirp():reverses the given number and prime checks both original number and reverse,
displays appropriate message
Source Code:
import java.util.*;
class Emirp
{
int n,rev,f=1;
Emirp(int nn)
{
n=nn;
}
int isPrime(int f)
{
if(n==f)
return 1;
if(n%f==0)
return 0;
return(isPrime(f+1));
}
void isEmirp()
{
for(int d=n;d>0;d/=10)
rev=d%10 + rev*10;
int a=isPrime(2);
n=rev;
95
int b=isPrime(2);
if(a==1 && b==1)
System.out.println("It is an Emirp number.");
else
System.out.println("It is an not Emirp number.");
}
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("enter n");
int x = sc.nextInt();
Emirp ob=new Emirp(x);
ob.isEmirp();
}
}
OUTPUT:
Enter n
13
It is an Emirp number.
96
INHERITANCE
97
QUESTION 1:
Define a class BasePro and a derived class DervPro to find the product of two numbers.
The class details are given below:
Data Members:
double n1 - double variable to store a number
double n2 - double variable to store another number
Member Functions:
void enter() : accept n1 and n2
void show() : display n1 and n2
Data Members:
double result - double variable to store the product
Member Functions:
void prod() : multiply and store the product in result
void display() : display n1 and n2 and the result
SOURCE CODE:
import java.util.*;
public class basePro
{
double n1,n2;
public void enter ()
{
Scanner sc = new Scanner (System.in);
System.out.println("Enter the values of n1 and n2");
n1 = sc.nextInt();
n2=sc.nextInt();
}
public void show()
{
System.out.println("First number: "+n1);
System.out.println("Second number: "+n2);
}
}
98
public void prod()
{
enter();
result = n1*n2;
}
public void display()
{
show();
System.out.println("Product="+result);
}
}
Output:
QUESTION 2:
A super class student defines information such as name, roll number and date of birth, while
another class marks defines the marks in various subjects, percentage, and grade of the
students, the details of both the classes are given below:
Data members:
nam,dobirth: string variables to store, name and date of birth of the students
roll: integer variable to store the roll no.
Member functions:
Public void inputdata(): to input the value of all data members.
Public voice print data (): different the data members.
Data members:
tot, per: double variables is two marks in percentage.
gd: character character available to store the grade as per the following criteria:
Percentage Grade
99
>=85% A
<40 D
Member functions:
public void, readData(): input, the name, date of birth, rno, and total marks.
public void compute ():to find and store percentage and grade.
void showdata (): to display the data members of both classes.
SOURCE CODE:
import java.util.*;
class student
{
String nam, dobirth;
int roll;
public void inputdata()
{
Scanner sc = new Scanner (System.in);
System.out.println("Enter name of student:");
nam=sc.nextLine();
System.out.println("Enter date of birth:");
dobirth=sc.nextLine();
System.out.println("Enter roll number:");
roll=sc.nextInt();
}
public void printdata()
{
System.out.println("Name: "+nam+"\nDate of Birth: "+dobirth+"\nRoll number: "+roll);
}
}
import java.util.*;
class marks extends student
{
double tot,per;
char gd;
void readData()
{
100
inputdata();
Scanner sc = new Scanner(System.in);
System.out.println("Enter total marks:");
tot = sc.nextDouble();
}
public void compute()
{
per=(tot/500.0)*100.0;
if(per>=85)
gd='A';
else if(per>=60 && per<85)
gd='B';
else if(per>=40 && per<60)
gd='C';
else
gd='D';
}
void showData()
{
printdata();
System.out.println("Percentage: "+per+"\nGrade: "+gd);
}
}
OUTPUT:
101
QUESTION 3
A superclass banks contains details of account holders, such as name and account number when
the subclass Deposit defines the variable to find fixed deposit.
Data members:
nam: string variable to store the name of account holder.
accno: long variable to store the account number.
Member functions:
Bank(long x, String na): parameter is constructor to assign x to accno and na to name.
void display (): different data members.
Member functions:
Deposit (double q): to invoke the super class constructor and initialise q to amt.
void display (): To display the date of members of both the classes.
SOURCE CODE:
import java.util.*;
public class Bank
{
long accno;
String nam;
Bank(long x, String na)
{
accno = x;
nam = na;
}
public void display()
{
System.out.println("Account number: "+accno);
System.out.println("Name of Account holder: "+nam);
}
}
class Deposit extends Bank
{
double amt;
Deposit(long x, String n, double q)
{
super(x,n);
amt=q;
102
}
public void display()
{
super.display();
System.out.println("Amount :"+amt);
}
}
Output:
Account number: 540861894
Name of Account holder: Rajapasa
Amount :5000.0
QUESTION 4:
A super class EmployeeData and a subclass Overtime has been defined with the following
specifications.
Data Members:
empcode - integer to store employee code
basicpay - double variable to store the basic salary
Member Functions:
EmployeeData() : Default constructor to initialise the variables
EmployeeData(int c, int b) : constructor to assign c to empcode and b to basic pay
void printdata() : Print the values of empcode and basic pay with suitable message
Data Members:
ndays - integer variable to store the number of days worked extra
rate - double variable to store the rate per day
Member Functions:
Overtime(...) : Parameterized constructor to assign values to the members of both
the classes
void calculatesal() : Calculate the total salary as basicpay + ndays worked * rate
void printdata() : Display the data members of both the classes and the total salary.
103
SOURCE CODE:
import java.util.*;
class EmployeeData
{
int empcode;
double basicpay;
EmpolyeeData(int c, double p)
{
empcode=c;
basicpay=p;
}
void printdata()
{
System.out.println("Employee Code= " +empcode);
System.out.println("Basic Pay= " +basicpay);
}
}
class Overtime extends EmployeeData
{
int ndays;
double rate;
Overtime(int c1, double p1, int nd, double r)
{
super(c1,p1);
ndays=nd;
rate=r;
}
double calculate_sal()
{
double res = basicpay +(ndays*rate);
return res;
}
void printdata()
{
super.printdata();
System.out.println("Total Salary ="+calculate_sal());
}
}
OUTPUT:
Employee Code= 58
Basic Pay= 50000.0
Total Salary =55000.0
104
QUESTION 5:
No. of calls Rate
0-100 rental charge
101-200 60p per call + rental charge
201-300 80p per call + rental charge
above 300 $1 per call + rental charge
SOURCE CODE:
class Detail
{
String name;
String address;
long telno;
double rent;
105
class Bill extends Detail
{
int n;
double amt;
Bill(String na, String ad, long no, double r, int n1,double amt1)
{
super(na,ad,no,r);
n=n1;
amt=amt1;
}
void calc()
{
if(n<=100)
amt=rent;
else if (n>100 && n<=200)
amt = rent+(n*0.60);
else if(n>200&&n<=300)
amt=rent+(n*0.80);
else
amt=rent+(n*1.0);
}
void show()
{
super.show();
System.out.println("Amount to be paid:"+amt);
}
}
OUTPUT:
Customer Details:
Customer Name: John Doe
Telephone Number: 1234567890
Rent: 50.0
Address: 123 Main St
Bill Details:
Customer Name: John Doe
Telephone Number: 1234567890
Rent: 50.0
Address: 123 Main St
Amount to be paid: 130.0
QUESTION 6:
A Super class record has been defined to store the names and ranks of 50 students. Define a
subclass rank to find the highest rank along with the name.
106
The details of both the classes are given below.
Data Members:
String name[ ] - To store the names of the students
int rank[ ] - to store the ranks of the students
Member Functions:
Record() ; Default constructor to initialise the arrays
void readValues() : To accept the names and ranks of 50 students
void display(): Display the names and the corresponding ranks
Data Members:
int index - integer variable to store the highest rank index
Member Functions:
Rank(): Default constructor to initialise the variables by invoking the base class
constructor
void highest() : Find the index of the top most rank and storage in the index variable
without sorting the array
void display() : Display the names and the ranks along with the name having the top
most rank
SOURCE CODE:
import java.util.*;
public class Record
{
String name[]=new String [3];
int rank[] =new int [3];
int i;
Record()
{
for(i=0;i<3;i++)
{
name[i]=" ";
rank[i]=0;
}
}
void readvalues()
{
Scanner sc=new Scanner (System.in);
System.out.println("Enter the name and rank of 3 students");
107
for(i=0;i<3;i++)
{
name[i]=sc.next();
rank[i]=sc.nextInt();
}
}
void display()
{
System.out.println("The names and corresponding ranks of the students are: ");
for(i=0;i<3;i++)
{
System.out.println(name[i]+"\t\t"+rank[i]);
}
}
}
import java.util.*;
public class Rank extends Record
{
int index;
Rank()
{
super();
index=0;
}
void highest()
{
readvalues();
index=0;
for(int i=1;i<3;i++)
{
if(rank[i]<rank[index])
index=i;
}
}
void display()
{
super.display();
System.out.println(name[index]+"\t\t"+rank[index]);
System.out.println("highest rank ");
}
public static void main(String args[])
{
Rank obj=new Rank();
obj.highest();
obj.display();
}
108
}
OUTPUT:
The names and corresponding ranks of the students are:
Cleo 2
Abraham 5
Josh 3
Cleo 2
highest rank
QUESTION 7:
A line on a plane can be represented by 2 coordinates i.e. point P1(x1,y1) and P2(x2,y2).
A superclass Plane is defined to represent a line and a subclass Circle to find the length of the
radius and area of the circle by using the required data members of the class. The details of both
the classes are given below.
SOURCE CODE:
import java.util.*;
public class Plane
109
{
double x1, y1;
Plane(double nx, double ny)
{
x1=nx;
y1=ny;
}
void show()
{
System.out.println("The coordinates of the first point are: "+"("+x1+","+y1+")");
}
}
import java.util.*;
public class Circle extends Plane
{
double x2, y2, radius, area;
Circle(double nx, double ny,double nx2, double ny2)
{
super(nx, ny);
x2=nx2;
y2=ny2;
radius =0.0;
area=0.0;
}
void findradius()
{
radius=(Math.sqrt(Math.pow((x2-x1),2)+Math.pow((y2-y1),2)))/2;
}
void findarea()
{
area=(22/7)*Math.pow(radius,2);
}
void show()
{
super.show();
System.out.println("The coo of the 2nd point are: "+"("+x2+","+y2+")");
System.out.println("Radius = "+radius);
System.out.println("Area = "+area);
}
public static void main(String args[])
{
Circle obj=new Circle(2,5,7,3);
obj.findradius();
obj.findarea();
obj.show();
}
}
110
OUTPUT:
QUESTION 8:
A super class Author
While another class Booklist
Data members:
bookno: long to store book no.
bookname : name of book
price: store the price of the book in decimals
edition: int to store edition no.
Functions:
Booklist(......): to assign data members of both classes
void show()-display all data members
SOURCE CODE:
class Author
{
long authorno;
String name;
Author(long nx, String n)
{
authorno=nx;
name=n;
}
111
void show()
{
System.out.println("Author Name: "+name);
System.out.println("Author Number: "+authorno);
}
}
OUTPUT:
QUESTION 9:
The length of the radius between the two endpoints P1(x1,y1) and P2(x2,y2) is calculated as r=
(𝑥2 − 𝑥1)² + (𝑦2 − 𝑦1)²/2
A class Point represents the point on a 2D plane while another class Distance calculates the
length of the radius and the midpoint.
112
Class Name: Point
Data members:
x1, y1: to store the coordinates of the point P1 in decimal
Member Function:
Point(double nx1, double ny1): Parameterized constructor to assign nx1 to x1 and ny1 to
y1.
abstract void FindDistance(): to declare the abstract type function
abstract void FindMidPoint(): to declare the abstract type function
void show(): print values of data members with suitable headings
Member Functions:
Distance(...): Parameterized constructor to initialise data members of both the classes
abstract void FindDistance(): define the abstract function, find the length of the radius
using the given formula
abstract void FindMidPoint(): calculate the midpoint using the formula
midx=(x1+x2)/2 midy=(y1+y2)/2
void show(): to print data member of both the classes
SOURCE CODE:
113
{
super(nx1, ny1);
x2=nx2;
y2=ny2;
dist = d;
midx=mx;
midy=my;
}
void FindDistance()
{
dist=Math.sqrt(Math.pow((x2-x1),2)+Math.pow((y2-y1),2))/2.0;
}
void FindMidPoint()
{
midx=(x1+x2)/2.0;
midy=(y1+y2)/2.0;
}
void show()
{
super.show();
System.out.println("Radius="+dist);
System.out.println("Midpoint="+midx+","+midy);
}
}
OUTPUT:
x1=3.0
y1=4.0
Radius=5.0
Midpoint=0.0,0.0
114
DATA STRUCTURES
115
Question:
Class Name: Queue
Data Members:
q[] - integer 1D array to store queue elements
r - integer variable representing the rear end of the queue
l - integer variable representing the front end of the queue
Member Functions:
Queue() - Default constructor to initialize the queue array and set default values to r and l
void insert(int x) - function to insert element x into the queue
void delete() - function to delete the front element from the queue
void display() - function to display the elements of the queue
Source Code:
import java.util.*;
public class Queue {
int q[] , r, l;
Queue() {
q = new int[10];
r = -1;
l = 0;
}
void insert(int x) {
if(r == 9)
System.out.println("Queue Overflow");
else
q[++r] = x;
}
void delete() {
if(l > r)
System.out.println("Queue Underflow");
else
System.out.println("Front Element: "+q[l++]);
}
void display() {
for(int i=l; i<=r; System.out.print(q[i] + " "), i++);
System.out.println();
}
public static void main(String[]algs) {
Queue in = new Queue();
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("select operation from options below:\n1: insert\n2: delete\n3: display");
String s = sc.next();
switch(s) {
case "insert":
116
System.out.println("Enter element to be inserted:");
int x = sc.nextInt();
in.insert(x);
break;
case "delete":
in.delete();
break;
case "display":
in.display();
break;
OUTPUT
Question:
Class Name: Cinema
Data Members:
ele[] - integer 1D array to store cinema items
rear - integer variable representing the rear end of the cinema
front - integer variable representing the front end of the cinema
Member Functions:
Cinema() - Default constructor to initialize the cinema array and set default values to rear and
front
void pushitem(int x) - function to push item x into the cinema
void popitem() - function to pop the front item from the cinema
117
void printitems() - function to print the items in the cinema
Source Code:
import java.util.*;
public class Cinema {
int ele[] , rear, front;
Cinema() {
ele = new int[10];
rear = -1;
front = 0;
}
void pushitem(int x) {
if(rear == 9)
System.out.println("Overflow");
else
ele[++rear] = x;
}
void popitem() {
if(front > rear)
System.out.println("Underflow");
else
System.out.println("Front Element: "+ele[front++]);
}
void printitems() {
for(int i=front; i<=rear; System.out.print(ele[i] + " "), i++);
System.out.println();
}
public static void main(String[]algs) {
Cinema in = new Cinema();
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("select operearation from options below:\n1: push\n2: pop\n3: print");
String s = sc.next();
switch(s) {
case "push":
System.out.println("Enter element to be pushed:");
int x = sc.nextInt();
in.pushitem(x);
break;
case "pop":
in.popitem();
break;
case "print":
in.printitems();
118
break;
OUTPUT
select operearation from options below:
1: push
2: pop
3: print
push
Enter element to be pushed:
1
Do you want to continue? (yes/no)
yes
select operearation from options below:
1: push
2: pop
3: print
push
Enter element to be pushed:
2
Do you want to continue? (yes/no)
yes
select operearation from options below:
1: push
2: pop
3: print
push
Enter element to be pushed:
3
Do you want to continue? (yes/no)
yes
select operearation from options below:
1: push
2: pop
3: print
push
Enter element to be pushed:
4
Do you want to continue? (yes/no)
119
yes
select operearation from options below:
1: push
2: pop
3: print
push
Enter element to be pushed:
5
Do you want to continue? (yes/no)
yes
select operearation from options below:
1: push
2: pop
3: print
print
12345
Do you want to continue? (yes/no)
yes
select operearation from options below:
1: push
2: pop
3: print
pop
Front Element: 1
Do you want to continue? (yes/no)
yes
select operearation from options below:
1: push
2: pop
3: print
print
2345
Do you want to continue? (yes/no)
no
Question:
Class Name: Operate
Data Members:
Operate() - Default constructor to initialize the array and set the initial position
void accept() - Function to accept the length of the array from the user and initialize the array
120
void insert() - Function to insert an element at a specified position in the array
void delete() - Function to delete an element at a specified position in the array
void print() - Function to print the elements of the array
Source Code:
import java.util.*;
public class Operate {
int arr[], pos;
Scanner sc = new Scanner(System.in);
Operate() {
arr = null;
pos = 0;
}
void accept() {
System.out.println("enter length of the array:");
int len = sc.nextInt();
arr = new int[len];
}
void insert() {
System.out.println("enter position of the element to be inserted:");
pos = sc.nextInt();
System.out.println("enter the element to be inserted:");
arr[pos-1] = sc.nextInt();
}
void delete() {
System.out.println("enter position of the element to be deleted:");
pos = sc.nextInt();
arr[pos-1] = 0;
}
void print() {
for(int i=0; i<arr.length; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String[]args) {
Operate in = new Operate();
Scanner sc = new Scanner(System.in);
in.accept();
while(true) {
System.out.println("select from the below options:\n1: insert\n2: delete\n3: print");
String s = sc.next();
switch(s) {
case "1":
in.insert();
break;
121
case "2":
in.delete();
break;
case "3":
in.print();
break;
122
select from the below options:
1: insert
2: delete
3: print
3
12045
Question:
Class Name: Stack
Data Members:
arr[] - integer array to store elements of the stack
m - integer to represent the size of the stack
sp - integer representing the stack pointer
Member Functions:
Stack(int mm) - parameterized constructor to initialize the stack with size mm
void PUSH(int x) - function to push an element onto the stack
void POP() - function to pop the top element from the stack
void PEEK() - function to display the top element of the stack without removing it
void DISPLAY() - function to display all elements of the stack
Source Code:
import java.util.*;
public class Stack
{
int arr[], m, sp; // data member initialisation
Stack(int mm) // parameterised constructor
{
m = mm;
arr = new int[m];
sp = -1;
}
public static void main(String[]args) // drive method
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of m");
int t = sc.nextInt(); // user input
Stack in = new Stack(t);
while(true)
{
System.out.println("Enter 1 to PUSH");
System.out.println("Enter 2 to POP");
System.out.println("Enter 3 to PEEK");
System.out.println("Enter 4 to DISPLAY");
int x = sc.nextInt(); // user input
switch(x) // switch statement
{
case 1:
123
System.out.println("Enter the number");
int n = sc.nextInt();
in.PUSH(n);
break;
case 2:
in.POP();
break;
case 3:
in.PEEK();
break;
case 4:
in.DISPLAY();
break;
124
System.out.println("Stack :");
for(int i=sp; i>=0; i--)
System.out.println(arr[i]);
}
}
OUTPUT
125
yes
Enter 1 to PUSH
Enter 2 to POP
Enter 3 to PEEK
Enter 4 to DISPLAY
1
Enter the number
5
Enter 'yes' if you want to continue
yes
Enter 1 to PUSH
Enter 2 to POP
Enter 3 to PEEK
Enter 4 to DISPLAY
2
Enter 'yes' if you want to continue
yes
Enter 1 to PUSH
Enter 2 to POP
Enter 3 to PEEK
Enter 4 to DISPLAY
3
Last Element = 4
Enter 'yes' if you want to continue
yes
Enter 1 to PUSH
Enter 2 to POP
Enter 3 to PEEK
Enter 4 to DISPLAY
4
Stack :
4
3
2
1
126