Sei sulla pagina 1di 157

Computer

Assignment
On

By-

Bhargav Parashar 12 S
Acknowledgement

I would like to thank my Computer


Science Teacher ,
Mr. Dulu Dutta, without the guidance and
support of whom I would not have been
able to complete this project.

I would also like to thank my parents who


helped me immensely in making the
completion of this project a success.

Thank you.

Bhargav Parashar 12 S Page | 2


Index

SL.NO TOPIC PAGE


. NO.
NUMBER PROGRAMS
1. Write a program to check if a number is circular 6
prime
2. Write a program to check if a number is evil number 10
3. Write a program to check if a number is a Kaprekar 14
number
4. Write a program to check if a number is prime 17
palindrome
5. Write a program to check if a number is a pronic 20
number
6. Write a program to check if a number is a Unique 22
number
7. Write a program to check if a number is a Harshad 25
number
8. Write a program to print all the Twin Prime numbers 27
within a given range.
PATTERNS
9. Write a program to display a pattern of stars with 31
reduction of start from the middle from the next line.
10. Write a program to display a pattern of stars with a 33
void shaped as an arrow
11. Program to display a pattern of a hollow inverted 37
pyramid on top of a hollow pyramid with *:

MATRIX AND ARRAY


12. Write a program to input an array and print boundary 42
elements
13. Write a program in Java to input a 2-D square matrix 45
and
check whether it is a Scalar Matrix or not.
14. Write a program in Java to fill a square matrix of size 49
* n*n in a circular fashion (clockwise)
15. Write a program in Java to input a 2-D square matrix 53
and check whether it is a Diagonal Matrix or not.
16. Write a program to check if the given matrix is 57
Symmetric or not.
17. Write a program to find the SADDLE POINT for the 61
matrix.
Bhargav Parashar 12 S Page | 3
18. Write a program to input a matrix and transpose it. 66
19. Write a program to input two matrices and print their 69
multiplication.
20. Write a program to input a matrix and print its 74
diagonal and secondary-diagonal summations.
21. Write a program to input a matrix and sort columns 77
independently.
22. Write a program to input a matrix and print its
boundary sum and internal sum. 81
23. Write a program which first inputs two integers, the 85
first between 1 and 12 (both inclusive) and second
between 0 and 59 (both inclusive) and then prints
out the time they represent, in words,using arrays.
STRING HANDLING
24. Write a program to count and display the 90
palindromic words in the sentence.
25. Write a program to count the number of words and 94
consonants of a given string.
26. Write a program to count the frequency of words 97
starting with a vowel.
27. Write a program to input a sentence and interchange 99
the first alphabet with the last alphabet for each
word in the sentence.
OBJECT PASSING
28. Program to merge two integer arrays. 103
DATA STRUCTURES
29. Write a program to push and pop characters in an 110
array-based queue.
30. Write a program to push elements from rear and pop 113
numbers from front end of an array-based stack.
31. Write a program to show Last in, first out in an 117
array based queue
32. Write a program to add and remove integers from 122
either ends in an queue based array.
33. Write a program to push and pop characters in an 130
array-based stack.
INHERITANCE
34. Write a program to store the names and ranks of 50 135
students. Find the highest rank and his name using
the concept of inheritance.
35. Write a program to store the details of a customer. 139
Compute the monthly telephone charge of the
customer using inheritance.
36. Write a program to calculate the area and perimeter 143
of a parallelogram using the concept of inheritance.
Bhargav Parashar 12 S Page | 4
37. Write a program to find the radius and area of a 147
circle based on coordinates using the concept of
inheritance.
RECURSION
38. Write a program to calculate the sum of the series: 152
X2/1! + x4/3! + x6/5! + ..+ xn/(n-1)!
39. Write a program to interchange upper case to lower 156
case wordsand vice versa.
40. Write a program to check whether a number is a 159
happy number.

NUMBER PROGRAMS

Bhargav Parashar 12 S Page | 5


1) Program to check if a number is
circular prime:
ALGORITHM:
/*Algorithm for main()
* Step 1: Start of Algorithm
* Step 2: Input a number to be checked and store it in
integer variable n
* Step 3: Call the function isCircularPrime(int n)
* Step 4: End of Algorithm for main()
* Algorithm for isCircularPrime()
* Step 1: Start of Algorithm
* Step 2: Create a do-while() loop which is exit controlled
untill the value of 'a' becomes equal to n,
if a==n go to Step 7, else go to Step 2
* Step 3: Create a dublicate value of 'n' and store it in 'a'
* Step 4: Print 'a'
* Step 5: Check if 'a' is Prime by callinf function isPrime(a)
* Step 6: If 'a' is not Prime, change value of integer
variable 'f' to 1
* Step 7: Then value of 'a' is circulated by circulating the
charcters of the integer by calling function
circulate(a)
* Step 8: Iff 'f' ==1 print " NOT A CIRCULAR PRIME" else
print "CIRCULAR PRIME"
* Step 9: End of Algorithm for isCircularPrime()
*Algorithm for isPrime()
Bhargav Parashar 12 S Page | 6
*Step 1: Start of Algorithm
*Step 2: Create a for loop whinh runs till 'n' and checks if
'n' is prime
for(int i = 1; i<=n; i++)
{
if(n%i == 0)
c++;
}
* Step 3: If c==2, return 'true' else return 'false'
* Step 4: End of Algorithm for isPrime()
* Algorithm for circulate()
* Step 1: Start of Algorithm
* Step 2: Convert the integer into String type
String s = Integer.toString(n);
* Step 4: Send the first character to the end of the String
thus circulating it
String p = s.substring(1)+s.charAt(0);
* Step 5: Convert the new String p into Integer type
int a = Integer.parseInt(p);
* Step 6: return 'a'
* Step 7: End of Algorithm for circulate()
*/

SOURCE CODE:

import java.util.*;
class CircularPrime
{
boolean isPrime(int n) // Function for checking whether a
number is prime or not
{
int c = 0;
for(int i = 1; i<=n; i++)
{
if(n%i == 0)
c++;
}
Bhargav Parashar 12 S Page | 7
if(c == 2)
return true;
else
return false;
}
int circulate(int n) //Function for circulating the digits to
form new number
{
String s = Integer.toString(n);
String p = s.substring(1)+s.charAt(0);
int a = Integer.parseInt(p);
return a;
}
void isCircularPrime(int n) //Function to check for circular
prime
{
int f = 0,a = n;
do
{
System.out.println(a);
if(isPrime(a)==false)
{
f = 1;
}
a = circulate(a);
}while(a!=n);
if(f==1)
System.out.println(n+" IS NOT A CIRCULAR PRIME");
else
System.out.println(n+" IS A CIRCULAR PRIME");
}
public static void main(String args[])
{
CircularPrime ob = new CircularPrime();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
Bhargav Parashar 12 S Page | 8
int n = sc.nextInt();
ob.isCircularPrime(n);
}
}

Output:

Enter a number : 87
87
87 IS NOT A CIRCULAR PRIME

Enter a number : 1193


1193
1931
9311
3119
1193 IS A CIRCULAR PRIME

Enter a number : 123


123
231
312
123 IS NOT A CIRCULAR PRIME

Bhargav Parashar 12 S Page | 9


2) Program to check if a number is
evil number:
ALGORITHM:
/*Algorithm for main() method :
*Step 1: Start of algotithm
*Step 2: Input the number to be checked and store it in
integer variable 'n'
*Step 3: Create dublicate values of 'n' and store them in
integer variables 'd' and 'd1'
*Step 4: Create a while loop to get the length of required
array to store the remainders
(a)A loop is created which runs untill value of n
becomes 0
(b)The number of times the loop runs is stored in the
integer 'count'
*Step 5: Create 'array[]' and 'array2[]' of size 'count'
*Step 6: Create another while loop to find and store the
remainders in 'array[count]'
(a)A loop is created which runs untill value of d
becomes 0
(b)the remainders are found and stored in
'array[count]'
*Step 7: Create a for loop to reverse 'array[count]' and find
the binary equivalent
(a)A loop is created which runs backwards form 'count'-
1 to 0
(b)The integers in 'array[count]' are stored in backward
order in 'array2[count]'
*Step 8: Create a for loop to count the number of 1's
(a)A loop is created which runs from 0 to 'count'
(b)Check if the integer in the present index of
'array2[count]' ==1,
and increase value of sum by 1 if true
Bhargav Parashar 12 S Page | 10
*Step 9:Create a if conditional to check if there are even
number of ones
(a)Check if sum%2==0, if true the increase value of
'flag' by 1
*Step10: Display the Binary equivalent and number of 1's
*Step 11: Create a if conditional to check if 'flag'>0, if true
display "Evil Number"
else display "notEvil number"
*Step 12: End of Algorithm
*/
SOURCE CODE:

import java.io.*;
public class EvilNumber
{
int n,d,count,val,x,i,y,k,sum,flag,d1,l;
public void main() throws IOException
{
BufferedReader obj=new BufferedReader (new
InputStreamReader(System.in));
System.out.println("Enter number to checked:");
n=Integer.parseInt(obj.readLine());
d=n;
d1=d;
while(n>0) //while loop to calculate the
required length of array
{
n=n/2;
count++;
}
int array[]=new int[count];
int array2[]=new int[count];
x=0;
while(d>0) //while loop to find and store the
remainders in 'array[count]'
{
val=d%2;
array[x]=val;
Bhargav Parashar 12 S Page | 11
x++;
d=d/2;
}
for(i=count-1; i>=0;i--) //for loop to reverse
'array[count]' and find the binary equivalent
{
array2[y]=array[i];
y++;
}
for(k=0; k<count;k++) //for loop to count the number
of 1's
{
if(array2[k]==1)
sum++;
}
if(sum%2==0) //if conditional to check if there
are even number of ones
{
flag++;
}
System.out.print("INPUT:"+ d1); // Displaying
the Binary equivalent and number of 1's
System.out.println();
System.out.print("BINARY EQUIVALENT:");
for(l=0; l<count;l++)
{
System.out.print(array2[l]);
}
System.out.println();
System.out.print("NO. OF 1's :" + sum);
System.out.println();
if(flag>0) //if conditional to check if there are even
number of ones or not
{
System.out.print("EVIL NUMBER"); // Displaying
output
}
else
Bhargav Parashar 12 S Page | 12
{
System.out.print("NOT AN EVIL NUMBER");
}
}
}

Output:
Enter a positive number : 26
Binary Equivalent = 11010
Number of Ones = 3
26 is Not an Evil Number.

3) Program to check if a number is a


Kaprekar number:
Bhargav Parashar 12 S Page | 13
ALGORITHM:
/* Algorithm for main() method
* Step1: Start of algorithm
* Step 2: Input the begining limit and the end limit and
store them in 'p' and 'q' respectively
* Step 3:Create an if conditional to check if 'p' or 'q'
exceeds 5000, if yes display "out of range"
else call function calculate()
* Algorithm for calculate() method
* Step 1: Create a outer while loop which runs till end limit
and checks if a number is Kaprekar
* Step 2: Create an inner while loop which runs till'p'!=0
and checks the length of the integer and
stores it in 'freq'
*Step 3: Find the square of the number and separate the
number in half and add them
num1=num*num;
power=Math.pow(10,freq);
int power1=(int)power;
part1=num1%power1;
part2=num1/power1;
sum=part1+part2;

* Step 4: if 'sum'=='num' print the number and add 1 to


'count'
* Step 5: Increase the value of 'num' by 1 and if it is less
then 'q' (end limit) of outer while
loop, the process takes place again
* Step 6: Display frequency by printing 'count'
* Step 7: End of Algorithm
*/

SOURCE CODE:

import java.util.*;
public class Kaprekar
{
int n,p,q,i,count,num,num1,freq,power1,part1,part2,sum;
Bhargav Parashar 12 S Page | 14
double power;
public void main()
{
Scanner scan=new Scanner(System.in);
System.out.println("Enter begining limit");
p=scan.nextInt();
System.out.println("Enter end limit");
q=scan.nextInt();
if(p>5000||q>5000)
{
System.out.println("out of range");
}
else
{
calculate();
}
}

void calculate()
{

num=p;
while(num<=q)
{

p=num;
freq=0;

while(p!=0)
{
p=p/10;
freq++;
}

num1=num*num;
power=Math.pow(10,freq);
int power1=(int)power;
part1=num1%power1;
part2=num1/power1;
Bhargav Parashar 12 S Page | 15
sum=part1+part2;

if(sum==num)
{
count++;
System.out.println(num+" ");

}
num++;

}
System.out.println("Frequency : " +count);

}
}

Output:
Enter begining limit
1
Enter end limit
100
1
9
45
55
99
Frequency : 5

4) Program to check if a number is


prime palindrome:
ALGORITHM:
/* Algorithm for main() method
* Step1: Start of algorithm
* Step2: Input two positive integers m and n where
m<3000 and n<3000
Bhargav Parashar 12 S Page | 16
* Step3: Check for prime numbers using for loops
t=i;
for(i=1; j<=t; j++)
{
if( t%j==0)
c++;
*Step4: If c==2, the number is prime, check for palindrome
r=0;
while (t>0)
{
a=t%10;
r=r*10 +a;
t=t/10;
}
*Step5: If r==i, print the number and increase the value of
integer variable freq holding the
frequency of the prime palindrome number by 1.
*Step 6:Print the value of frequency
*Step 7:End of void main()
*/

SOURCE CODE:

import java.util.*;
public class PrimePalindrome
{
public void main()
{
Scanner scan=new Scanner(System.in);
int m,n,i,j,t,c,r,a,freq;
System.out.println("Enter two positive integers m and
n, where m<3000 and n<3000");
m=scan.nextInt();
n=scan.nextInt();
if(m<3000 && n<3000)
{
freq=0;
System.out.println("The prime palindrome integers
are:");
Bhargav Parashar 12 S Page | 17
for(i=m;i<=n;i++)
{ t=i;
c=0;
for(j=1;j<=t;j++)
{
if(t%j==0)
c++;
}
if(c==2)
{
r=0;
while(t>0)
{
a=t%10;
r=r*10+a;
t=t/10;
}
if(r==i)
{
System.out.print(i+" ");
freq++;
}
}
}
System.out.println("\nFrequency of prime
palindrome integers:"+freq);
}
else
{
System.out.println("Out of Range");
}
}
}
Output:
m=100
n=100
N=1000
The prime palindrome integers are:

Bhargav Parashar 12 S Page | 18


101,131,151,181,191,313,351,373,383,727,757,787,797,91
9,929
Frequency of prime palindrome integers:15

5) Program to check if a number is a


Pronic number:
ALGORITHM:
/* Algorithm for main() method
* Step1: Start of algorithm
* Step2: Enter the number and store the value in integer
variable n
* Step3: Multiply n with n+1 using for loop and check
for Pronic numbers
for(int i=0; i<n; i++)
{
if(i*(i+1) == n)
{
Bhargav Parashar 12 S Page | 19
flag = 1;
break;
}
}
Step4: If flag==1, print Pronic number else print Not a
pronic number
Step 5: End of Algorithm for void main()
*/
SOURCE CODE:

import java.util.*;
class PronicNumber
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
int n = sc.nextInt();
int flag = 0;
for(int i=0; i<n; i++)
{
if(i*(i+1) == n)
{
flag = 1;
break;
}
}
if(flag == 1)
System.out.println(n+" is a Pronic Number.");
else
System.out.println(n+" is not a Pronic Number.");
}
}
Output:
Enter a number : 110
110 is a Pronic Number.

Bhargav Parashar 12 S Page | 20


Enter a number : 73
73 is not a Pronic Number.

6) Program to check if a number is a


Unique number:
ALGORITHM:
/* Algorithm for main() method
* Step1: Start of algorithm
* Step2:Enter the number and store it in integer variable
n
*Step3: Convert the number to string
String s=Integer.toString(n);
*Step4: Find its length and store it in integer variable l
*Step5: Use for loops to check for repeated digits
for(int i=0;i<l-1;i++)
{
for(int j=i+1;j<l;j++)
{
if(s.charAt(i)==s.charAt(j)) //if any digits match,
then we know it is not a Unique Number
{
flag=1;
break;
Bhargav Parashar 12 S Page | 21
}
}
}

*Step 6: If flag==0, print : "**** The Number is a Unique


Number ****"
else print: ("**** The Number is a Not
Unique Number ****"
*Step 7: End of Algorithm for void main()
/*

SOURCE CODE:

import java.io.*;
class UniqueNumber
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter any number : ");
int n=Integer.parseInt(br.readLine());

String s=Integer.toString(n); //converting the number


into String form
int l=s.length();
int flag=0;

/* loop for checking whether there are repeated digits


*/
for(int i=0;i<l-1;i++)
{
for(int j=i+1;j<l;j++)
{
if(s.charAt(i)==s.charAt(j)) //if any digits match,
then we know it is not a Unique Number
{
flag=1;
Bhargav Parashar 12 S Page | 22
break;
}
}
}

if(flag==0)
System.out.println("**** The Number is a Unique
Number ****");
else
System.out.println("**** The Number is Not a Unique
Number ****");
}
}

Output:

Enter any number : 3121


**** The Number is Not a Unique Number ****
Enter any number : 5243
**** The Number is a Unique Number ****

Bhargav Parashar 12 S Page | 23


7) Program to check if a number is a
Harshad number:
ALGORITHM:
/* Algorithm for main() method
* Step1: Start of algorithm
* Step2: Enter the number and store it in integer variable
n
* Step3:Create a dublicate value c of integer variable n
*Step4: Find the sum of the digits using while loop
while(c>0)
{
d = c%10;
sum = sum + d;
c = c/10;
}
*Step5: Check if sum of the digits is divisible by the digit
itself, i.e, if sum is
divisible by n
*Step6: If sum is divisible by n print: " Harshad Number "
else print: "Not a Harshad Number."
*Step7: End of Algorithm for void main()

Bhargav Parashar 12 S Page | 24


/*
SOURCE CODE:
import java.util.*;
class HarshadNumber
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
int n = sc.nextInt();
int c = n, d, sum = 0;
//finding sum of digits
while(c>0)
{
d = c%10;
sum = sum + d;
c = c/10;
}
if(n%sum == 0)
System.out.println(n+" is a Harshad Number.");
else
System.out.println(n+" is not a Harshad Number.");

Output:
Enter a number : 195
195 is a Harshad Number.
Enter a number : 194
194 is not a Harshad Number.

Bhargav Parashar 12 S Page | 25


8) Program to print all the Twin Prime
numbers within a given range:
ALGORITHM:
/* Algorithm for boolean isPrime()
* Step1: Start of algorithm
* Step2: Initiate value of count to 0
* Step3:Use for loop to check if given parameter n is
prime
for(int i=1; i<=n; i++)
{
if(n%i == 0)
count++;
}
*Step4: If count==2, return true else, return false
*Step5: End of Algorithm for boolean isPrime()
* Algorithm for void main()
*Step1: Start of algorithm
*Step2: Input the lower range and the upper range and
store them in integer variables
p and q respectively
*Step3: If(p>q), print :INVALID INPUT
*Step4: Use for loop to checkif two consecutive numbers
are prime
for(int i=p; i<=(q-2); i++)
{
if(ob.isPrime(i) == true && ob.isPrime(i+2) ==
true)
{
System.out.print("("+i+","+(i+2)+") ");
}

Bhargav Parashar 12 S Page | 26


*Step5: If the condition satisfies, i.e, if(ob.isPrime(i) ==
true && ob.isPrime(i+2) == true)
print the Twin prime pair.
*Step6: End of Algorithm for void main()
/*

SOURCE CODE:

import java.io.*;
class TwinPrimeRange
{
boolean isPrime(int n) //function for checking prime
{
int count=0;
for(int i=1; i<=n; i++)
{
if(n%i == 0)
count++;
}
if(count == 2)
return true;
else
return false;
}
public static void main(String args[]) throws IOException
{
TwinPrimeRange ob = new TwinPrimeRange();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));

System.out.print("Enter the lower range : ");


int p = Integer.parseInt(br.readLine());
System.out.print("Enter the upper range : ");
int q = Integer.parseInt(br.readLine());
if(p>q)
System.out.println("Invalid Range !");
else
{
Bhargav Parashar 12 S Page | 27
System.out.println("nThe Twin Prime Numbers
within the given range are : ");
for(int i=p; i<=(q-2); i++)
{
if(ob.isPrime(i) == true && ob.isPrime(i+2) ==
true)
{
System.out.print("("+i+","+(i+2)+") ");
}
}
}
}
}
Output:
Enter the lower range : 1
Enter the upper range : 200

The Twin Prime Numbers within the given range are :


(3,5) (5,7) (11,13) (17,19) (29,31) (41,43) (59,61) (71,73)
(101,103) (107,109) (137,139) (149,151) (179,181)
(191,193) (197,199)

Bhargav Parashar 12 S Page | 28


PATTERNS

9) Program to display a pattern of


stars with reduction of start from the
middle from the next line:
ALGORITHM:
1.Start
2.Create class Pattern1
3.Declare input int n
4.Declare variable i& j
5.Print menu
6.int f=(n/2)+1
7.int g=(n/2)
8.i=1
Bhargav Parashar 12 S Page | 29
9.if i<=n, proceed to step 9 else to step 15
10. j=1
11. if j<=n proceed to step 11, else go to step 13
12. if((j>=f&&j<=g)&&(j!=1)), print , else *
13. f=f-1
14. g=g+1
15. new line
16. i++ and go to step 9
17. end

SOURCE CODE:
class Pattern1 //legs
{
void main(int n) //main fuction
{
int i,j;
System.out.println("Pattern :");
System.out.println();
int f=(n/2)+1; //for first line
int g=(n/2); //line of symmetry
for(i=1;i<=(n/2);i++)
{
for(j=1;j<=n;j++)
{
if((j>=f&&j<=g)&&(j!=1))
{
System.out.print(" ");
}
else
{
System.out.print("*");
}
}
f=f-1;
g=g+1;
System.out.println();
}
}
}
Bhargav Parashar 12 S Page | 30
OUTPUT

Pattern :

**********
**** ****
*** ***
** **
* *

10) Program to display a pattern of


stars with the void shaped like an
arrow:
ALGORITHM:
1.Start
2.Create class Pattern2
3.Declare input n
4.Declare variable I & j
5.i =1
6.if i<=n proceed to step 7, else go to step 13
7.j=1
8.if j<=n proceed to step 9, else go to step 11
9.if j>=i, print * , else
10. j++ to back to step 8
11. new line
12. i++ to back to step 6
13. i=n
Bhargav Parashar 12 S Page | 31
14. if i>=1 proceed to step 15, else go to step 21
15. j=1
16. if j<=n proceed to step 17, else go to step 19
17. if j>=i, print * , else
18. j++ to back to step 16
19. new line
20. i-- to back to step 14
21. end

SOURCE CODE:
public class Pattern2 //mouth

void main(int n) //dynamic initialization of variable

int i,j;

System.out.println("Pattern :");

System.out.println();

for(i=1;i<=n;i++) //printing upper lip of mouth

for(j=1;j<=n;j++) //deciding if to print blank space

or star

if(j>=i)

System.out.print("*");
Bhargav Parashar 12 S Page | 32
}

else

System.out.print(" ");

System.out.println();

for(i=n;i>=1;i--) //printing lower lip of mouth

for(j=1;j<=n;j++)

if(j>=i)

System.out.print("*");

else

System.out.print(" ");

}
Bhargav Parashar 12 S Page | 33
}

System.out.println();

OUTPUT
Pattern : n=10

**********
*********
********
*******
******
*****
****
***
**
*
*
**
***
****
*****
******
*******
********
*********
**********

Bhargav Parashar 12 S Page | 34


11) Program to display a pattern of a
hollow inverted pyramid on top of a
hollow pyramid with *:
ALGORITHM:
1.Start
2.Create class Pattern3
3.Declare input n
4.Declare variable I & j,
5.Print menu
6.f8=2
7.g8=n-1
8.i =1
9.if i<=(n/2) proceed to step 10, else go to step18
10. j=1
11. if j<=(n) proceed to step 12, else go to step 14
12. if(j>=f8 &j<=g8), print , else *
13. j++ and go back to step 11
14. f8=f8+1
15. g8=g8-1
16. new line
17. i++ to back to step 9
18. f6=(n/2)+1
19. g6=(n/2)
20. i=1
21. if i<=(n/2) proceed to step 22, else go to step 30
22. j=1
23. if j<=(n) proceed to step 24, else go to step 26
Bhargav Parashar 12 S Page | 35
24. if((j>=f6 & j<=g6) &(j!=1)), print , else *
25. j++ and go back to step
26. f6=f6-1
27. g6=g6+1
28. new line
29. i++ to back to step
30. end

SOURCE CODE:
public class Pattern3

void main(int n)

int i,j;

System.out.println("Pattern :");

System.out.println();

int f8=2; //for first line

int g8=n-1; //for line of symmetry

for(i=1;i<=(n/2);i++) //upper part of pattern

for(j=1;j<=n;j++)

if(j>=f8&&j<=g8)

{
Bhargav Parashar 12 S Page | 36
System.out.print(" ");

else

System.out.print("*");

f8=f8+1;

g8=g8-1;

System.out.println();

int f6=(n/2)+1; //line of no gap

int g6=(n/2); //after line of no gap

for(i=1;i<=(n/2);i++) //for lower section of pattern

for(j=1;j<=n;j++)

if((j>=f6&&j<=g6)&&(j!=1))

System.out.print(" ");
Bhargav Parashar 12 S Page | 37
}

else

System.out.print("*");

f6=f6-1;

g6=g6+1;

System.out.println();

OUTPUT
Pattern :

* *
** **
*** ***
**** ****
**********
**********
**** ****
*** ***
** **
* *

Bhargav Parashar 12 S Page | 38


MATRIX AND
ARRAYS

12) Write a program to input an


array and print boundary elements:
ALGORITHM:
Bhargav Parashar 12 S Page | 39
/* Algorithm for main() method
* Step1: Start of algorithm
* Step2: Input the number of rows and columns and store
them in integer variable s m and
n respectively.
*Step3: Create an integer array A[][]=new int[m][n];
*Step4: Input the array elements using for loops
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print("Enter the elements: ");
A[i][j]=Integer.parseInt(br.readLine());
}
}
*Step6: Print only the boundary elements (rows and
columns) using for loops when the following conditional
satisfies:
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==0 || j==0 || i == m-1 || j == n-1) //condition
for accessing boundary elements
System.out.print(A[i][j]+"\t");
else
System.out.print(" \t");
}
System.out.println();
}

*Step7: End of Algorithm for void main()


/*
SOURCE CODE:

import java.io.*;
class Boundary_Element
{
Bhargav Parashar 12 S Page | 40
public static void main(String args[])throws IOException
{
int i,j,m,n;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));

System.out.print("Enter the no. of rows: "); //Inputting


the number of rows
m=Integer.parseInt(br.readLine());
System.out.print("Enter the no. of columns: ");
//Inputting the number of columns
n=Integer.parseInt(br.readLine());

int A[][]=new int[m][n]; //Creating the array

/* Inputting the array */


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print("Enter the elements: ");
A[i][j]=Integer.parseInt(br.readLine());
}
}

System.out.println("The Boundary Elements are:");


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==0 || j==0 || i == m-1 || j == n-1) //condition
for accessing boundary elements
System.out.print(A[i][j]+"\t");
else
System.out.print(" \t");
}
System.out.println();
}
}
Bhargav Parashar 12 S Page | 41
}
Output:
Enter the no. of rows: 4
Enter the no. of columns: 3
Enter the elements: 1
Enter the elements: 5
Enter the elements: 3
Enter the elements: 2
Enter the elements: 1
Enter the elements: 2
Enter the elements: 4
Enter the elements: 6
Enter the elements: 7
Enter the elements: 5
Enter the elements: 78
Enter the elements: 75
The Boundary Elements are:
1 5 3
2 2
4 7
5 78 75

13) Program in Java to input a 2-D


square matrix and check whether it
is a Scalar Matrix or not:

ALGORITHM:
/* Algorithm for main() method
* Step 1 : Start of algorithm
Bhargav Parashar 12 S Page | 42
* Step 2 : Input the size of the matri aand store it in
integer variable m
*Step 3 : Create an integer array A[][]=new int[m][m];
*Step 4 : Using for loops input the elements into the
matrix
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print("Enter an element : ");
A[i][j]=sc.nextInt();
}
}
*Step 5 : Print the Matrix
*Step 6 : Create intgers p and q with initial values 0 and
x=A[0][0]
*Step 7 : Using for loops check if the matrix is diagonal:
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
/* Checking that the matrix is diagonal or
not */
if(i!=j && A[i][j]!=0) // All non-diagonal
elements must be zero
{
p=1;
break;
}

*Step 8 : Continue the loop body and check the matrix for
Scalarity
/* Checking the matrix for scalarity */
// All main diagonal elements must be
equal to 'x' and non-zero
if(i==j && (A[i][j]==0 || A[i][j]!=x))
{
q=1;
break;
Bhargav Parashar 12 S Page | 43
}
}
}
*Step 9 : If p==0 &&q==0, print: The matrix is scalar
else print: The matrix is not scalar
*Step10:End of Algorithm for void main()

SOURCE CODE:

import java.util.*;
class ScalarMatrix
{
public static void main(String args[])throws Exception
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the matrix : ");
int m=sc.nextInt();
int A[][]=new int[m][m];
/* Inputting the matrix */
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print("Enter an element : ");
A[i][j]=sc.nextInt();
}
}

/* Printing the matrix */


System.out.println("*************************");
System.out.println("The Matrix is : ");
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(A[i][j]+"\t");
Bhargav Parashar 12 S Page | 44
}
System.out.println();
}
System.out.println("*************************");
int p = 0, q = 0, x = A[0][0]; // 'x' is storing the 1st
main diagonal element
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
/* Checking that the matrix is diagonal or
not */
if(i!=j && A[i][j]!=0) // All non-diagonal
elements must be zero
{
p=1;
break;
}
/* Checking the matrix for scalarity */
// All main diagonal elements must be
equal to 'x' and non-zero
if(i==j && (A[i][j]==0 || A[i][j]!=x))
{
q=1;
break;
}
}
}
if(p==0 && q==0)
System.out.println("The matrix is scalar");
else
System.out.println("The matrix is not scalar");
}
}

Output:

Bhargav Parashar 12 S Page | 45


Enter the size of the matrix : 4
Enter an element : 5
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 5
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 5
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 5
*************************
The Matrix is :
5000
0500
0050
0005
*************************
The matrix is Scalar

14) program in Java to fill a square


matrix of size n*n in a circular
fashion (clockwise):
Algorithm:
Ste
p1 : Start of algorithm
Ste Input the size of circular matrix and store it in integer
p2 : variable n
Ste Create an integer square array of size n*n which will
p3 : be the circular matrix
Declare and initialize variables k = 0 (for filling the
Ste matrix), c1 = 0 (for storing index of
p4 : first column),
c2 = n-1 (for storing index of last column), r1 = 0
(for storing index of first row),
Bhargav Parashar 12 S Page | 46
r2 = n-1 (for storing index of last row)
Ste Start a while loop till k<=n*n and repeat steps 6 to
p5 : 10
Ste
p6 :
(a) Start a for loop from i = c1 to c2, where i
increases by 1 every time and perform step
(b)
(b) Store the natural numbers in the first row
using A[r1][i] = k++
Step 7 :
(a) Start a for loop from j = r1+1 to r2, where
j increases by 1 every time and perform step
(b)
(b) Store the natural numbers in the last
column using A[j][c2] = k++
Step 8 :
(a) Start a for loop from i = c2-1 to c1, where
i decreases by 1 every time and perform step
(b)
(b) Store the natural numbers in the last row
using A[r2][i] = k++
Step 9 :
(a) Start a for loop from j = r2-1 to r1+1,
where j decreases by 1 every time and
perform step (b)
(b) Store the natural numbers in the first
column using A[j][c1] = k++
Step 10 :Update the variables c1, c2, r1 and r2
Step 11 :Display the circular matrix A[ ]
Step 12 : End of Algorithm
SOURCE CODE:
import java.io.*; class Circular_Matrix
{
public static void main(String args[])throws IOException

Bhargav Parashar 12 S Page | 47


{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in)); System.out.print("Enter the
number of elements : ");

int n=Integer.parseInt(br.readLine());
int A[][]=new int[n][n];
int k=1, c1=0, c2=n-1, r1=0, r2=n-1;

while(k<=n*n)
{
for(int i=c1;i<=c2;i++)
{
A[r1][i]=k++;
}
for(int j=r1+1;j<=r2;j++)
{
A[j][c2]=k++;
}
for(int i=c2-1;i>=c1;i--)
{
A[r2][i]=k++;
}
for(int j=r2-1;j>=r1+1;j--)
{
A[j][c1]=k++;
}
c1++; c2--; r1++; r2--;
Bhargav Parashar 12 S Page | 48
}
/* Printing the Circular matrix */
System.out.println("The Circular Matrix is:");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+ "\t");
}
System.out.println();
}
}}

Output:
Enter the number of elements : 4
The Circular Matrix is:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

Bhargav Parashar 12 S Page | 49


15) Program in Java to input a 2-D
square matrix and check whether it
is a Diagonal Matrix or not:
ALGORITHM:
/* Algorithm for main() method
* Step 1: Start of algorithm
* Step 2: Input the size of the matrix and store it in
integer variable m
*Step 3: Create an integer array A[][]=new int[m][m];
*Step 4: Using for loops input the elements into the
matrix
for(int i=0;i<m;i++)
Bhargav Parashar 12 S Page | 50
{
for(int j=0;j<m;j++)
{
System.out.print("Enter an element : ");
A[i][j]=sc.nextInt();
}
}
*Step 5: Print the Matrix
*Step6: Create intgers p and q with initial values 0
*Step7: Checking non-diagonal elements:
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
if(i!=j && A[i][j]!=0) // Checking non-diagonal
elements
{
p=1;
break;
}
*Step 8: Checking diagonal elements:
if(i==j && A[i][j]==0) // Checking
diagonal elements
{
q++;
}
}
}

*Step 9: if p==0 && q<m, print: The matrix is


Diagonal
else print: The matrix is not
Diagonal
*Step 10 : End of Algorithm for void main()
/*

SOURCE CODE:

Bhargav Parashar 12 S Page | 51


import java.util.*;
class DiagonalMatrix
{
public static void main(String args[])throws Exception
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the matrix : ");
int m=sc.nextInt();
int A[][]=new int[m][m];

/* Inputting the matrix */


for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print("Enter an element : ");
A[i][j]=sc.nextInt();
}
}

/* Printing the matrix */


System.out.println("*************************");
System.out.println("The Matrix is : ");
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
System.out.println("*************************");

int p=0, q=0;

for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
Bhargav Parashar 12 S Page | 52
if(i!=j && A[i][j]!=0) // Checking non-diagonal
elements
{
p=1;
break;
}
if(i==j && A[i][j]==0) // Checking diagonal
elements
{
q++;
}
}
}

if(p==0 && q<m)


System.out.println("The matrix is Diagonal");
else
System.out.println("The matrix is not Diagonal");
}
}

Output:
Enter the size of the matrix : 4
Enter an element : 5
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 1
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 7
Bhargav Parashar 12 S Page | 53
*************************
The Matrix is :
5000
0100
0000
0007
*************************
The matrix is Diagonal

16) Program in Java to input a 2-D


square matrix and check whether it
is a Symmetric Matrix or not:
ALGORITHM:
/* Algorithm for main() method
* Step 1: Start of algorithm
* Step 2: Input the size of the matrix and store it in
integer variable m
* Step 3: Create an integer array A[][]=new int[m][m];
* Step 4: Using for loops input the elements into the
matrix
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print("Enter an element : ");
A[i][j]=sc.nextInt();
}
}
Bhargav Parashar 12 S Page | 54
* Step 5: Print the Matrix
* Step 6: Use for loop to check if the following conditional
is satisfied:
int flag = 0;
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
if(A[i][j] != A[j][i])
{
flag = 1; // Setting flag = 1 when elements do
not match
break;
}
}
}
*Step 7: if flag==0, print: The Matrix is Symmetric
else print: The Matrix is not Symmetric
*Step 8: End of Algorithm for void main()
*/

SOURCE CODE:

import java.io.*;
class SymetricMatrix
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the number of elements : ");
int m=Integer.parseInt(br.readLine());
int A[][]=new int[m][m];
if(m>2 && m<10) // Checking for valid input of rows
and columns size
Bhargav Parashar 12 S Page | 55
{
System.out.println("\nInputting the elements in the
Matrix: n");
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print("Enter the elements : ");
A[i][j]=Integer.parseInt(br.readLine());
}
}
/* Printing the Original Matrix */
System.out.println("\nThe Original Matrix is : ");
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
/* Checking whether the matrix is symmetric or not */
int flag = 0;
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
if(A[i][j] != A[j][i])
{
flag = 1; // Setting flag = 1 when elements do
not match
break;
}
}
}
if(flag == 1)

Bhargav Parashar 12 S Page | 56


System.out.println("\nThe given Matrix is Not
Symmetric");
else
System.out.println("\nThe given Matrix is
Symmetric");

}
else
System.out.println("The Matrix Size is Out Of
Range");
}
}

Output:
Enter the number of elements : 3

Inputting the elements in the Matrix: n


Enter the elements : 1
Enter the elements : 2
Enter the elements : 3
Enter the elements : 2
Enter the elements : 4
Enter the elements : 5
Enter the elements : 3
Enter the elements : 5
Enter the elements : 6

The Original Matrix is :


1 2 3
2 4 5
3 5 6

The given Matrix is Symmetric

Bhargav Parashar 12 S Page | 57


17) Program to find the SADDLE
POINT for the matrix:
ALGORITHM:
/* Algorithm for main() method
* Step 1: Start of algorithm
* Step 2: Input the size of the matrix and store it in
integer variable n
* Step 3: Create an integer array A[][]=new int[n][n];
* Step 4: Using for loops input the elements into the
matrix
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print("Enter an element : ");
A[i][j]=sc.nextInt();
}
}
* Step 5: Print the Matrix
* Step 6: Find the minimum element of a row:
int max, min, x, f=0;
for(int i=0;i<n;i++)
Bhargav Parashar 12 S Page | 58
{
/* Finding the minimum element of a row */
min = A[i][0]; // Initializing min with first element of
every row
x = 0;
for(int j=0;j<n;j++)
{
if(A[i][j]<min)
{
min = A[i][j];
x = j; // Saving the column position of the
minimum element of the row
}
}

*Step 7: Find the maximum element in the column


corresponding to the minimum element of row:
max = A[0][x]; // Initializing max with first
element of that column
for(int k=0;k<n;k++)
{
if(A[k][x]>max)
{
max = A[k][x];
}
}

*Step 8: If the minimum of a row is same as maximum of


the corresponding column,
then, we have that element as the Saddle point :
if(max==min)
{
System.out.println("********************");
System.out.println("Saddle point = "+max);
System.out.println("********************");
f=1;
}

Bhargav Parashar 12 S Page | 59


if(f==0)
{
System.out.println("********************");
System.out.println("No saddle point");
System.out.println("********************");
}
*Step 9: End of Algorithm for void main()
*/

SOURCE CODE:

import java.io.*;
class SaddlePoint
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the order of the matrix : ");
int n=Integer.parseInt(br.readLine());
int A[][]=new int[n][n];
System.out.println("Inputting the elements in the
matrix");
System.out.println("******************************");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print("Enter Element at ["+i+"]["+j+"]
: ");
A[i][j]=Integer.parseInt(br.readLine());
}
}

/* Printing the Original Matrix */

System.out.println("******************************");
Bhargav Parashar 12 S Page | 60
System.out.println("The Original Matrix is");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}

int max, min, x, f=0;


for(int i=0;i<n;i++)
{
/* Finding the minimum element of a row */
min = A[i][0]; // Initializing min with first element of
every row
x = 0;
for(int j=0;j<n;j++)
{
if(A[i][j]<min)
{
min = A[i][j];
x = j; // Saving the column position of the
minimum element of the row
}
}

/* Finding the maximum element in the column


* corresponding to the minimum element of row */
max = A[0][x]; // Initializing max with first element
of that column
for(int k=0;k<n;k++)
{
if(A[k][x]>max)
{
max = A[k][x];
}
}

Bhargav Parashar 12 S Page | 61


/* If the minimum of a row is same as maximum of
the corresponding column,
then, we have that element as the Saddle point */
if(max==min)
{
System.out.println("********************");
System.out.println("Saddle point = "+max);
System.out.println("********************");
f=1;
}
}

if(f==0)
{
System.out.println("********************");
System.out.println("No saddle point");
System.out.println("********************");
}
}
}

Output:

Enter the order of the matrix : 3


Inputting the elements in the matrix
******************************
Enter Element at [0][0] : 4
Enter Element at [0][1] : 5
Enter Element at [0][2] : 6
Enter Element at [1][0] : 7
Enter Element at [1][1] : 8
Enter Element at [1][2] : 9
Enter Element at [2][0] : 5
Enter Element at [2][1] : 1
Enter Element at [2][2] : 3
Bhargav Parashar 12 S Page | 62
******************************
The Original Matrix is
4 5 6
7 8 9
5 1 3
********************
Saddle point = 7
********************

18) Program to input a matrix and


transpose it:
ALGORITHM:
1.Begin
2.Declare class
3.Declare r,c
4.Input number of Rows and Columns for Matrix
5.Create Matrix (rXc)
6.Input integers in matrix A using loops until its (r,c)
limit
7.Display Matrix using looping
8.Create Matrix transwith parameters [c][r]
9.Declare i=0, j=0
10. if i<c go to step 11 else to step 15
11. if j<r go to step 12 else to step 14
12. trans[j][i] = matrix[i][j]
13. j=j+1, go to step 14
14. i=i+1, j=0 go to step 13
15. Display Matrix trans using looping
16. End

SOURCE CODE:

import java.io.*; //package import


class transpose
{

Bhargav Parashar 12 S Page | 63


BufferedReader a = new BufferedReader(new
InputStreamReader(System.in));
void main()throws IOException //main function
{
intr,c;
System.out.println("Enter the number of rows of matrix");
r = Integer.parseInt(a.readLine()); //inputting rows
System.out.println("Enter the number of columns of
matrix");
c = Integer.parseInt(a.readLine()); //inputting
columns
int matrix[][] = new int[r][c];
System.out.println("Enter the elements of matrix");
for (inti=0;i<r;i++) //inserting values
{
for (int j=0;j<c;j++)
{
matrix[i][j] = Integer.parseInt(a.readLine());
}
}
System.out.println("Inputted matrix :");
for (inti=0;i<r;i++) //showcasing inputted matrix
{
for (int j=0;j<c;j++)
{
System.out.print(matrix[i][j]+"\t");
}
System.out.println();
}
int trans[][] = new int[c][r]; //duplicate framework matrix
for (inti=0;i<r;i++) //main transpose method
{
for (int j=0;j<c;j++)
{
trans[j][i] = matrix[i][j];
}
}
System.out.println("Transposed matrix :");
for (inti=0;i<c;i++)
Bhargav Parashar 12 S Page | 64
{
for (int j=0;j<r;j++)
{
System.out.print(trans[i][j]+"\t");
}
System.out.println();
}
}}

OUTPUT

Enter the number of rows of matrix


3
Enter the number of columns of matrix
3

Enter the elements of matrix


1
2
3
4
5
6
7
8
9

Inputted matrix :
1 2 3
4 5 6
7 8 9
Transposed matrix :
1 4 7
2 5 8
3 6 9

Bhargav Parashar 12 S Page | 65


19) Write a program to input two
matrices and print their
multiplication:
ALGORITHM:
1.Begin
2.Declare class
3.r1, r2, c1,c2
4.declare i, j, k
5.Input number of Rows and Columns for Matrix A
6.Create Matrix (r1Xc1)
7.Input integers in matrix A using loops until its (r1,c1)
limit
8.Display Matrix A using looping
9.Input number of Rows and Columns for Matrix B
10. Create Matrix B(r2Xc2)
11. Input integers in matrix B using loops until its
(r2,c2) limit
12. Display Matrix B using looping
13. Create Matrix C [r1][c2]
14. if (r1==c2) go to step 15, else go to step 24
15. Declare i=0, j=0, k=0
16. if i<r1, go to next step, else go to step 23
17. if j<c2, go to next step, else go to step 22
18. if k<c1, go to next step, else go to step 21
19. c[i][j] = c[i][j]+a[i][k]*b[k][j];
20. k=k+1, go to step 18
21. j=j+1, put k=0, go to step 17
22. i=i+1, put j=0, go to step 16
23. Display Product Matrix C(rxC) using loops, go to
step 25
24. Display Error Message. Product not possible
25. End.
Bhargav Parashar 12 S Page | 66
SOURCE CODE:
import java.io.*;
public class multiplication
{
BufferedReader sc = new BufferedReader(new
InputStreamReader(System.in));
int r1,c1,r2,c2;
public void main() throws IOException //mainfuction
{
int i, j, k;
System.out.println("Enter the number of rows of Matrix
A");
r1 = Integer.parseInt(sc.readLine());
System.out.println("Enter the number of columns of
Matrix A");
c1 = Integer.parseInt(sc.readLine());
int a[][] = new int[r1][c1]; // declarartion of array A
System.out.println("Enter the number of rows of Matrix
B");
r2 = Integer.parseInt(sc.readLine());
System.out.println("Enter the number of columns of
Matrix B");
c2 = Integer.parseInt(sc.readLine());
int b[][] = new int[r2][c2]; // inputted array B
int c[][] = new int[r1][c2]; // product matrix
if (r1==c2) //multiplication possible on this sole
relationship
{
System.out.println("Enter the elements of Matrix A
");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
System.out.println("Enter an Integer for row "
+ (i+1) + " and column " + (j+1));
a[i][j] = Integer.parseInt(sc.readLine());
//entering values for array A
Bhargav Parashar 12 S Page | 67
}
}
System.out.println("Enter the elements of Matrix B
");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
System.out.println("Enter an Integer for row "
+ (i+1) + " and column " + (j+1));
b[i][j] = Integer.parseInt(sc.readLine());
//entering values for array B
}
}
for(i=0;i<r1;i++) // calculating product
{
for(j=0;j<c2;j++)
{
for(k=0;k<c1;k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
System.out.println("Printing Matrix A "); //
Output for matrix A
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
System.out.println("Printing Matrix B "); //
Output for matrix B
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
Bhargav Parashar 12 S Page | 68
{
System.out.print( b[i][j] + "\t");
}
System.out.println();
}
System.out.println("Printing product matrix ");
for (i=0;i<r1;i++) // displaying product
matrix
{
for (j=0;j<c2;j++)
{
System.out.print(c[i][j]+ "\t");
}
System.out.println();
}
}
else
{
System.out.print("Mutiplication not possible");
//Message showing it cannot multiply
}}}

OUTPUT
Enter the number of rows of Matrix A
2
Enter the number of columns of Matrix A
2
Enter the number of rows of Matrix B
2
Enter the number of columns of Matrix B
2

Enter the elements of Matrix A


Enter an Integer for row 1 and column 1
1
Enter an Integer for row 1 and column 2
2
Enter an Integer for row 2 and column 1
3
Bhargav Parashar 12 S Page | 69
Enter an Integer for row 2 and column 2
4
Enter the elements of Matrix B
Enter an Integer for row 1 and column 1
5
Enter an Integer for row 1 and column 2
6
Enter an Integer for row 2 and column 1
7
Enter an Integer for row 2 and column 2
8

Printing Matrix A
1 2
3 4
Printing Matrix B
5 6
7 8
Printing product matrix
19 22
43 50

Bhargav Parashar 12 S Page | 70


20) Program to input a matrix and
print the diagonal and secondary-
diagonal summations:
ALGORITHM:
1.Begin
2.Declare class
3.Declare sum1=0, sum2=0
4.int m;
5.Input number of Rows for Square Matrix A
6.Create Matrix A(mXm)
7.Input integers in matrix A using loops until its (m,m)
limit
8.Display Matrix A using looping
9.Declare i=0
10. if i<m go to step 11 else to step 13
11. sum1 = sum1 + a[i][i]
12. i=i+1go to step 10
13. int c = m-1
14. Declare j=0
15. if j<m go to step 16 else to step 19
16. sum1 = sum1 + a[i][c]
17. c=c-1
18. j=j+1go to step 15
19. Display sum1
20. Display sum2
21. End

SOURCE CODE:
import java.io.*;
class diagonal_secondarydiagonal
{
int sum1 = 0; //value storage for summation of
diagonals
int sum2 = 0;
public void main() throws IOException
Bhargav Parashar 12 S Page | 71
{
int i, j, m;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the number of rows for
square matrix ");
m = Integer.parseInt(br.readLine());
int a[][] = new int[m][m]; // declarartion of array
System.out.println("Enter the elements of Matrix ");
for(i=0;i<m;i++) // inputting array a
{
for(j=0;j<m;j++)
{
System.out.println("Enter an Integer for row " +
(i+1) + " and column " + (j+1));
a[i][j] = Integer.parseInt(br.readLine());
}
}
System.out.println("Printing Matrix "); // Output for
matrix A
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
for (i=0;i<m;i++)
{
sum1 = sum1 + a[i][i]; // calculating sum2 of
diagonal
}
int c = m-1;
for (j=0;j<m;j++) // calculating sum2 of secondary
diagonal
{
sum2 = sum2 +a[j][c];
c--;
Bhargav Parashar 12 S Page | 72
}
System.out.println("Diagonal summation of matrix is
"+sum1);
System.out.println("Secondary Diagonal summation of
matrix is "+sum2);
}
}
OUTPUT

Enter the number of rows for square matrix


3

Enter the elements of Matrix


Enter an Integer for row 1 and column 1
1
Enter an Integer for row 1 and column 2
3
Enter an Integer for row 1 and column 3
4
Enter an Integer for row 2 and column 1
7
Enter an Integer for row 2 and column 2
9
Enter an Integer for row 2 and column 3
11
Enter an Integer for row 3 and column 1
13
Enter an Integer for row 3 and column 2
15
Enter an Integer for row 3 and column 3
17

Printing Matrix
1 3 4
7 9 11
13 15 17

Diagonal summation of matrix is 27


Secondary Diagonal summation of matrix is 26
Bhargav Parashar 12 S Page | 73
21) Program to input a matrix and
sort columns independently:
ALGORITHM:
1.Begin
2.Declare Class
3.Declare variables r,c,i,j,k,n,m,z,temp
4.Input number of Rows and Columns for Array
5.Create Array arr(rxc)
6.Input integers in array arr using loops until its (r,c) limit
7.Display Array arr using looping
8.Create one dimensional array arr2(r)
9.Declare i=0, j=0, k=0, n=0
10. If i<c, k=0 and go to next step, else go to step 26
11. If j<r, go to next step, else go to step 14
12. arr2[k] = arr[j][i];
13. k=k+1, j=j+1, go to step 11
14. If n<r, go to next step, else go to step 21
15. If m<r-n-1, go to next step, else go to step 20
16. If arr2[m]>arr[m+1], go to next step, else go to
step 19
17. temp=arr[m], arr2[m]=arr2[m+1]
18. arr2[m+1]=temp
19. m=m+1, go to step 15
20. n=n+1, put m=0, go to step 14
21. Declare k=0, z=0
22. if z<r, go to next step, else go to step 25
23. arr[z][i]=arr2[k];
24. k=k+1, z=z+1, go to step 22
25. i=i+1, put z=0, go to step 10
26. Display Array arr with Sorted Columns using loops
27. End

SOURCE CODE:
import java.io.*; //importting package
classsort_columns
{
Bhargav Parashar 12 S Page | 74
void main()throws IOException
{
BufferedReader a = new BufferedReader(new
InputStreamReader(System.in));
int r, c, i, j, k, n, m, z, temp;
System.out.println("Enter number of rows for array :");
r=Integer.parseInt(a.readLine());
System.out.println("Enter number of columns for array :");
c=Integer.parseInt(a.readLine());
intarr[][]=new int[r][c]; //array framework initialization
System.out.println("Enter elements of array :");
for(i=0;i<r;i++) //Entering values
{
for(j=0;j<c;j++)
{
System.out.println("Row " +(i+1)+ " and Column " +(j+1));
arr[i][j]=Integer.parseInt(a.readLine());
}
}
System.out.println("Inputted array :");
System.out.println();
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
int arr2[]=new int[r]; //Creating single dimension array
for(i=0;i<c;i++) //master loop
{
k=0; //reset interval
for(j=0;j<r;j++)
{
arr2[k]=arr[j][i]; //Transfer of data to 1D array
k++;
}
for(n=0;n<r;n++)
Bhargav Parashar 12 S Page | 75
{
for(m=0;m<r-n-1;m++)
{
if(arr2[m]>arr2[m+1]) //Bubble sorting algorithm
{
temp=arr2[m];
arr2[m]=arr2[m+1]; //swapping places
arr2[m+1]=temp;
}
}
}
k=0;
for(z=0;z<r;z++)
{
arr[z][i]=arr2[k]; //Transfer of array data back to 2D array
k++;
}
}
System.out.println("Displaying array with Sorted
Columns:");
System.out.println();
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
}
}

OUTPUT

Enter number of rows for array :


3
Enter number of columns for array :
3
Bhargav Parashar 12 S Page | 76
Enter elements of array :
Row 1 and Column 1
12
Row 1 and Column 2
83
Row 1 and Column 3
27
Row 2 and Column 1
74
Row 2 and Column 2
23
Row 2 and Column 3
64
Row 3 and Column 1
1
Row 3 and Column 2
37
Row 3 and Column 3
8

Inputted array :
12 83 27
74 23 64
1 37 8

Displaying array with Sorted Columns:


1 23 8
12 37 27
74 83 64

22) Program to input a matrix and


print its boundary sum and internal
sum:
Bhargav Parashar 12 S Page | 77
ALGORITHM:
1.Begin
2.Declare class
3.Declare m,n,i,j
4.Input number of Rows and Columns for Matrix A
5.Create Matrix A(mXn)
6.Input integers in matrix A using loops until its (m,n)
limit
7.Display Matrix A using looping
8.sum = 0
9.Declare i=0, j=0
10. if i<m go to step 11 else to step 15
11. if j<n go to step 12 else to step 14
12. sum = sum+arr[i][j]
13. j=j+1, go to step 11
14. i=i+1, j=0 go to step 10
15. y = m-1
16. z = n-1
17. num = 0
18. Declare i=1, j=1
19. if i<y go to step 20 else to step 24
20. if j<z go to step 21 else to step 22
21. num = num+arr[i][j]
22. j=j+1, go to step 11
23. i=i+1, j=1 go to step 10
24. Bound=sum-num
25. Display Bound, num, sum
26. End

SOURCE CODE:
import java.io.*;
class boundary_internal_sum
{
int m,n,i,j;
BufferedReader a = new BufferedReader(new
InputStreamReader(System.in));
void main()throws IOException //main fuction
{
System.out.println("Enter the numbers of Rows");
Bhargav Parashar 12 S Page | 78
m=Integer.parseInt(a.readLine());
System.out.println("Enter the numbers of Columns");
n=Integer.parseInt(a.readLine());
int arr[][]=new int [m][n]; //array initialization
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.println("Enter value for row "+(i+1)+"
and column "+(j+1));
arr[i][j]=Integer.parseInt(a.readLine()); //read
array
}
}
System.out.println("Matrix entered :"); //output
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
System.out.println();
int sum = 0;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
sum = sum+arr[i][j]; //adding
}
}
int y = m-1;
int z = n-1;
int num = 0;
for(i=1;i<y;i++)
{
for(j=1;j<z;j++)
{
Bhargav Parashar 12 S Page | 79
num = num+arr[i][j];
}
}
int Bound=sum-num;
System.out.println("Sum of Outer Boundary elements
= "+Bound);
System.out.println("Sum of Inner Boundary elements =
"+num);
System.out.println("Sum of the elements of all values
in matrix= "+sum);
}
}

OUTPUT

Enter the numbers of Rows


3
Enter the numbers of Columns
3

Enter value for row 1 and column 1


1
Enter value for row 1 and column 2
2
Enter value for row 1 and column 3
3
Enter value for row 2 and column 1
4
Enter value for row 2 and column 2
5
Enter value for row 2 and column 3
6
Enter value for row 3 and column 1
7
Enter value for row 3 and column 2
8
Enter value for row 3 and column 3
9

Bhargav Parashar 12 S Page | 80


Matrix entered :
1 2 3
4 5 6
7 8 9

Sum of Outer Boundary elements = 40


Sum of Inner Boundary elements = 5
Sum of the elements of all values in matrix= 45

23)Program which first inputs two


integers, the first between 1 and 12
(both inclusive) and second between 0
and 59 (both inclusive) and then prints
out the time they represent, in
words,using arrays:
ALGORITHM:
Bhargav Parashar 12 S Page | 81
/* Algorithm for main() method
* Step 1: Start of algorithm
*Step 2: Create an String array num[]to store all numbers
in words
String num[] =
{null,"One","Two","Three","Four","Five","Six","Seven","Eight"
,"Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fiftee
n","Sixteen","Seventeen","Eighteen","Nineteen","Twenty","T
wenty One","Twenty Two","Twenty Three","Twenty
Four","Twenty Five","Twenty Six","Twenty Seven","Twenty
Eight","Twenty Nine"}
*Step 3: Input the time(hours and minutes) and store it in
integer variable h and m respectively
*Step 4: if(h>0 && h<13 && m<60) and if(m==0)
print: ("TIME : " + h + " : 00 ");
else, print ("TIME : " + h + " : " + m + " ");
*Step 5: if(m==0) //special case
print: (num[h] + " o' clock");
else if(m==15) //special case
print:("Quarter past " + num[h]);
else if(m==30) //special case
print:("Half past " + num[h]);
else if(m==45) //special case
print:("Quarter to " + num[h+1]);
else if(m<30) //printing in the
given format if it is less than 30
print:(num[m] + " minutes past " +
num[h]);
else if(m>30) //printing in the given
format if it is more than 30
print:(num[60-m] + " minutes to " +
num[h+1]);
*Step 6: End of Algorithm for void main()
*/

Bhargav Parashar 12 S Page | 82


SOURCE CODE:
import java.util.*;
public class Convert_Time
{
int h,m; //declaring variables
String num[] =
{null,"One","Two","Three","Four","Five","Six","Seven","Eight"
,"Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fiftee
n","Sixteen","Seventeen","Eighteen","Nineteen","Twenty","T
wenty One","Twenty Two","Twenty Three","Twenty
Four","Twenty Five","Twenty Six","Twenty Seven","Twenty
Eight","Twenty Nine"}; //string array to store all numbers in
words
void main()
{
Scanner scan = new Scanner(System.in); //creating
scanner object
System.out.println("ENTER THE TIME");
int h = scan.nextInt();
System.out.print(h + " : ");
int m = scan.nextInt(); //inputting value from user
if(h>0 && h<13 && m<60)
{
System.out.println("INPUT TIME :" + h + "," + m);
//printing hour and minute
if(m==0)
{
System.out.print("TIME : " + h + " : 00 ");
}
else
{
System.out.print("TIME : " + h + " : " + m + " ");
} //printing time
as inputted by user
Bhargav Parashar 12 S Page | 83
if(m==0) //special case
{
System.out.print(num[h] + " o' clock");
}
else if(m==15) //special case
{
System.out.print("Quarter past " + num[h]);
}
else if(m==30) //special case
{
System.out.print("Half past " + num[h]);
}
else if(m==45) //special case
{
System.out.print("Quarter to " + num[h+1]);
}
else if(m<30) //printing in the given format if it is
less than 30
{
System.out.print(num[m] + " minutes past " +
num[h]);
}
else if(m>30) //printing in the given format if it is
more than 30
{
System.out.print(num[60-m] + " minutes to " +
num[h+1]);
}
}
else
{
System.out.println("INVALID INPUT");
}
}
}

Output:
ENTER THE TIME
4
Bhargav Parashar 12 S Page | 84
4 : 20
INPUT TIME :4,20
TIME : 4 : 20 Twenty minutes past Four

Bhargav Parashar 12 S Page | 85


STRING
HANDLING

24) Program to count and display the


palindromic words in the sentence:
Algorithm for main() method :
Ste 1
p : Start of algotithm
Ste 2 Input the sentence and store it in a String variable
p : s
Ste 3
p : Convert the sentence into upper case

Ste 4 Create a StringTokenizer object str to extract


p : tokens (words) from the sentence using space and
other the punctuation marks namely ., ?, !

Ste 5 Count the number of tokens (words) and store it in


p : an integer variable c. Also create a String array
word[ ] of size c
Bhargav Parashar 12 S Page | 86
Ste 6
p : Start a for loop from i = 0 to less than c and store
the tokens of the sentence into the word [ ] array
Ste 7 Declare an integer variable count and initialize it
p : with 0
Ste 8 Start a for loop from i = 0 to less than c and
p : repeat step 9

Ste 9 Call the function isPalin() as : ob.isPalin(word[i]). If


p : the returned value is true then increase the count
variable and print the word.

Step
10 : If count of palindromic words is not equal to zero,
then print the value stored in the variable count
Step
11 : End of algorithm for main() method
Algorithm for function boolean isPalin(String s) :
Ste 1
p : Start of algorithm for function isPalin()
Ste 2 Find the length of the String s and store it in an
p : integer variable l
Ste 3 Declare and initialize a String variable rev= for
p : storing the reverse of the String s
Ste 4 Start a reverse for loop from i = l-1 to 0 and repeat
p : step 5

Ste 5 Extract characters from the end of the original string


p : and add them to the variable
rev

Ste 6 If the reverse word obtained (rev) is equal to the


p : original String (s), then return true, otherwise return
false
Ste 7
p : End of algorithm for the function isPalin().

SOURCE CODE:

import java.io.*;
import java.util.*;
Bhargav Parashar 12 S Page | 87
class Palin
{

static BufferedReader br=new BufferedReader (new


InputStreamReader (System.in));

boolean isPalin(String s)
{

int l=s.length(); String rev="";

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


{
rev=rev+s.charAt(i);

if(rev.equals(s)) return true;

else return false;


}

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


{

Palin ob=new Palin (); System.out.print("Enter any


sentence : "); String s=br.readLine();

s=s.toUpperCase();

StringTokenizer str = new StringTokenizer(s,".?! "); int


w=str.countTokens();

String word[]=new String[w]; for(int i=0;i<w;i++)

{
word[i]=str.nextToken();
}

Bhargav Parashar 12 S Page | 88


int count=0; System.out.print("OUTPUT : "); for(int i=0;
i<w; i++)

{
if(ob.isPalin(word[i])==true)

count++; System.out.print(word[i]+" ");


}
}

if(count==0)

System.out.println("No Palindrome Words"); else


System.out.println("nNumber of Palindromic Words :
"+count);
}

Output:

Enter any sentence : NITIN ARORA USES LIRIL SOAP

OUTPUT : NITIN ARORA LIRIL


Number of Palindromic Words : 3

Bhargav Parashar 12 S Page | 89


25) Program to count the number of
words and consonants of a given
string:
ALGORITHM:
1.Begin
2.Declare class
3.Declare variables (len=0,wordcount=0,cons=0,str="")
4.Input string in variable a1
5.Send a1 to String variable ds
Bhargav Parashar 12 S Page | 90
6.Declare str=ds, convert str into lowercase
7.Store length of str in len
8.Declare variable i=0
9.If i<len, go to next step, else go to step 13
10. If str.characterAt(i)=whitespace, go to next step,
else go to step 12
11. count=count+1
12. i=i+1, go to step 9
13. count=count+1
14. Declare i=0
15. If i<len, go to next step, else go to step 22
16. If str.characterAt(i)!=whitespace, go to next step,
else go to step 21
17. Declare character variable d
18. Put d=str.characterAt(i)
19. If (d!='a' & d!='e' & d!='i' & d!='o' & d!='u'), go to
next step, else go to step 21
20. cons=cons+1
21. i=i+1, go to step 15
22. Print Original String: str
23. Print number of words: wordcount
24. Print number of consonants: cons
25. End.

SOURCE CODE:
import java.io.*;
public class string
{
String str;
int len, wordcount, cons;
string() //default constructor
{
str="";
len=0;
wordcount=0;
cons=0;
}
string(String ds) // parameterized constructor
Bhargav Parashar 12 S Page | 91
{
str=ds;
}
public static void main()throws IOException //
main function
{
BufferedReader a=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Please input string:");
String a1=a.readLine(); // statement for user
input of string by choice
System.out.println();
System.out.println("Original String : " +a1);
string obj=new string(a1); // object sending value to
constructor
obj.countFreq(); // method calls by object of
main function
obj.show();
}
void countFreq() //count words and consonants
{
len=str.length();
str=str.toLowerCase();
for(int i=0;i<len;i++)
{
if(str.charAt(i)==32) // checking for whitespace
wordcount++;
}
wordcount++;
for(int i=0;i<len;i++) // loop to count number of
consonants
{
if(str.charAt(i)!=32) // checking whether it is a
character
{
char d=str.charAt(i);
if(d!='a'&&d!='e'&&d!='i'&&d!='o'&&d!='u') //
statement checking if its not a vowel
cons++;
Bhargav Parashar 12 S Page | 92
}
}
}
void show()
{
System.out.println();
System.out.println("Number of words : " +wordcount);
System.out.println("Number of consonants : " +cons);
}
}

OUTPUT

Please input string:


Deadpool is the coolest superhero

Original String : Deadpool is the coolest superhero

Number of words : 5
Number of consonants : 16
26) Write a program to count the
frequency of words starting with a
vowel:
ALGORITHM:
1. Begin
2. Declare class
3. Declare variables (str="",frequency=0)
4. Input Sentence in str
5. Print Original sentence: str
6. Convert str to lowercase letters
7. Declare integer variables (i,l)
8. Store length of str in l
9. Declare character variables (b,d)
10. Store b=Character of str which is at(0 index)
11. If b=='a' or b=='e' or b=='i' or b=='o' or b=='u', go to next step,
else to step 13
12. frequency=frequency+1
13. Declare i=1
14. If i<l, go to next step, else go to step 20

Bhargav Parashar 12 S Page | 93


15. If Character of str which is at (i)=whitespace, go to next step 16,
else go to step 19
16. Store d=Character of s1 which is at (i+1)
17. If d=='a' or d=='e' or d=='i' or d=='o' or d=='u', go to next step,
else to step 19
18. frequency =frequency +1
19. i=i+1, go to step 14
20. Print Frequency of words starting with vowels: frequency
21. End.

SOURCE CODE:
import java.io.*;
public class vowelNum
{
String str;
int frequency;
BufferedReader a=new BufferedReader(new InputStreamReader(System.in));
public void main()throws IOException // main function
{
vowelNum obj=new vowelNum();
obj.read();
obj.freq();
obj.show();
}
void read()throws IOException //inputting sentence
{
System.out.println("Please Input Sentence: ");
str=a.readLine();
str=str.trim(); //removing whitespaces
System.out.println();
System.out.println("Sentence: " +str); // showing original sentence
str=str.toLowerCase(); // converting sentence to lowercase
}
vowelNum() // default constructor
{
str="";
frequency=0;
}
void freq() //count frequency of vowels at start of a word
{
int l=str.length();
char b=str.charAt(0);
if(b=='a'||b=='e'||b=='i'||b=='o'||b=='u')
frequency++;
for(int i=1;i<l;i++)
{
if(str.charAt(i)==32) // checking for whitespace
{
char d=str.charAt(i+1);
if(d=='a'||d=='e'||d=='i'||d=='o'||d=='u')
frequency++;
}
Bhargav Parashar 12 S Page | 94
}
}
void show() // showing total frequency of words starting with vowel
{
System.out.println("Frequency of Words starting with Vowel : "
+frequency);
}
}

OUTPUT

Please Input Sentence:


I have to go home at nine

Sentence: I have to go home at nine


Frequency of Words starting with Vowel : 2

27) Design a class to accept a sentence and


interchange the first alphabet with the last
alphabet for each word in the sentence, with
single letter word remaining unchanged. The
words in the input sentence are separated by a
single blank space and terminated by a full
stop:

ALGORITHM:
1.Begin
2.Declare class
3.Declare variables (sent="",reverse="",size=0)
4.Input sentence in sent
5.Store length of sent in size
6.Declare sub=0 and a string variable b
7.Declare i=0 and a character variable c
8.If i<size, go to next step, else go to step 19
Bhargav Parashar 12 S Page | 95
9.Store c=sent.characterAt(i)
10. If (c='' or c='.'), go to next step, else go to step 18
11. Store sub part of string from (sub to i) of sent in b
12. If b.length()!=1, go to next step, else go to step 16
13. reverse=reverse+ Character of b which is at
(b.length()-1)
14. reverse=reverse+b.sub part of string
from(1,b.length()-1)
15. reverse=reverse+ Character of b which is at (0
index), go to step 17
16. reverse=reverse+b
17. reverse=reverse+" ", sub=i+1
18. i=i+1, go to step 8
19. Print original Sentence: sent
20. Print altered Sentence: reverse
21. End.

SOURCE CODE:
import java.io.*; //input output package
public class interchange
{
String sent, reverse;
int size;
public static void main()throws IOException // main
function
{
interchange obj=new interchange(); // object creation
obj.read();
obj.firstlast();
obj.show();
}
interchange() // default constructor
{
sent="";
reverse="";
size=0;
}
void read()throws IOException //inputting sentence
{
Bhargav Parashar 12 S Page | 96
BufferedReader f=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter sentence ending with full
stop:");
sent=f.readLine();
}
void firstlast() //interchange first and last
character of word
{
size=sent.length();
int sub=0;
String b;
for(int i=0;i<size;i++) // Loop to operate the whole
sentence
{
char c=sent.charAt(i); // Stores character at that
index
if(c==' '||c=='.') // checking for whitespace or
end
{
b=sent.substring(sub,i); // stores part of string
if(b.length()!=1)
{
reverse=reverse+b.charAt(b.length()-1);
reverse=reverse+b.substring(1,b.length()-1); //
stores altered sentence
reverse=reverse+b.charAt(0);
}
else
reverse=reverse+b;
reverse=reverse+" "; // adding space to
sentence
sub=i+1;
}
}
}
void show() //show initial and altered
sentence
{
Bhargav Parashar 12 S Page | 97
System.out.println();
System.out.println("Original sentence: " +sent);
System.out.println("Altered sentence: " +reverse);
}
}

OUTPUT
Enter sentence ending with full stop:
Bhargav has been working for quite some time.

Original sentence: Bhargav has been working for quite some


time.
Altered sentence: vhargaB sah neeb gorkinw rof euitq eoms
eimt

Bhargav Parashar 12 S Page | 98


OBJECT
PASSING

28) Design a class to merge two


arrays using object passing
technique:
ALGORITHM:
/* Algorithm for void accept()
* Step 1: Start of algorithm
*Step 2: Input the array usinf for loop
for(int i=0; i<n; i++)
{
System.out.print("Enter Element ["+(i+1)+"] : ");
arr[i] = Integer.parseInt(br.readLine());
}
System.out.println();
*Step 3: End of Algorithm for void accept()

Bhargav Parashar 12 S Page | 99


*Step 4: Declare Mixer mix(Mixer A)to merge the current
object array elements with the parameterized array
elements and return the resultant object.
int size = this.arr.length + A.arr.length;
Mixer B = new Mixer(size); //object which will
store the result of merging

int x = 0;

/* Merging the array of current object with array of


parameter object */
for(int i=0; i<size; i++)
{
if(i<A.arr.length)
B.arr[i] = A.arr[i];
else
{
B.arr[i] = this.arr[x];
x++;
}
}
*Step 5: Sort the result:
/* Sorting the result*/
int temp=0;
for(int i=0; i<size-1; i++)
{
for(int j=i+1; j<size; j++)
{
if(B.arr[i]>B.arr[j])
{
temp = B.arr[i];
B.arr[i] = B.arr[j];
B.arr[j] = temp;
}
}
}

*Step 6: return B;

Bhargav Parashar 12 S Page | 100


*Step 7: End of Algorithm
/* Algorithm for void display()
* Step 1: Start of algorithm
*Step 2: Display the array
for(int i=0; i<n; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
*Step 3: End of Algorithm for void display()

/* Algorithm for void main()


* Step 1: Start of algorithm
* Step 2: Input size of first array and store it in integer
variable p
* Step 3: Mixer obj1 = new Mixer(p);
obj1.accept();
* Step 4: Input size of second array and store it in integer
variable q
* Step 3: Mixer obj2 = new Mixer(q);
obj2.accept();

*Step 5: Mixer obj3 = obj2.mix(obj1); //obj2 is the current


object which is referred by 'this' keyword above
*Step 6: Print the first, secod and the merged array by
calling function void display():
obj1.display();
obj2.display();
obj3.display();
* Step 7: End of Algorithm for void main()
*/

SOURCE CODE:

import java.io.*;
class Mixer
{
int arr[];
Bhargav Parashar 12 S Page | 101
int n;
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

Mixer(int nn)
{
n = nn;
arr = new int[n];
}

void accept()throws IOException


{
System.out.println("\n* Input the Array *\n");
for(int i=0; i<n; i++)
{
System.out.print("Enter Element ["+(i+1)+"] : ");
arr[i] = Integer.parseInt(br.readLine());
}
System.out.println();
}

Mixer mix(Mixer A)
{
int size = this.arr.length + A.arr.length; //size of
resulting array
/* 'this' keyword refers to the current object, i.e. the
object which calls mix() function */
Mixer B = new Mixer(size); //object which will store the
result of merging

int x = 0;

/* Merging the array of current object with array of


parameter object */
for(int i=0; i<size; i++)
{
if(i<A.arr.length)
B.arr[i] = A.arr[i];
else
Bhargav Parashar 12 S Page | 102
{
B.arr[i] = this.arr[x];
x++;
}
}

/* Sorting the result*/


int temp=0;
for(int i=0; i<size-1; i++)
{
for(int j=i+1; j<size; j++)
{
if(B.arr[i]>B.arr[j])
{
temp = B.arr[i];
B.arr[i] = B.arr[j];
B.arr[j] = temp;
}
}
}

return B;
}

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

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


{
System.out.print("Enter size of the 1st array : ");
int p = Integer.parseInt(br.readLine());
Mixer obj1 = new Mixer(p);
obj1.accept();
Bhargav Parashar 12 S Page | 103
System.out.print("Enter size of the 2nd array : ");
int q = Integer.parseInt(br.readLine());
Mixer obj2 = new Mixer(q);
obj2.accept();

Mixer obj3 = obj2.mix(obj1); //obj2 is the current object


which is referred by 'this' keyword above

System.out.print("The 1st Array is : ");


obj1.display();

System.out.print("The 2nd Array is : ");


obj2.display();

System.out.print("The Merged Array is : ");


obj3.display();
}
}
Output:

Enter size of the 1st array : 5

* Input the Array *

Enter Element [1] : 11


Enter Element [2] : 13
Enter Element [3] : 17
Enter Element [4] : 24
Enter Element [5] : 33

Enter size of the 2nd array : 3

* Input the Array *

Enter Element [1] : 5


Enter Element [2] : 19
Enter Element [3] : 30

Bhargav Parashar 12 S Page | 104


The 1st Array is : 11 13 17 24 33
The 2nd Array is : 5 19 30
The Merged Array is : 5 11 13 17 19 24 30 33

DATA
STRUCTURES
Bhargav Parashar 12 S Page | 105
29)Program to push and pop
characters in an array-based queue:
ALGORITHM:
1.Begin
2.Declare class
3.Declae variables(ch[],capacity,top)
4.Assign capacity=cap, top=-1, ch.length=capacity
5.Enter Stack length to size
6.Send size value to cap in step 4
7.Declare i=0
8.If i<size, go to next step, else go to step 16
9.Enter character (i+1) in chhh
10. Assign chhh to v
11. top=top+1
12. If top=capacity, go to step 15, else go to next step
13. Assign ch[top]=v
14. i=i+1, go to step 8
15. Display " Wordpile is Full "
16. top=top+1
17. Declare i=0
Bhargav Parashar 12 S Page | 106
18. If i<capacity, go to next step, else go to step 25
19. top=top-1
20. If top=-1, go to step 24, else go to next step
21. Assign ct=ch[top]
22. Display ct
23. i=i+1, go to step 18
24. Display ch="/"
25. End.

SOURCE CODE:
import java.io.*;
public class Stack15
{
char ch[]; //variable declaration
int capacity;
int top;
public Stack15(int cap) //variable initialization
{
capacity=cap;
top=-1;
ch=new char[capacity];
}
void pushChar(char v)
{
if(top<capacity-1) //check queues status
{
top++;
ch[top]=v;
}
else
{
System.out.println("WordPile is full"); //full message
}
}
char popChar()
{
char val=' ';
if(top>=0)
{
Bhargav Parashar 12 S Page | 107
val=ch[top--];
return val;
}
Else
return '/'; //false return to indicate termination
}
void main()throws IOException //main method
{
int size;
char ct=' ';
String chhh=" ";
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the size of the stack, less
than 20:");
size=Integer.parseInt(br.readLine());
Stack15 obj=new Stack15(size); //new object
for(int i=1;i<=size;i++)
{
System.out.println("Enter element to be pushed at
position:"+i);
chhh=br.readLine();
obj.pushChar(chhh.charAt(0));
chhh=" ";
}
System.out.println("Stack is now full");
for(int j=1;j<=size;j++)
{
ct=obj.popChar(); //calling method out take out
element
System.out.println("Popped element:"+ct);
}
System.out.println("Stack is now empty");
} }
OUTPUT
Enter the size of the stack, less than 20:
4
Enter element to be pushed at position:1
f
Bhargav Parashar 12 S Page | 108
Enter element to be pushed at position:2
g
Enter element to be pushed at position:3
s
Enter element to be pushed at position:4
e
Stack is now full
Popped element:e
Popped element:s
Popped element:g
Popped element:f
Stack is now empty
30) Link is an entity which can hold a maximum
of 100 integers. Link enables the user to add
elements from the rear end and remove
integers from the front end of the entity.Specify
the class Link giving details of the
constructor(int ), void addlink(int ), intdellink()
and void display():
ALGORITHM:
1.Begin
2.Declare class
3.Declae variables(str[],capacity,top)
4.Assign capacity=cap, top=-1, str.length=capacity
5.Enter Stack length in: l
6.Send l value to cap in step 4
7.Declare i=0
8.If i<l, go to next step, else go to step 16
9.Enter name (i+1) in: temp
10. Assign temp to v
11. top=top+1
12. If top=capacity, go to step 15, else go to next
step
13. Assign str[top]=v
14. i=i+1, go to step 8
15. Display " Wordpile is Full "
16. top=top+1
Bhargav Parashar 12 S Page | 109
17. Declare i=0
18. If i<capacity, go to next step, else go to step
25
19. top=top-1
20. If top=-1, go to step 24, else go to next step
21. Assign st=str[top]
22. Display st
23. i=i+1, go to step 18
24. Display st="//"
25. End.

SOURCE CODE:
import java.io.*; // Java input output package called
public class Queue // class name
{
int Q[], rear, front; // instance variables
public Queue(int n) // parameterized constructor
{
Q=new int[n];
front=-1;
rear=-1;
}
public void insert(int num)
// method for inserting elements in queue and shifting
them forward
{
int p=Q.length;
if(rear<p-1) // condition to fill
{
rear++; // Updating rear as no. of elements increase
Q[rear]=num;
}
else
// max capacity of queue reached
System.out.println("The queue is full, cannot insert
data");
}
public void display()
Bhargav Parashar 12 S Page | 110
// method to display each element of queue starting from
front
{
while(front<rear)
{
front++;
System.out.println(Q[front]);
// virtual deletion, jst display of elements in front to
rear order
}
System.out.println("The queue is empty"); // If queue is
out of elements
}
public static void main()throws IOException // main
function
{
BufferedReader x=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter length of Array-based
Queue:");
int l=Integer.parseInt(x.readLine()); // input queue size
Queue obj=new Queue(l); // sending length of queue
int val, ch=1;
while(ch==1) // user based input option
{
System.out.println("Enter Data : ");
val=Integer.parseInt(x.readLine());
obj.insert(val); // method call, inserting elements
System.out.println("Any more data (1 for yes/ 0 for
no)?");
ch=Integer.parseInt(x.readLine());
}
System.out.println();
System.out.println();
obj.display(); // call display method after inserting is
done
}
}
OUTPUT
Bhargav Parashar 12 S Page | 111
Enter length of Array-based Queue:
3
Enter Data :
34
Any more data (1 for yes/ 0 for no)?
1
Enter Data :
23
Any more data (1 for yes/ 0 for no)?
1
Enter Data :
76
Any more data (1 for yes/ 0 for no)?
0

34
23
76
The queue is empty

Bhargav Parashar 12 S Page | 112


31) Program to demonstrate Last in,
first out in an array based queue:
ALGORITHM:
1.Begin
2.Declare Class
3.Declare variables(cap, top, m[],st[])

METHOD main()
1.Declare x, ret
2.Ask user to input size of array (less than 50) and store
in x
3.Send constructor Stack14 value of x and create object
obj with cap=x, top=-1, and create arrays st[cap] &
m[cap]
4.Call method input_marks(send obj)
5.Call method display(send obj)
6.Declare i=0
7.If i<x
8.Ret = the value returned by popmarks
9.If ret>0 proceed to next step, else to step 11
10. Output Element after popping: "+ret
11. Output stack underflow
12. i=i+1
13. go back to step 7
14. Call method display(send obj)
15. end

Bhargav Parashar 12 S Page | 113


METHOD input_marks
1.Declare i=0
2.If i<cap, go to next step, else to step 7
3.Enter element at position (i+1) and store it in m[i]
4.Call method pushmarks(send m[i])
5.i++
6.go back to step 2
7.go to step 5 of main method

METHOD display
1.Declare i=0
2.If i<cap, go to next step, else to step 6
3.Display element stored in position st[i]
4.i=i+1
5.go back to step 2
6.go to step 6 of main method

METHOD display
1.if top>=0, proceed to next step else to step 3
2.return st[top--] to main method
3.output stack over flow and return 0 to main method

SOURCE CODE:
import java.io.*;
public class Stack14 //main class
{
int m[];
int st[];
int cap;
int top;
public Stack14(int n) //constructor overload
{
cap=n;
top=-1;
st=new int[cap];
m=new int[cap];
}

Bhargav Parashar 12 S Page | 114


void input_marks()throws IOException //method to
input
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter marks to array M in
ascending order");
for(int i=0;i<cap;i++)
{
System.out.println("Enter element at position:"+
(i+1));
m[i]=Integer.parseInt(br.readLine());
pushmarks(m[i]);
}
}
void pushmarks(int v) //push variables out
{
if(top<cap)
{
top++;
st[top]=v;
}
else
{
System.out.println("Stack overflow");
}
}
int popmarks()
{
if(top>=0)
{
return st[top--];
}
else //error message
{
System.out.println("Stack underflow");
return 0;
}
}
Bhargav Parashar 12 S Page | 115
void display()
{
System.out.println("Elements of Array ST are");
for(int i=0;i<cap;i++)
{
System.out.println("Element in position"+
(i+1)+"is"+(st[i]));
}
}
void main()throws IOException //main method
{
int x,ret;
BufferedReader br2=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter size of the array, less than
50:");
x=Integer.parseInt(br2.readLine());
Stack14 obj=new Stack14(x);
obj.input_marks();
obj.display();
for(int i=0;i<x;i++)
{
ret=obj.popmarks();
if (ret>0)
System.out.println("Element after popping:"+ret);
else
System.out.println("Stack underflow");
}
obj.display();
}}
OUTPUT
Enter size of the array, less than 50:
3
Enter marks to array M in ascending order
Enter element at position:1
23
Enter element at position:2
45
Enter element at position:3
Bhargav Parashar 12 S Page | 116
67
Elements of Array ST are
Element in position1is23
Element in position2is45
Element in position3is67
Element after popping:67
Element after popping:45
Element after popping:23
Elements of Array ST are
Element in position1is23
Element in position2is45
Element in position3is67

Bhargav Parashar 12 S Page | 117


32)Program to demonstrate a doubly-ended
queue,which is a linear data structure
which enables the user to add and remove
integers from either ends, i.e. from front or
rear:
ALGORITHM:
1.Begin
2.Declare Class
3.Declare variables(cap=0,front=0,rear=0,ele[])
4.Declare cap=max, ele.length=cap

METHOD main()
1.Declare variables(v,f,max=0,chc=0)
2.Enter Size of Dequeue in: max
3.Send max to step 4 of class body
4.If chc!=6, go to next step, else go to step 27
5.Input option as per Menu given in variable: chc
6.If chc=1, go to next step, else go to step 10
7.Enter element to be inserted in front of dequeue in: v
8.Call method pushfront(send v)
9.Go to step 4
10. If chc=2, go to next step, else go to step 14
11. Enter element to be inserted in the rear of dequeue
in: v
12. Call method pushrear(send v)
13. Go to step 4
14. If chc=3, go to next step, else go to step 18
15. Call method popfront() and store popped value in: f
16. If f!=0, go to next step, else go to step 18
17. Display element popped from front: f
18. Go to step 4
19. If chc=4, go to next step, else go to step 23
20. Call method poprear() and store popped value in: f
21. If f!=0, go to next step, else go to step 23
22. Display element popped from rear: f
23. Go to step 4
24. If chc=5, go to next step, else go to step 26
Bhargav Parashar 12 S Page | 118
25. Call method display()
26. Go to step 4
27. End.

METHOD pushfront(v)
1.Receive value in v from main function
2.If front=0 and rear=0, go to next step, else go to step
5
3.ele[front]=v
4.rear=rear+1
5.If rear<=cap-1, go to next step, else go to step 12
6.Declare i=rear+1
7.If i>front, go to next step, else go to step 10
8.Put ele[i-1] in ele[i]
9.i=i-1, go to step 7
10. Put v in ele[front]
11. rear=rear+1, go to step 13
12. Display "Queue overflow"
13. Go to step 9 of method main()

METHOD pushrear(v)
1.Receive value in v from main function
2.If rear<=cap-1, go to next step, else go to step 5
3.Put v in ele[rear]
4.rear=rear+1
5.Display "Queue overflow"
6.Go to step 13 of method main()

METHOD popfront()
1.If front>=0, go to next step, else go to step 5
2.front=front+1
3.Send ele[front] value to step 15 main() method
4.Go to step 7
5.Display "Queue underflow"
6.Send 0 to step 15 main() method
7.Go to step 16 of method main()

METHOD poprear()
1.If rear!=0, go to next step, else go to step 5
Bhargav Parashar 12 S Page | 119
2.rear=rear-1
3.Send ele[rear] value to step 20 main() method
4.Go go step 7
5.Display "Queue underflow"
6.Send 0 to step 20 main() method
7.Go to step 21 of method main()

METHOD display()
1.Set i=front
2.If i<rear, go to next step, else go to step 5
3.Display Element. ele[i], with an arrow
4.i=i+1, go to step 2
5.Print line
6.Go to step 26 of method main()

SOURCE CODE:

import java.io.*; // Java input output package called


class Dequeue // class name
{
static int ele[]; // instance variables
static int cap, front, rear;
public Dequeue() // default constructor
{
cap=front=rear=0;
}
public Dequeue(int max) // parameterized constructor
{
front=0;
rear=0;
cap=max;
ele=new int[cap];
}

Bhargav Parashar 12 S Page | 120


public void pushfront(int v) // method to insert elements
from front
{
if(front==0&&rear==0) // checking condition to insert
{
ele[front]=v;
rear++; // updating rear
}
else if(rear<=cap-1)
{
for(int i=rear+1;i>front;i--)
ele[i]=ele[i-1]; // shifting of elements
ele[front]=v;
rear++;
}
else
System.out.println("Queue overflow"); // Showing
Queue is Full
}
public void pushrear(int v) // method to insert elements
from rear
{
if(rear<=cap-1)
{
ele[rear]=v; // updating front
rear++;
}
else
System.out.println("Queue overflow");
}
public int popfront() // method to delete elements from
front
{
if(front>=0)
return ele[front++]; // virtual reduction of queue
else
{
System.out.println("Queue underflow");
return 0; // return statements to caller
Bhargav Parashar 12 S Page | 121
}
}
public int poprear() // method to delete elements from
rear
{
if(rear!=0)
return ele[rear--]; // virtual reduction of queue
else
{
System.out.println("Queue underflow");
return 0;
}
}
public void display() // To display elements as per method
call
{
System.out.print("Element of the Dequeue are = ");
for(int i=front;i<rear;i++) // loop showing virtual
movement of elements
System.out.print(ele[i]+" -->");
System.out.println();
}
public static void main()throws IOException // main
function
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int v, f, max=0, chc=0; // local variables
System.out.println("Enter the Size of the Dequeue");
max=Integer.parseInt(br.readLine());
Dequeue ch=new Dequeue(max); // object creation
with parameter
System.out.println();
while(chc!=6) // Looping for handling error in option
based input
{
System.out.println("1. For Pushing Element in
Front");
System.out.println("2. For Pushing Element in Rear");
Bhargav Parashar 12 S Page | 122
System.out.println("3. For Popping Element From
Front");
System.out.println("4. For Popping Element From
Rear");
System.out.println("5. For Displaying Element of
DQueue");
System.out.println("6. For Terminating the
Program");
System.out.println();
System.out.println("Enter Your Choice");
chc=Integer.parseInt(br.readLine());
// switch-case for option based input by user
switch(chc)
{
case 1: // for inserting elements in front
System.out.println("Enter Number to be inserted
in the Dequeue:");
v=Integer.parseInt(br.readLine());
ch.pushfront(v); // method call
break; // termination statement

case 2: // for inserting elements from rear


System.out.println("Enter Number to be inserted
in the Dequeue:");
v=Integer.parseInt(br.readLine());
ch.pushrear(v); // method call
break;

case 3: // for deleting elements from front


f=ch.popfront();
if(f!=0) // checking necessary condition
System.out.println("Item "+f+" Deleted from
Front...");
break;

case 4: // for deleting elements from rear


f=ch.poprear();
if(f!=0)

Bhargav Parashar 12 S Page | 123


System.out.println("Item "+f+" Deleted from
Rear...");
break;

case 5: // for displaying Dequeue items


ch.display();
break;
}
System.out.println();
}
}
}
OUTPUT
Enter the Size of the Dequeue
2

1. For Pushing Element in Front


2. For Pushing Element in Rear
3. For Popping Element From Front
4. For Popping Element From Rear
5. For Displaying Element of DQueue
6. For Terminating the Program

Enter Your Choice


1
Enter Number to be inserted in the Dequeue:
43

1. For Pushing Element in Front


2. For Pushing Element in Rear
3. For Popping Element From Front
4. For Popping Element From Rear
5. For Displaying Element of DQueue
6. For Terminating the Program

Enter Your Choice


2
Enter Number to be inserted in the Dequeue:
43
Bhargav Parashar 12 S Page | 124
1. For Pushing Element in Front
2. For Pushing Element in Rear
3. For Popping Element From Front
4. For Popping Element From Rear
5. For Displaying Element of DQueue
6. For Terminating the Program

Enter Your Choice


5
Element of the Dequeue are = 43 -->43 -->

1. For Pushing Element in Front


2. For Pushing Element in Rear
3. For Popping Element From Front
4. For Popping Element From Rear
5. For Displaying Element of DQueue
6. For Terminating the Program

Enter Your Choice


6

Bhargav Parashar 12 S Page | 125


33) Program to demonstrate Stack data
structure.
Stack is a kind of data structure which can
store elements with the restriction that an
element can be added or removed from the
top only. Specify class Stack giving details
of the constructors(), void pushname(String
n), String popname() and void display().
ALGORITHM:
1.Begin
2.Declare class
3.Declae variables(str[],capacity,top)
4.Assign capacity=cap, top=-1, str.length=capacity
5.Enter Stack length in: l
6.Send l value to cap in step 4
7.Declare i=0
8.If i<l, go to next step, else go to step 16
9.Enter name (i+1) in: temp
10. Assign temp to v
11. top=top+1
12. If top=capacity, go to step 15, else go to next step
13. Assign str[top]=v
14. i=i+1, go to step 8
15. Display " Wordpile is Full "
16. top=top+1
17. Declare i=0
18. If i<capacity, go to next step, else go to step 25
19. top=top-1
20. If top=-1, go to step 24, else go to next step
21. Assign st=str[top]
22. Display st
23. i=i+1, go to step 18
Bhargav Parashar 12 S Page | 126
24. Display st="//"
25. End.

SOURCE CODE:
import java.io.*; //importing input output package
public class Stack11
{
String st[]; //constructing variables
int size,top,ctr;
Stack11() //constructor overloaded
{
size=0;
top=0;
ctr=0;
}
public Stack11(int cap)
{
size=cap;
top=-1;
st=new String[cap];
}
void pushname(String n)
{
if (top== (size-1)) //going to next variable
System.out.println(" Stack overflow");
else
st[++top]= n;
}
String popname()
{ if (top<0)
{
System.out.println("Stack underflow");
return "invalid";
}
else
return st[top--]; //stack underflow
}
void display()
{
Bhargav Parashar 12 S Page | 127
System.out.println("The stack is:");
for(int i=0;i<=size;i++)
{
System.out.println("Element at
position(i+1)is:"+st[i]);
}
}
public void main()throws IOException //main
method
{
String names="";
String f="";
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter size of the array:");
int p=Integer.parseInt(br.readLine());
Stack11 obj=new Stack11(p);
for (int k = 1 ; k <=p; k++) //loop to enter names
{
System.out.println("Enter name:");
names=br.readLine();
obj.pushname(names);
names="";
}
for (int l = 1 ; l<=p; l++)
{
f = obj.popname();
System.out.println("popped value ="+f);
}
}
}

OUTPUT

Enter size of the array:


Bhargav Parashar 12 S Page | 128
5
Enter name:
bhargav
Enter name:
Nicky
Enter name:
Superman
Enter name:
Milap
Enter name:
Bond
popped value =Bond
popped value =Milap
popped value =Superman
popped value =Nicky
popped value =bhargav

Bhargav Parashar 12 S Page | 129


INHERITAN
CE

34) Program to store the names and


ranks of 50 students. Find the
highest rank and his name using the
concept of inheritance:
Bhargav Parashar 12 S Page | 130
ALGORITHM:
CLASS Record
1.Begin
2.Create a String array name[] and integer array rnk[]
with variable lim
3.Assign l to lim and initiate the two arrays using the
constructor
4.Enter the values to names and ranks through method
readvalues()
5.Print the names and corresponding ranks

CLASS Rank
1.Declare index as integer variable
2.Enter value to l and send it to lim in the parent class
through the constructor of the child class
3.Call method readvalues of the parent class from the
one in the child class
4.i=0
5.i<lim given in the parent class, go to step 6 else go to
10
6.if the rank [] from the parent class at i>index, go to
step 7
7.index=i
8.Add I to i
9.Go to step 5
10. Display the topmost rank after printing the display
method of the parent class
11. End

SOURCE CODE:
import java.io.*; //import package
class Record
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String name[];
int rnk[];
Record() //constructor
Bhargav Parashar 12 S Page | 131
{
name=new String[50];
rnk=new int[50];
}

void readvalues()throws IOException //method to read


values
{

System.out.println("Enter names");
for(int i=0;i<50;i++) //loop to enter names
{ System.out.println("Name "+(i+1)+" = ");
name[i]=br.readLine();
System.out.println("Enter his/her rank");
rnk[i]=Integer.parseInt(br.readLine());
}

}
void display() //displaying output
{
System.out.println("The names and corresponding
ranks:");
for(int i=0;i<50;i++)
{
System.out.println("Name "+name[i]+" Rank
"+rnk[i]);
}
}
}
public class Rank extends Record //sub class
{
int index;
Rank()
{
super();
index=0;
}

void highest() throws IOException


Bhargav Parashar 12 S Page | 132
{
int min=rnk[0];
for(int i=0;i<50;i++)
{
if(rnk[i]<min) //calling super class
index=i;
}
}

void display()
{
super.display();
System.out.println("The topmost rank belongs to:
"+name[index]);
}
}
class Inheritance
{

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


//main method
{
Rank ob=new Rank();
ob.readvalues();
ob.highest();

System.out.println("Output");
ob.display();
}
}

OUTPUT

Bhargav Parashar 12 S Page | 133


Enter names
Name 1 =
Bhargav
Name 2 =
Milap
Name 3 =
Hrishikesh
Enter ranks
Enter rank 1 =
3
Enter rank 2 =
1
Enter rank 3 =
2
The names and corresponding ranks:
Name Bhargav Rank 3
Name Milap Rank 1
Name Hrishikesh Rank 2
The topmost rank belongs to: Milap

35) Program to store the details of a


customer. Compute the monthly
telephone charge of the customer
using inheritance:
A super class Detail has been defined to store the
details of a customer. Define a sub class Bill to
Bhargav Parashar 12 S Page | 134
compute the monthly telephone charge of the
customer as per the chart given below:

NUMBER OF RATE
CALLS
100 Only rental charge
101-200 60 paisa per call +
rental charge
201-300 80 paisa per call +
rental charge
Above 300 1 rupee per call +
rental charge

ALGORITHM:
CLASS Detail
1. Begin
2. Declare variables name,address,telno,rent and
initialize through constructor
3. Print name,address,telno,rent

CLASS Bill
1.Declare variable n=no and amt
2.Send the values of na,add,tno,rnt to the parent class
through constructor
3.if(n<=100), amt=rent and go to step 7,else go to 6
4.if (n>100&& n<=200), amt=rent+(0.60*(n-100)) and
go to step 7,else go to 6
5.if(n>200&&n<=300), amt=rent+(0.60*100)+(0.80*(n-
200)) and go to step 7,else go to 6
6.amt=rent+(0.60*100)+(0.80*100)+(1*(n-300))
7.Call show option of the parent class then print the
number of calls made and the amount
8.End

SOURCE CODE:

import java.io.*;
class Detail
Bhargav Parashar 12 S Page | 135
{
protected String name; //base
variables
protected String address;
protected long telno;
protected int rent;
Detail(String na,String add, long tno, int rnt)
//constructor
{
name=na;
address=add;
telno=tno;
rent=rnt;
}

void show() //output method


{
System.out.println();
System.out.println("OUTPUT");
System.out.println("Name is: "+name);
System.out.println("Address is: "+address);
System.out.println("Telephone number is: "+telno);
System.out.println("Rent paid is: "+rent);
}
}
public class Bill extends Detail
{
int n;
double amt;
public static void main()throws IOException
//control method
{
String nam=" ";
String addrs=" ";
long tele=0;
int num=0;
int ren=0;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Bhargav Parashar 12 S Page | 136
System.out.println("Enter name");
nam=br.readLine();
System.out.println("Enter address");
addrs=br.readLine();
System.out.println("Enter telephone number");
tele=Long.parseLong(br.readLine());
System.out.println("Enter rent:");
ren=Integer.parseInt(br.readLine());
System.out.println("Enter number of phone calls");
num=Integer.parseInt(br.readLine());
Bill obj=new Bill(nam,addrs,tele,ren,num);
//object creation
obj.cal();
obj.show();
}

public Bill(String na,String add, long tno, int rnt, int no)
{
super(na,add,tno,rnt);
n=no;
amt=0.0;
}

void cal()
{
if(n<=100)
amt=rent;
else if (n>100&&n<=200)
amt=rent+(0.60*(n-100));
else if(n>200&&n<=300)
amt=rent+(0.60*100)+(0.80*(n-200));
else
amt=rent+(0.60*100)+(0.80*100)+(1*(n-300));
}

void show()
{
super.show();
System.out.println();
Bhargav Parashar 12 S Page | 137
System.out.println("No of phone calls: "+n);
System.out.println("Amount to be paid: "+amt);
}
}

OUTPUT
Enter name
Bhargav
Enter address
Tezpur
Enter telephone number
967878696
Enter rent:
12000
Enter number of phone calls
345
OUTPUT
Name is: Bhargav
Address is: Tezpur
Telephone number is: 967878696
Rent paid is: 12000

No of phone calls: 345


Amount to be paid: 12185.0
36) Program to calculate the area
and perimeter of a parallelogram
using the concept of inheritance:
A super class Perimeter has been defined to
calculate the perimeter of a parallelogram. Define a
sub class Area to compute the area of the
parallelogram by using the required data members of
the super class.

ALGORITHM:
SUPER CLASS:-
1.Begin
Bhargav Parashar 12 S Page | 138
2.Declare class
3.Declare variables(a,b)
4.Assign a=lenght, b=breadth
5.Calculate per=2*(a+b)
6.Display Length of Parallelogram: a
7.Display Breadth of Parallelogram: b
8.Display Perimeter of Parallelogram: per

SUBCLASS:-
1.Begin
2.Declare Class
3.Inherit super class
4.Declare variables(h,b)
5.Initialise (height, bred) for super class' step 4 after
input in sub class
6.Assign h= heigh, after input of height value in subclass
7.Call step 5 from superclass
8.area=b*h
9.Call step 6 to 8 of superclass
10. Display Height of Parallelogram: h
11. Display Area of Parallelogram: b
12. End.

SOURCE CODE:

import java.io.*;
class Peri
{
double a;
double b;
Peri(double length,double breadth)
{
a=length;
b=breadth;
}
double Calculate() //calculating
{
return (2*(a+b));
Bhargav Parashar 12 S Page | 139
}
void show() //display
{
System.out.println();
System.out.println("OUTPUT:-");
System.out.println("Length: "+a);
System.out.println("Breadth: "+b);
System.out.println("Perimeter: "+Calculate() );
}
}
public class Area extends Peri
{
double h;
double b;
void main()throws IOException //main function
{
double x=0.0;
double y=0.0;
double z=0.0;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)); //input out buffer
System.out.println("Enter the length of the
paralellogram:");
x=Double.parseDouble(br.readLine());
System.out.println("Enter the breadth of the
paralellogram:");
y=Double.parseDouble(br.readLine());
System.out.println("Enter the height of the
paralellogram:");
z=Double.parseDouble(br.readLine());
Area obj= new Area(x,y,z);
obj.doarea();
obj.show();
}
Area(double lenght,double bred, double heigh)
{
super(lenght,bred);
h=heigh;
Bhargav Parashar 12 S Page | 140
b=0.0;
}
void doarea()
{
b=super.b*h; //calling super class
method
}
void show()
{
super.show();
System.out.println("The height of the parallelogram:
"+h);
System.out.println("The area of the parallelogram:
"+b);
}
}

OUTPUT

Enter the length of the paralellogram:


2
Enter the breadth of the paralellogram:
3
Enter the height of the paralellogram:
4

OUTPUT:-
Length: 2.0
Breadth: 3.0
The height of the parallelogram: 4.0
Perimeter: 10.0

The area of the parallelogram: 12.0

Bhargav Parashar 12 S Page | 141


37) Program to find the radius and
area of a circle based on coordinates
using the concept of inheritance:
A line on a plane can be represented by coordinates
of two end-points p1 and p2 as pi(x1,y1) and
p2(x2,y2). A super class Place is defined to represent
a line and a sub class Circle to find the length of the
radius and the area of a circle by using the required
data members of super class.

ALGORITHM:
SUPER CLASS:-
1.Begin
2.Declare class
3.Declare variables(x1,y1)
4.Assign x1=x, y1=y
5.Display x-coordinate of First End Point: x1
6.Display y-coordinate of First End Point: y1

SUBCLASS:-
Bhargav Parashar 12 S Page | 142
1.Begin
2.Declare Class
3.Inherit super class
4.Declare variables(x2,y2,radius,area,pi=3.14)
5.Initialise (x,y) for super class' step 4 after input in sub
class
6.Assign x2=a, y2=b, after input of these values in
subclass
7.radius=(((x2-x1)^2)+((y2-y1)^2))^(1/2)/2
8.area=(radius^2)*pi
9.Call step 5 and 6 of Super Class
10. Display x-coordinate of Second End Point: x2
11. Display y-coordinate of Second End Point: y2
12. Display Radius of Circle: radius
13. Display Area of Circle: area
14. End.

SOURCE CODE:

import java.io.*; //import input-output class


class Plane
{
protected int x1; //base class variables
protected int y1;
Plane(int x,int y)
{ x1=x;
y1=y;
}
void Show() //output
{
System.out.println("Output");
System.out.println("The x-coordinate of the 1st point
is: "+x1);
System.out.println("The y-coordinate of the 1st point
is: "+y1);
System.out.println();
}
}
public class Circle extends Plane
Bhargav Parashar 12 S Page | 143
{
int x2;
int y2;
double radius;
double area;
double pie=3.14;
public Circle(int x, int y, int a, int b) //object parameters
{
super(x,y);
x2=a;
y2=b;
radius=0.0;
area=0.0;
}
void Show()
{
super.Show();
System.out.println("The x-coordinate of the 2nd point
is: "+x2);
System.out.println("The y-coordinate of the 2nd point
is: "+y2);
System.out.println("The radius:"+radius);
System.out.println("The area:"+area);
}
void findRadius()
{
radius=(Math.sqrt(Math.pow((x2-x1),2)+Math.pow((y2-
y1),2)))/2;
}
void findArea()
{
area=pie*radius*radius;
}
void main()throws IOException //main function
{
int q,w,e,r;
BufferedReader br= new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter x-coordinate for 1st point:");
Bhargav Parashar 12 S Page | 144
q=Integer.parseInt(br.readLine());
System.out.println("Enter y-coordinate for 1st point:");
w=Integer.parseInt(br.readLine());
System.out.println("Enter x-coordinate for 2nd point:");
e=Integer.parseInt(br.readLine());
System.out.println("Enter y-coordinate for 2nd point:");
r=Integer.parseInt(br.readLine());
System.out.println();
Circle obj=new Circle(q,w,e,r); //sending
parameters to constructor
obj.findRadius();
obj.findArea();
obj.Show();
}
}

OUTPUT

Enter x-coordinate for 1st point:


2
Enter y-coordinate for 1st point:
2
Enter x-coordinate for 2nd point:
-2
Enter y-coordinate for 2nd point:
-2

Output
The x-coordinate of the 1st point is: 2
The y-coordinate of the 1st point is: 2

The x-coordinate of the 2nd point is: -2


The y-coordinate of the 2nd point is: -2
The radius:2.8284271247461903
The area:25.120000000000005

Bhargav Parashar 12 S Page | 145


RECURSSIO
N
Bhargav Parashar 12 S Page | 146
38) Program to calculate the sum of
the series:X2/1! + x4/3! + x6/5! +
..+ xn/(n-1)! :

WHERE ! STANDS FOR FACTORIAL

ALGORITHM:
1.Begin
2.Declare a class SeriesSum with x and n as integer
variables and sum as a double
Variable
3.Enter the values of and integer p and q through
constructor/ object obj
4.Call functions calculate() and display() using obj

METHOD double findfact(int m)


1.y=1,i=1
2.If i<=m, got o step 3 else go to step 6
3.y=y*i
4.Add 1 to i
5.Go to step 2
6.Return y

METHOD double findpower(int x, int y)


1.Declare a variable double c
Bhargav Parashar 12 S Page | 147
2.c= y times x or x^y

METHOD calculate()
1.Declare the variables double calculate and num
2.Integer i=2
3.If i<=n*2, go to step 4, else go to step 9
4.fact=findfact(i-1), calling function to variable fact
5.num=findpower(x,i), calling function to variable sum
6.sum=sum+(num/fact), to calculate the final output
7.Add 1 to i
8.Go to step 3
9.Exit to main

METHOD display()
1.Print sum
2.End of Algorithm.

SOURCE CODE:

import java.io.*; // Java input output package called


public class SeriesSum // class name
{
int x, n, temp; // instance variable declaration
double sum;
SeriesSum(int xx, int nn) // parameterized constructor
{
x=xx;
n=nn;
temp=1;
sum=0.0;
}
Bhargav Parashar 12 S Page | 148
double findfact(int m) // recursive function for finding
factorial of a number 'm'
{
if(m>=1) // checking condition for factorial
{
temp=temp*m ; // calculating factorial
m--; // decreement iteration
return findfact(m); // recursive call
}
else
{
int k=temp; // copying factorial value
temp=1; // resetting factorial holder to 1
return k; // returning factorial value to caller function
}
}

void calculate() // function to calculate sum of series


{
for(int i=2;i<=n*2;i=i+2)
// loop to calculate sum and repeatedly call recursive
function 'findfact'
sum=sum+(Math.pow(x,i)/findfact(i-1));
}
void display() // function to display sum of the series
{
System.out.println("Sum of Series is:" +sum);
}

public static void main()throws IOException // main


function
{
BufferedReader f=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter Numerator for series sum:");
int x1=Integer.parseInt(f.readLine()); // inputting
numerator of series
System.out.println("Enter limit of series:");
Bhargav Parashar 12 S Page | 149
int n1=Integer.parseInt(f.readLine()); // inputting limit
of series
SeriesSum obj=new SeriesSum(x1,n1); // object
sending values to constructor
obj.calculate(); // method calls by object of main
function
obj.display();
}
}

OUTPUT
Enter Numerator for series sum:
2
Enter limit of series:
3
Sum of Series is:7.199999999999999

Bhargav Parashar 12 S Page | 150


39) Program to interchange upper
case to lower case words and vice
versa:
ALGORITHM:
1.Begin
2.Create a class CaseRecur
3.Declare s and s1 as String variables, ch as a character
variable and n and m as integer variables
4.Store input in n and s
5.Call function recchar()

METHOD recchar(int p)
1.If p<0, call function display(), else go to step 2
2.Assign character at p to ch
3.Assign ch to m
4.If (m>=65&&m<=90), go to step 5 else go to step 8
5.Add 32 to m
6.Put character value of m to ch
7.s1=ch+s1
8.If (m>=97&&m<=122), go to step 9 else go to step
12
9.Subtract 32 from m
10. Put character value of m to ch
11. s1=ch+s1
12. call recchar(--p)
13. Exit to main

METHOD display()
1.Print original string
2.Print new string

SOURCE CODE:
Bhargav Parashar 12 S Page | 151
import java.io.*;
public class CaseRecur
{
String s; //variable declaration
String s1="";
char ch;
int n,m;
void main()throws IOException //main method
{
BufferedReader a= new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter string:");
s=a.readLine();
n=s.length();
recchar(n-1);
}

void recchar(int p)throws IOException


{
if(p<0)
display();
else
{
ch=s.charAt(p);
m=ch;
if(m>=65&&m<=90) //checking if upper case
{
m=m+32;
ch=(char)m;
s1=ch+s1;
}
else if(m>=97&&m<=122) //checking if lower case
{
m=m-32;
ch=(char)m;
s1=ch+s1;
}
recchar(--p); //calling itself
Bhargav Parashar 12 S Page | 152
}
}
void display()
{
System.out.println("The original string is:"+s);
System.out.println("The new string is:"+s1);
}
}

OUTPUT

Enter string:
Go To School
The original string is:Go To School
The new string is:gOtOsCHOOL

40) Program to check whether a


number is a happy number:
ALGORITHM:
1.Begin
Bhargav Parashar 12 S Page | 153
2.Declare class
3.Declare variables (n=0,sum=0,p=0)
4.Input number in integer variable: p
5.Assign p to integer variable nn
6.Assign n=nn
7.Declare integer variable z
8.z=call: sum_sq_digits(sending n to method), then go to
next step
9.If z=1, go to next step, else go to step 11
10. Display n as Happy Number
11. Display n as Not a Happy Number

Method sum_sq_digits(x):
1.If x>0, go to next step, else go to step (5)
2.d=x%10
3.sum=sum+(d*d)
4.x=x/10, Return to step (1)
5.x=sum, sum=0
6.if x>9, go to step (1), else go to next step
7.Send x value to step 8 method call, Exit
sum_sq_digits(x)

SOURCE CODE:

import java.io.*; // Java input output package called


class RecurHappy // class name
{
BufferedReader a=new BufferedReader(new
InputStreamReader(System.in));
int n, sum, d; // instance variable declaration
RecurHappy() // default constructor
{
n=0;
sum=0;
d=0;
}
public void main()throws IOException // main function
{
System.out.println("Enter Number:");
Bhargav Parashar 12 S Page | 154
int p=Integer.parseInt(a.readLine()); // inputting
number to be checked
RecurHappy obj=new RecurHappy(); // object creation
obj.getnum(p); // method call with parameter
obj.ishappy();
}
void getnum(int nn) // function to accept number
{
n=nn;
}
void ishappy() // function to call and check whether it is
happy no. or not
{
System.out.println();
int z=sum_sq_digits(n); // calling function
if(z==1) // checking condition
System.out.println(n+ " is a Happy Number");
else
System.out.println(n+ " is Not a Happy Number");
}
int sum_sq_digits(int x)
// function to calculate sum of eventual squares of digits of
no.
{
if(x>0)
{
d=x%10;
sum=sum+(d*d); // calculating sum of digits
return sum_sq_digits(x/10); // recursive call
}
else
{
x=sum; // copying sum value for continuity
sum=0;
if(x>9) // checking if sum is a single digit number
return sum_sq_digits(x);

else
Bhargav Parashar 12 S Page | 155
return x; // return statement to caller function
}
}
}

OUTPUT
Enter Number:
31

31 is a Happy Number

Bhargav Parashar 12 S Page | 156


Bhargav Parashar 12 S Page | 157

Potrebbero piacerti anche