Computer Project (Srishti)
Computer Project (Srishti)
COMPUTER SCIENCE
Programming assignments Session:
2023-24
Submitted by - Submitted to -
Name - SANCHITA SRIVASTAVA Mr. Amit Kumar Trivedi
UID -
Index Number-
Page|2
CERTIFICATE
Name :- _____________________________________
ACKNOWLEDGMENT
Name:
PROGRAM 1
A Goldbach number is a positive even integer that can be expressed as the sum
of two odd primes.
Note: All even integer numbers greater than 4 are Goldbach numbers.
Example:
6=3+3
10 = 3 + 7
10 = 5 + 5
Hence, 6 has one odd prime pair 3 and 3. Similarly, 10 has two odd prime
pairs, i.e. 3 and 7, 5 and 5.
Write a program to accept an even integer 'N' where N > 9 and N < 50. Find all
the odd prime pairs whose sum is equal to the number 'N'.
Test your program with the following data and some random data:
Example 1
INPU
T:
N=
14
OUTPUT:
PRIME PAIRS ARE:
3, 11
7, 7
Example 2
INPU
T: N =
30
OUTPUT:
PRIME PAIRS
ARE: 7, 23
11, 19
13, 17
Example 3
INPU
T: N =
17
OUTPUT:
INVALID INPUT. NUMBER IS ODD.
Example 4
INPUT:
N = 126
OUTPUT:
INVALID INPUT. NUMBER OUT OF RANGE.
Page|6
ALGORITHM:
• Initialize a number ‘N’.
• Store it in a variable.
• Check if the number is even or not.
• If the number is odd, print “Invalid Input’.
• If the number is even then,
o Define two arrays. One for storing prime numbers and other for
calculating the prime numbers.
o Find all prime numbers till the entered number
using a ‘for loop’ and store it in an array.
o In the second array, store only odd prime numbers using ‘if’ statement.
SOURCE CODE:
import java.util.*;
public class Goldbach
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in); int
i,j,k,b=0,c=0,num=0,sum=0;
System.out.println("Enter the number: "); int
num=sc.nextInt(); k=num;
int arr1[]=new int[num];
int arr2[]=new int[num];
if(num%2!=0)
{
System.out.println("Invalid Input, Number is odd");
}
else
{
for(i=1;i<=num;i++)
{
for(j=1;j<=i;j++)
{ if(i
%j==0)
{ c
++;
}
}
if((c==2)&&(i%2!=0))
{ arr1[
b]=i; arr2[b]=i;
b++;
}
c=0;
}
System.out.println("Odd and prime pairs are: ");
for(i=0;i<b;i++)
{
for(j=i;j<b;j++)
{
sum=arr1[i]+arr2[j];
if(sum==k)
{
System.out.print(arr1[i]+" , "+arr2[j]);
System.out.println();
Page|8
}
}
}
System.out.println(k+" is a Goldbach Number");
}
}
}
OUTPUT:
PROGRAM 2
Write a program to declare a matrix a[][] of order (m × n) where 'm' is the
number of rows and 'n' is the number of columns such that the values of both 'm'
and 'n' must be greater than 2 and less than 10. Allow the user to input integers
into this matrix. Perform the following tasks on the matrix:
Test your program for the following data and some random data:
P a g e | 10
Example 1
INPUT:
M
=4
N=3
ENTER ELEMENTS OF MATRIX:
11 -2 3
5 16 7
9 0 4
3 1 8
nnOUTPUT:
ORIGINAL
MATRIX
11 -2 3
5 16 7
9 0 4
3 1 8
P a g e | 11
9 13 6
OUTPUT:
ORIGINAL MATRIX
22 5 19
7 36
12 9
13 6
MATRIX AFTER SORTING ROWS
5 19 22 7 12 36
6 9 13
Example 3
INPUT:
M
N= 5
OUTPUT:
MATRIX SIZE OUT OF RANGE
ALGORITHM:
• Start.
• Declare variables.
• Check if the value of m and n is less than 2 and greater than 10, if so print
‘Invalid Input’ and terminate the program.
• Else.
• Create a matrix of order ‘M’*’N’.
• Enter the values in the matrix.
• Find the largest number.
P a g e | 13
SOURCE CODE:
import java.util.Scanner;
public class ArraySort
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("ENTER THE VALUE OF M: ");
int m = in.nextInt();
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt();
if (m <= 2|| m >= 10|| n <= 2 || n >= 10)
{
System.out.println("Invalid Input");
return;
}
int a[][] = new int[m][n];
System.out.println("ENTER ELEMENTS OF MATRIX:");
for (int i = 0; i < m; i++)
OUTPUT:
PROGRAM 3
The names of the teams participating in a competition should be displayed on a
banner vertically, to accommodate as many teams as possible in a single banner.
Design a program to accept the names of N teams, where 2 < N < 9 and display
them in vertical order, side by side with a horizontal tab (i.e. eight spaces).
Test your program for the following data and some random data:
Example 1
INPUT:
N=3
Team 1: Emus
Team 2: Road Rols
Team 3: Coyote
OUTPUT:
E R
Cm o
ou a
ys d
o
t R
e o
l
s
Example 2
INPUT:
N=4
Team 1: Royal
Team 2: Mars
Team 3: De Rose
Team 4: Kings
OUTPUT:
R M D
Ko a e
iy r
na s R
gl o
s s
e
Example 3
INPU
T: N =
10
OUTPUT:
INVALID INPUT
ALGORITHM:
• Initialize a number N to store number of names.
• Initialize array.
• If the entered number is less than 2 and more than 9 then print ‘Invalid
Input’.
SOURCE CODE:
import java.util.*;
public class Banner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt();
in.nextLine();
if (n <= 2 || n >= 9)
{
System.out.println("INVALID INPUT");
return;
}
String teams[] = new String[n];
int highLen = 0;
for (int i = 0; i < n; i++)
{
System.out.print("Team " + (i+1) + ": ");
teams[i] = in.nextLine();
if (teams[i].length() > highLen)
{
highLen = teams[i].length();
}
}
for (int i = 0; i < highLen; i++)
{
for (int j = 0; j < n; j++)
{
int len = teams[j].length();
if (i >= len)
{
P a g e | 21
System.out.print(" \t");
}
else
{
System.out.print(teams[j].charAt(i) + "\t");
}
}
System.out.println();
}
}
}
PROGRAM 4
Methods/Member functions:
Perfect (int nn) : parameterized constructor to initialize the data member
num=nn.
int sum_of_factors(int i) : returns the sum of the factors of the number(num),
excluding itself, using recursive technique.
void check( ) : checks whether the given number is perfect by invoking the
function sum_of_factors( ) and displays the result with an appropriate message.
Specify the class Perfect giving details of the constructor( ), int
sum_of_factors(int) and void check( ). Define a main( ) function to create an
object and call the functions accordingly to enable the task.
ALGORITHM:
• Step 1 – Start, Initialize the instance variable.
• Step 2 – Make a default constructor.
• Step 3 – Make the function to return the sum of the factors of the number.
• Step 4 – Make the function to check whether the given number is perfect by
invoking the previous function.
• Step 5 – Make the main function.
• Step 6 – Input a number and Check whether it is a Perfect number or Not.
• Step 7 - End.
SOURCE CODE:
import java.util.*;
class Perfect
{
int num;
Perfect(int nn)
{
num=nn;
}
int sum_of_factors(int i)
{
if (i == num)
return 0; else if (num%i==0)
return i + sum_of_factors(i+1); else
return sum_of_factors(i+1);
}
void check()
{
int s=sum_of_factors(1);
if (s==num)
PROGRAM 5
Two matrices are said to be equal if they have the same dimension and their
corresponding elements are equal.
Design a class EqMat to check if two matrices are equal or
not. Assume that the two matrices have the same
dimension.
a[ ][ ] : to store integer
elements m : to store the
number of rows
n : to store the number of columns
Member functions/methods:
Define the class EqMat giving details of the constructor( ), void readarray( ), int
check(EqMat, EqMat) and void print( ). Define the main( ) function to create
objects and call the functions accordingly to enable the task.
ALGORITHM:
• Step 1 – Make the parameterized constructor.
• Step 2 – Make the function „readarray‟ to input the elements in the array.
SOURCE CODE:
import java.util.*;
class EqMat
{ int a[]
[]; int m;
int n;
static Scanner sc=new Scanner(System.in);
EqMat(int mm,int nn)
{
m=mm;
n=nn;
a=new int[m][n];
}
void readarray()
{
System.out.println("Enter " + (m*n) + " elements" );
for (int i=0;i<m;i++) for (int j=0;j<n;j++)
a[i][j]=sc.nextInt();
}
int check(EqMat P,EqMat Q)
{
for (int i=0;i<P.m;i++)
OUTPUT :
}
else
System.out.println("No
t Equal");
}
}
VARIABLE
DESCRIPTION TABLE:
PROGRAM 6
A class Capital has been defined to check whether a sentence has words
beginning with a capital letter or not.
Some of the members of the class are given below:
Class name : Capital
Data member/instance variable:
sent : to store a sentence freq : stores the frequency of
words beginning with a capital letter Member
functions/methods:
Capital( ) : default
constructor void input() : to
accept the sentence
boolean isCap(String w) : checks and returns true if word begins with a capital
letter, otherwise returns false void display () : displays the sentence along with
the frequency of the words beginning with a capital letter.
Specify the class Capital, giving the details of the constructor( ), void input( ),
boolean isCap(String) and void display( ). Define the main( ) function to create
an object and call the functions accordingly to enable the task
ALGORITHM:
• Step 1 – Start; Make the default constructor.
• Step 2 – Make a function input to input the values from user.
• Step 3 – Make a function „isCap‟ to check and returns true if word begins
with a capital letter, otherwise returns false.
SOURCE CODE:
import java.util.*;
class Capital
{
String sent;
int freq;
Capital()
{
sent="";
freq=0;
}
void input()
{
Scanner sc=new Scanner(System.in); System.out.println("Enter
the sentence");
sent=sc.nextLine();
}
boolean isCap(String w)
{
char c=w.charAt(0); if
(Character.isUpperCase(c) )
return true;
else
return false;
}
void display()
{
System.out.println("sentence="+sent);
StringTokenizer ob=new StringTokenizer(sent); int
count=ob.countTokens();
for (int i=0;i<count;i++)
{
String wd=ob.nextToken();
if (isCap(wd))
freq=freq+1;
}
System.out.println("Frequency of title word="+freq);
}
public static void main(String args[])
{
Capital ob=new Capital();
ob.input();
ob.display();
}
}
OUTPUT:
PROGRAM 7
Design a program to accept a day number (between 1 and 366), year (in 4
digits) from the user to generate and display the corresponding date. Also,
accept 'N' (1 <= N <= 100) from the user to compute and display the future date
corresponding to 'N' days after the generated date. Display an error message if
the value of the day number, year and N are not within the limit or not
according to the condition specified.
Test your program with the following data and some random data:
Example 1
INPUT:
DAY NUMBER: 255
YEAR: 2018
DATE AFTER (N DAYS): 22
OUTPUT:
DATE: 12TH SEPTEMBER, 2018
DATE AFTER 22 DAYS: 4TH OCTOBER, 2018
Example 2
INPUT:
DAY NUMBER: 360
YEAR: 2018
DATE AFTER (N DAYS): 45
OUTPUT:
DATE: 26TH DECEMBER, 2018
DATE AFTER 45 DAYS: 9TH FEBRUARY, 2019
Example 3
INPUT:
DAY NUMBER: 500
YEAR: 2018
DATE AFTER (N DAYS): 33
OUTPUT:
DAY NUMBER OUT OF RANGE
Example 4
INPUT:
DAY NUMBER: 150
YEAR: 2018
DATE AFTER (N DAYS): 330
OUTPUT:
DATE AFTER (N DAYS) OUT OF RANGE
ALGORITHM:
• Step 1 –The Program enter the Day number and Year.
• Step 2 –The dateofmonth() function checks the month and checks for leap
year.
• Step 3– The main functions runs datetomonth() function and print the date
and month after n days.
SOURCE CODE:
import java.util.Scanner;
if (y % 400 == 0) {
ret = true;
}
else if (y % 100 == 0)
{
P a g e | 31
ret = false;
}
else if (y % 4 == 0)
{
ret = true;
}
else
{
ret = false;
}
return ret;
}
int i = 0; int
daySum = 0;
for (i = 0; i < monthDays.length; i++)
{
daySum += monthDays[i];
if (daySum >= day)
{
break;
}
}
2023-23| SANCHITA SRIVASTAVA
P a g e | 41
P a g e | 32
return sb.toString();
}
nYear = nYear + 1;
nDays = nDays - 366;
}
else if (nDays > 365)
{
nYear = nYear + 1;
nDays = nDays - 365;
}
System.out.println();
System.out.println("DATE: " + dateStr);
System.out.println("DATE AFTER " + n
+ " DAYS: " + nDateStr);
}
}
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Program 8:
Write a program to declare a single-dimensional array a[] and a square matrix
b[][] of size N, where N > 2 and N < 10. Allow the user to input positive
integers into the single dimensional array.
Perform the following tasks on the matrix:
1258
1251
1212
1125
Test your program for the following data and some random data:
Example 1
INPUT:
N=3
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: 3 1 7
OUTPUT:
131
113
ALGORITHM:
• Step 1- Entering the matrix and array.
P a g e | 47
P a g e | 36
SOURCE CODE:
import java.util.Scanner;
sortArray(a);
System.out.println("SORTED ARRAY:");
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
System.out.println("FILLED MATRIX:");
for (int i = 0; i < n; i++) { for (int j = 0; j <
n; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
}
}
Program 9
Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’
or ‘!’ only. The words are to be separated by a single blank space and are in
uppercase.
Perform the following tasks:
(a) Check for the validity of the accepted sentence.
(b) Convert the non-palindrome words of the sentence into palindrome
words by concatenating the word by its reverse (excluding the last
character).
Example:
The reverse of the word HELP would be LEH (omitting the last alphabet) and by
concatenating both, the new palindrome word is HELPLEH. Thus, the word
HELP becomes HELPLEH.
Note: The words which end with repeated alphabets, for example ABB would
become ABBA and not ABBBA and XAZZZ becomes XAZZZAX.
[Palindrome word: Spells same from either side. Example:
DAD, MADAM etc.] (c) Display the original sentence along
with the converted sentence. Test your program for the
following data and some random data: Example 1 INPUT:
THE BIRD IS
FLYING. OUTPUT:
THE BIRD IS FLYING.
THEHT BIRDRIB ISI FLYINGNIYLF
ALGORITHM:
• Step 1 – Entering the sentence and converting in UPPERCASE
• Step 2 – Checking whether the sentence terminates with ‘.’ , ‘?’ ,’!’
• Step 3 – Running loop to get palindrome of each word.
• Step 4 – Concatenating each word of the sentence
SOURCE CODE:
P a g e | 40
return palin;
}
return sb.toString();
}
while (st.hasMoreTokens())
{ String word = st.nextToken();
boolean isPalinWord = isPalindrome(word);
if (isPalinWord) {
sb.append(word);
}
else {
String palinWord = makePalindrome(word);
sb.append(palinWord);
}
sb.append(" ");
}
System.out.println();
System.out.println(ipStr);
System.out.println(convertedStr);
}
}
2023-23| SANCHITA SRIVASTAVA
P a g e | 59
VARIABLE DESCRIPTION
TABLE:
OUTPUT :
PROGRAM 10
Design a class ArmNum to check if a given number is an Armstrong number or
not. [A number is
said to be Armstrong if sum of its digits raised to the power of length of the
number is equal to
the number]
Example : 371 = 33 + 73 + 13
1634 = 14 + 64 + 34 + 44
54748 = 55 + 45 + 75 + 45 + 85
Thus 371, 1634 and 54748 are all examples of Armstrong numbers.
Some of the members of the class are given below:
Class name : ArmNum
Data members/instance variables:
n : to store the
number
l: to store the length of the number
Methods/Member functions:
ArmNum (int nn) : parameterized constructor to initialize the data member
n=nn Int sum_pow(int i) : returns the sum of
each digit raised to the power of the length of the number
using recursive technique eg. 34 will return 32 + 42 (as the length of the
number is 2) void isArmstrong( ) : checks whether
the given number is an Armstrong number by invoking the
function sum_pow( ) and displays the result with an appropriate message
Specify the class ArmNum giving details of the constructor( ), int
sum_pow(int) and void isArmstrong( ). Define a main( ) function to create an
object and call the functions accordingly to enable the task.
P a g e | 61
ALGORITHM:
• Step 1 – Start Make the parameterized constructor.
• Step 2 – Make the function „sum_pow‟ to find the sum of each digit raised
to the power of the length of the number using recursive technique.
• Step 4 – Make the main function and the call all the functions to find the
Armstrong number. End.
SOURCE CODE:
import java.util.Scanner;
public class ArmNum
{
int n,l;
ArmNum(int nn)
{
n=nn;
l=Integer.toString(n).length();
}
int sum_pow(int i)
{
if(i==0)
{
return 0;
}
else
{
return (int)Math.pow(i%10,l) + sum_pow(i/10);
}
}
void isArmstrong()
{
if(sum_pow(n)==n)
{
System.out.println(n + " is an Armstrong number");
}
else
{
System.out.println(n + "is not an Armstrong number");
}
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
int num=sc.nextInt();
ArmNum ob1=new ArmNum(num);
ob1.isArmstrong();
}
}
OUTPUT:
ALGORITHM:
• Step 3 – Make the function „void fillarray‟ to enter elements in the array.
• Step 6 –Make the function „show‟ to display the array elements in matrix
form.
• Step 7 – Make the main function and all the functions. End
SOURCE CODE:
import java.util.*;
class MatRev {
int arr[][], m, n; static Scanner x = new
Scanner(System.in);
void fillarray() {
System.out.println("Enter the elements");
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
arr[i][j] = x.nextInt();
}
int reverse(int x) {
int s = 0, c = 0;
while (x != 0)
{ c = x % 10;
s = s * 10 + c; x
= x / 10;
}
return s;
}
}
}
OUTPUT:
PROGRAM 12
A class Rearrange has been defined to modify a word by bringing all the vowels
in the word at the beginning followed by the consonants.
Example: ORIGINAL becomes OIIARGNL Some of the members of the class are
given below:
Class name : Rearrange
Data member/instance
variable:
wrd : to store a word
newwrd : to store the rearranged word
Member functions/methods:
Rearrange( ) : default constructor.
void readword( ) : to accept the word in UPPER case.
void freq_vow_con( ) : finds the frequency of vowels and consonants in the word
and displays them with an appropriate message.
void arrange( ) : rearranges the word by bringing the vowels at the
beginning followed by consonants. void display( ) : displays the original
word along with the rearranged word.
Specify the class Rearrange, giving the details of the constructor( ), void
readword( ), void freq_vow_con( ), void arrange( ) and void display( ). Define
the main( ) function to create an object and call the functions accordingly to
enable the task.
ALGORITHM:
Step 1 – Start; Initialize the instance variables. Step 2 – Make the default
constructor.
Step 3 – Make the function „readword‟ to accept the word in UPPER case.
Step 4 – Make the function „freq_vow_con‟ to find the frequency of vowels and
consonants in the word and displays them with an appropriate message.
Step 5 – Make the function „arrange‟ to rearrange the word by bringing the
vowels at the beginning followed by consonants.
Step 6 – Make the function „display‟ to display the original word along with the
rearranged word.
Step 7 – Make the main function and call all the functions. End.
SOURCE CODE:
import java.util.*;
class Rearrange
{
String wrd,newwrd;
static Scanner x=new Scanner(System.in);
Rearrange()
{
}
void readword()
{
System.out.println("Enter a word" );
wrd=x.next();
wrd=wrd.toUpperCase();
}
void freq_vow_con()
{
int s=0,s1=0; char ch;
for(int i=0;i<wrd.length();i++)
{
ch=wrd.charAt(i); if("AEIOU".indexOf(ch)!
=-1)
s++;
}
s1= wrd.length()-s;
System.out.println("vowels = "+ s);
System.out.println("consonants = " + s1);
}
void arrange()
{
char ch;
String p="",q="";
for(int i=0;i<wrd.length();i++)
{
ch=wrd.charAt(i);
if("AEIOU".indexOf(ch)!=-1)
p +=ch; else
q +=ch;
}
newwrd= p+q;
}
void display()
{
System.out.println("Original word = "+ wrd);
System.out.println("Rearranged word = "+ newwrd);
}
public static void main(String args[])
{
Rearrange obj=new Rearrange();
obj.readword();
obj.freq_vow_con(); obj.arrange();
obj.display();
}
}
OUTPUT:
PROGRAM 13
ALGORITHM:
• Step 1 – Entering the range.
• Step 2 – Getting the reverse of prime number and squaring both.
• Step 3 – Checking if both the squares are reverse of each other.
SOURCE CODE:
import java.util.*;
class Prime_Adam
{
public static void main(String[] args)
{
//PRIME ADAM NUMBER
Scanner sc = new Scanner(System.in);
System.out.print("m : ");
int m=sc.nextInt();
System.out.print("n : ");
int n=sc.nextInt();
System.out.println ("THE PRIME-ADAM INTEGERS ARE :");
int c=0;
if(m>n)
{
System.out.println ("INVALID INPUT");
} else { for (int i =
m; i <= n; i++) { if
(prime(i))
//prime number condition
{
if ((i * i) == reverse(reverse(i) * reverse(i)))
//Adam number condition
{
System.out.print(i + " ");
c++;
}
}
}
}
if(c==0)
{
System.out.println ("\nNIL");
System.out.println ("\nFREQUENCY OF PRIME-ADAM
INTEGERS IS : "+c);
}
}
//prime function return boolean
static boolean prime(int n)
{
int c=0; for(int i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)return true;
return false;
}
//reverse function returns integer
public static int reverse(int n)
{
int rev=0; while(n!=0)
{
int d=n%10; rev=rev*10+d; n=n/10;
}
return rev;
}
OUTPUT:
PROGRAM 14
Write a program to declare a matrix A[][] of order (M x N) where 'M' is the
number of rows and 'N' is the number of columns such that the value of 'M'
must be greater than 0 and less than 10 and the value of 'N' must be greater
than 2 and less than 6. Allow the user to input digits (0 - 7) only at each
location, such that each row represents an octal number.
Test your program for the following data and some random data
Example 1:
INPUT:
M =1
N= 3
ENTER ELEMENTS FOR ROW 1: 1 4 4
OUTPUT:
FILLED MATRIX DECIMAL EQUIVALENT
1 4 4 100
return;
}
OUTPUT:
2023-23| SANCHITA SRIVASTAVA
PROGRAM 15
Write a program to accept a sentence which may be terminated by either '.', '?' or '!'
only. The words are to be separated by a single blank space and are in UPPER CASE.
Perform the following tasks:
1. Check for the validity of the accepted sentence only for the terminating
character.
2. Arrange the words in ascending order of their length. If two or more words have
the same length, then sort them alphabetically.
3. Display the original sentence along with the converted sentence.
Test your program for the following data and some random data:
Example 1:
INPUT:
AS YOU SOW SO SHALL YOU REAP.
OUTPUT:
AS YOU SOW SO SHALL YOU REAP. AS SO SOW YOU YOU REAP SHALL
ALGORITHM:
• Step 1 – Entering the sentence in UPPERCASE.
• Step 2 – Checking validity of sentence
• Step 3 – Arranging words in ascending order.
SOURCE CODE:
import java.util.*;
public class StringCheck
{
public static String sortString(String ipStr)
{
St
ri
ng
OUTPUT :
Specify the class Convert giving details of the constructor( ),void accept( ),
void day_to_date( ) and voiddisplay( ). Define a main( ) function to create an
object and call the functions accordingly.
ALGORITHM:
• Step 1 – Start, Initialize the instance variables.
• Step 2 – Make the default constructor.
• Step 3 – Make the function “accept” to accept the day number and the
year.
SOURCE CODE:
import java.util.*;
class Convert
{
int n,d,m,y;
Convert( )
{
n=0;
y=0;
}
void accept()
{
Scanner x=new Scanner(System.in);
System.out.println(("Enter day number and year"));
n=x.nextInt() ;
y=x.nextInt() ;
}
void day_to_date()
{
int a[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
if(y%4==0)
a[2]=29;
int s=0, c=0;
while(s<n)
s=s+a[c++];
s=s-a[--c];
d=n-s;
m=c;
}
void display()
{
String x[]={"","JANUARY","FEBRUARY","MARCH","APRIL","MAY",
"JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","
DECEMBER"};
System.out.print("\n Day Number: " + n);
System.out.print("\n Date: " );
System.out.print(x[m]+" " +d + "," + y);
}
public static void main(String args[])
{
Convert obj =new Convert();
obj.accept( ) ;
obj.day_to_date();
obj.display();
}
}
OUTPUT:
PROGRAM 17
Design a class BinSearch to search for a particular value in an array.
ALGORITHM:
• Step 1 – Start, Initialize the instance variable.
• Step 2 – Make the parameterized constructor.
• Step 4 – Make the function “sort” to sort the array elements in ascending
order using any standard sorting technique.
• Step 5 – Make the function “bin_search” to search for the value “v” using
binary search and
recursive technique and returns its location if found otherwise returns
-1.
SOURCE CODE:
import java.util.*;
class BinSearch
{ int
arr[];
int n;
static Scanner x=new Scanner(System.in);
BinSearch(int nn)
{
n=nn;
}
void fillarray()
{
arr=new int[n];
System.out.println("Enter "+n + " elements");
for(int i =0;i<n;i++) arr[i]=x.nextInt();
}
void sort()
{
int t;
for(int i=0;i<n-1;i++)
for(int j =0;j<n-1-i;j++)
{
if (arr[j]>arr[j+1])
{
t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
}
int bin_search(int l,int u, int v )
{
int m=(l+u)/2; if(arr[m]==v)
return m; else if(l>u)
return -1; else if (arr[m]>v)
return bin_search(l,m-1,v); else
return bin_search(m+1,u,v);
}
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
obj.fillarray();
obj.sort();
System.out.println("Enter the number to be searched"); int
vvv=sc.nextInt();
System.out.println(" location: " + obj.bin_search(0,4,vvv) );
}
}
Temporary variable.
t int
i int For the loop.
j int For the loop.
Local variable for the
l int function.
To store the
dim int dimension of the
array.
To store the search
searchNum int
OUTPUT:
PROGRAM 18
A class Mix has been defined to mix two words, character by character, in the
following manner: The first character of the first word is followed by the first
character of the second word and so on.
If the words are of different length, the remaining characters of the longer word
are put at the end.
Example: If the First word is “JUMP” and the second word is “STROLL”, then
the required word will be “JSUTMRPOLL”.
Some of the members of the class are given below:
Classname : Mix
Data member/instance variable:
wrd : to store a word
len : to store the length of the word
Member functions/methods:
Mix( ) : default constructor to initialize the data members with legal
initial values. void feedword( ) : to accept the word in UPPER case.
void mix_word( Mix P, Mix Q ) : mixes the words of objects P and Q as stated
above and stores the resultant word in the current object. void display( ) :
displays the word
Specify the class Mix giving the details of the constructor( ), void feedword( ),
void mix_word( Mix, Mix ) and void display( ). Define the main( ) function to
create objects and call the functions.
ALGORITHM:
• Step 6 – Make the main function to call the functions to enable the task.
End.
SOURCE CODE:
import java.util.*; class
Mix
{
String wrd;
int len;
static Scanner x=new Scanner(System.in);
Mix()
{
wrd="";
len=0;
}
void feedword()
{
System.out.println( "Enter a word in UPPER CASE");
wrd=x.next(); len=wrd.length();
}
void mix_word(Mix P,Mix Q)
{
int s=(P.len <Q.len)? P.len:Q.len; for(int
i=0;i<s;i++) wrd += P.wrd.charAt(i)
+""+Q.wrd.charAt(i); if (P.len > Q.len)
wrd +=P.wrd.substring(Q.len); else
wrd +=Q.wrd.substring(P.len);
}
void display()
{
System.out.println("WORD = " + wrd);
}
public static void main(String args[])
{
Mix obj=new Mix();
Mix obj1=new Mix();
Mix obj2= new Mix();
obj.feedword();
obj1.feedword();
obj2.mix_word (obj,obj1);
obj2.display();
}
OUTPUT:
PROGRAM 19
A Fascinating number is one which when multiplied by 2 and 3 and then , after
the results are concatenated with the original number , the new number contains
all the digits from 1 to 9 exactly once . There can be any number of zero’s and
are to ignored.
Accept Two positive integers m and n where must be less than n and the value of
both ‘m’ and ‘n’ must be grater than 99 and less than 10000 as user input.
Display all the fascinating numbers that are in range between m and n(both
inclusive) and output them along with the frequency.
ALGORITHM:
• Step 1- First, check the given number consist of three digits or not. If no,
print cannot be a fascinating number.
• Step 2- Else, multiply the given number by 2 and 3, separately.
• Step 3- Convert the results (from step 2) into a string.
• Step 4- Concatenate the strings (from step 3) with the given number (n).
• Step 5- Iterate over the string that we get after concatenation and count the
frequency of each digit.
• Step 6- Print "not a fascinating number" if any digit is missing or appeared
multiple times. Else, print "fascinating number".
SOURCE CODE:
import java.util.*; public
class Fascinating
{
public static void main(String[] args)
int n=sc.nextInt();
int temp=m;
m=n; n=m;
i=m;i<=n;i++)
if(fascinating(i))
System.out.println ();
m3 = n*3;
String s=Integer.toString(n)+Integer.toString(m2)+Integer.toString(m3);
int l = s.length(); long user = Long.parseLong(s); for(int i=1;i<10;i++)
int c=0;
long num=user;
for(int j=0;j<l;j++)
if(c>1) return
false; else
if(c==0) return
false;
return true;
VARIABLE DESCRIPTION
TABLE:
OUTPUT:
PROGRAM 20
Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’
or ‘!’ only. The words are to be separated by a single blank space and are
UPPERCASE.
Display both the sentences along with the common words and their frequency.
ALGORITHM:
• Step 1 – Entering the sentence and checking if it ends with ‘.’, ‘?’ or ‘!’.
SOURCE CODE:
import java.util.*;
class CommonWrd
{
public static void main(String args[])
{ String x=""; int
h=0,z=0;
Scanner sc= new Scanner(System.in);
System.out.println("Enter para");
String n=sc.nextLine();
String a[]=new String[1000];
int l=n.length();
for(int i=0;i<l;i++)
{
char ch=n.charAt(i);
if(ch=='.'||ch=='?'||ch=='!')
{
z++;
}
}
if(z==2)
{
for(int i=0;i<l;i++)
{
char ch=n.charAt(i);
if(ch=='.'||ch=='?'||ch=='!')
{
String p=(n.substring(0,i+1));
String m=(n.substring(i+2,l)); n=p+m;
System.out.println(n.substring(0,i+1));
System.out.println(n.substring(i+1)); break;
}
}
for(int i=0;i<l-1;i++)
{
char ch=n.charAt(i); if(ch!='.'&&ch!='?'&&ch!='!'&&ch!=' ')
{
x=x+ch;
}
else
{
a[h]=x; h+
+; x="";
}
}
System.out.println("COMMON WORDS FREQUENCY"); for(int
i=0;i<h;i++)
{
int c=1;
for(int j=i+1;j<h;j++)
{
if(a[i].equals(a[j]))
{
for(int k=j;k<h-1;k++)
a[k]=a[k+1];
h--;
c++;
}
}
if(c>1)
System.out.println(a[i]+"\t\t"+c);
}
}
else
{
System.out.print("INVALID INPUT");
}
}
}
OUTPUT:
PROGRAM 21
a) Sort the matrix elements in descending order using any standard sorting
technique
b) Calculate the sum of the boundary elements of the matrix before sorting and
after sorting.
c) Display the original matrix and the sorted matrix along with the sum of their
boundary elements respectively
ALGORITHM:
• Step 1 – Entering the size of matrix and its elements
• Step 2 – Getting boundary elements after sorting and before sorting and
adding them by loop
• Step 3 – Displaying original and sorted matrix with their sum of boundary
elements
SOURCE CODE:
import java.util.*;
class Sum_Of_Boundary
{
{
int arr[] = new int [a*b],k=0;
//CONVERTTING MATRIX TO LINEAR ARRAY
for(int i=0;i<a;i++)
{
for(int j=0;j<b;j++)
{
arr[k]=mat[i][j];
k++;
}
}
//SORTING
for(int i=0; i<a*b; i++)
{
for( int j=0; j<a*b-1; j++ )
{
if(arr[j]<arr[j+1])
{
int copy = arr[j];
arr[j]=arr[j+1];
arr[j+1] = copy;
}
}
}
//COVERTING LINEAR ARRAY TO MATRIX
k=0;
for(int i=0;i<a;i++)
{
for(int j=0;j<b;j++)
{
mat[i][j]=arr[k]; k++;
}
}
}
}
VARIABLE DESCRIPTION TABLE:
OUTPUT:
PROGRAM 22
An Evil No. is a positive no. which has even no. of 1’s in its binary equivalent.
Example: Binary equivalent of 15 is 111, which contains even no. of 1’s.
Design a program to accept a positive whole no. and find the binary equivalent
of the no. and count the no. of 1’s in it and display whether it is an evil no. or not
with an appropriate message.
ALGORITHM:
• We first take a number.
• We then find the binary equivalent of this number and store it into another
variable.
• We find the total number of ones in the binary number.
• If we found an even number of ones in the binary equivalent number, then
the number is an evil number. Else the given number is not an evil number.
SOURCE CODE:
import java.util.Scanner;
int count = 0;
int p = 0;
int binNum = 0;
while (n > 0) {
int d = n % 2;
if (d == 1)
count++;
binNum += (int)(d * Math.pow(10, p ));
p ++;
n /= 2;
}
if (count % 2 == 0)
System.out.println("Output: Evil Number");
else
System.out.println("Output: Not an Evil Number");
}
}
VARIABLE DESCRIPTION
TABLE:
OUTPUT:
PROGRAM 23
ALGORITHM:
• We create a merge method that takes two sorted arrays arr1 and arr2 as input
and returns the merged array in ascending order.
• We initialize three indices: i for arr1, j for arr2, and k for the merged array.
• We iterate through both input arrays, comparing elements at indices i and j.
• We add the smaller element to the merged array and increment the respective
indices.
• After the first while loop, if any elements are remaining in arr1 or arr2, we
copy them to the merged array.
• Finally, we return the merged array.
SOURCE CODE:
public class MergeArray
{
PROGRAM 24
ALGORITHM:
• Initialize the constructor.
• Accept the word in UPPER case.
• Remove the repeated alphabet from the word and store the modified word.
• Display the original word along with the modified word.
• End.
SOURCE CODE:
import java.util.*;
class repeat
{
String str,newstr;
{ int
f=0;
for(int j=0;j<len;j++)
{
char ch=str.charAt(j);
if(ch==(char)i)
f++;
}
if(f==1)
newstr=newstr+(char)i;
}
}
void show()
{
System.out.println("Original word="+str);
System.out.println("Modified word="+newstr);
}
public static void main(String args[])
{
repeat ob=new repeat();
ob.readword();
ob.modify();
ob.show();
}
}
OUTPUT:
PROGRAM 25
A composite Magic number is a positive integer which is composite as well as
magic number. Composite number: A composite number is a number which
has more than two factors.
For example:
Factors of 12 are 1,2,3 ,4 ,6,12
Magic number: A Magic number is a number in which the eventual sum of the
digits is equal to 1.For example: 64: =6+4=10= 1+0=1
Accept two positive integers ‘m’ and ‘n’, where m is less than n. Display all
composite magic numbers that are in the range between m and n (both
inclusive and where m<n) and output them along with frequency, in the
format specified below:
Test your program for the following data and some random data.
Example 1:
INPUT m=10
n=100
OUTPUT:
The composite magic numbers are 10, 28, 46, 55, 64, 82, 91, 100
Frequency of composite magic numbers: 8
ALGORITHM:
• Define a function to check if a number is composite.
• Define a function to calculate the sum of digits of a number.
• Define a function to check if a number is a magic number.
• Define the main function.
• Take input for the lower and upper limits.
• Iterate over the range of numbers from the lower to the upper limit.
• Check if the number is composite and magic.
• Print the composite magic numbers and their frequency.
SOURCE CODE:
import java.util.Scanner;
System.out.print("Enter n: ");
int n = in.nextInt();
if (isComposite && i != 1) {
int num = i;
while (num > 9) { int
sum = 0; while (num !
= 0) { int d = num
% 10; num /= 10;
sum += d;
}
num = sum;
if (num == 1) {
count++;
System.out.print(i + " ");
}
}
}
System.out.println();
System.out.println("Frequency of composite magic numbers: " + count);
}
}
OUTPUT:
PROGRAM 26
Write a program to accept a sentence which may be terminated by full stop(.)
only. The words are to be separated by single blank space. Print an error
message if the sentence does not end with full stop. Perform the following tasks:
a) Convert first letter of each word to uppercase.
b) Find the vowel and consonants in each word and display them with proper
headings along with the words.
ALGORITHM:
• Accept a sentence.
• Check if it ends with a full stop.
• Convert the first letter of each word to uppercase.
• Then count and display the number of vowels and consonants in each word.
• If the sentence does not end with a full stop, it displays an error message.
SOURCE CODE:
import java.util.Scanner;
// Remove the full stop and split the sentence into words. String[]
words = inputSentence.substring(0, inputSentence.length() - 1).split(" ");
if (isVowel(c))
{ vowelCount++;
} else if (Character.isLetter(c))
{ consonantCount++;
}
}
// Print the word along with vowel and consonant counts.
System.out.println("Word: " + capitalizedWord);
System.out.println("Vowels: " + vowelCount);
System.out.println("Consonants: " + consonantCount);
System.out.println();
}
}
OUTPUT:
PROGRAM 27
Write a program to declare a matrix A [ ] [ ] of order (M x N) where ‘M’ is
the number of rows and ‘N’ is the number of columns such that both M and
N must be greater than 2 and less than 10 and M is equal to N. Allow the
user to input integers into this matrix. Perform the following task on the
matrix. o Display the input matrix. o Find the maximum and minimum
value of matrix and display them along with their index.
o Find and display sum of left diagonal elements of an array.
ALGORITHM:
• Enter the size of the square matrix (M x N, where M = N).
• Input the matrix elements.
• Display the input matrix.
• Find and display the maximum and minimum values along with their indices.
• Calculate and display the sum of left diagonal elements.
SOURCE CODE:
import java.util.Scanner; public
class MatrixOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the size of the matrix
int M, N; do {
System.out.print("Enter the number of rows and columns (M x
N, M=N): ");
M = scanner.nextInt();
N = scanner.nextInt();
} while (M < 3 || M > 9 || N < 3 || N > 9 || M != N);
// Declare the matrix
int[][] A = new int[M][N];
}
}
scanner.close();
}
}
}
PROGRAM 28
Design a class NumDude to check if a given number is a Dudeney number or
not. (A Dudeney number is a positive integer that is a perfect cube, such that the
sum of its digits is equal to the cube root of the number.) Example: 5832 = (5 + 8
+ 3 + 2)3 = (18)3 = 5832 Some of the members of
the class are given below:
Class name : NumDude
Data member/instance/variable:
num : to store a positive integer number
Methods/Member functions:
NumDude() : default constructor to initialise the data member with legal initial
value void input() : to accept a positive integer number
int sumDigits(int x) : returns the sum of the digits of number ‘x’ using recursive
technique void is Dude() : checks whether the given number is a
Dudeney number by invoking the function sumDigits() and displays the result
with an appropriate message.
Specify the class NumDude giving details of the constructor(), void input(), int
sumDigits(int) and void is Dude(). Define a main() function to create an object
and call the functions accordingly to enable the task.
ALGORITHM:
1. Create a classNumDude with a private instance
variable num to store a positive integer number.
2. NumDude() that
initializes num to a legal initial value, which is 0
Implement a default
in this case. constructor
3. Implement the method to accept a positive num
SOURCE CODE:
import java.util.Scanner;
class NumDude {
private int num; public
NumDude() { num = 0;
}
public void input() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: "); num
= scanner.nextInt(); scanner.close();
}
private int sumDigits(int x) {
if (x == 0) {
return 0;
}
OUTPUT:
PROGRAM 29
A class Trans is defined to find the transpose of a square matrix. A transpose of a
matrix is obtained by interchanging the elements of the rows and columns. Some
of the members of the class are given below:
Class name : Trans
Data members/instance variable:
ALGORITHM
• Create a class called "Trans" with data members:
- arr[][] to store integers in the matrix
- m to store the size of the matrix
• Define a parameterized constructor "Trans(int mm)" within the class:
- Initialize m with mm.
- Create a 2D array arr with dimensions m x m.
• Define a method "fillarray()" to input elements into the matrix:
- Use nested loops to input elements into the matrix.
• Define a method "transpose()" to calculate and update the transpose:
- Create a new 2D array transposedArr with dimensions m x m.
- Calculate the transpose of the matrix by swapping rows and columns.
SOURCE CODE:
import java.util.Scanner;
class Trans { private int[]
[] arr; private int m;
public Trans(int mm) {
m = mm;
arr = new int[m][m];
}
public void fillarray() {
Scanner input = new Scanner(System.in);
System.out.println("Enter elements of the matrix:");
for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) {
arr[i][j] = input.nextInt();
}
}
}
public void transpose() { int[][]
transposedArr = new int[m][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
transposedArr[i][j] = arr[j][i];
}
}
arr = transposedArr;
}
public void display() {
System.out.println("Original Matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
transpose();
System.out.println("Transposed Matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
OUTPUT:
PROGRAM 30
A class SortAlpha has been defined to sort the words in the sentence in
alphabetical order. Example: Input: THE SKY IS BLUE Output: BLUE IS SKY
THE Some of the members of the class are given below: Class name : SortAlpha
Data members/instance variable: sent : to store a sentence n : integer to store the
number of words in a sentence Methods/Member functions: SortAlpha() :
default constructor to initialise data members with legal initial value void
acceptsent() : to accept a sentence in UPPER CASE void sort(SortAlpha P) :
sorts the words of the sentence of object P in alphabetical order and stores the
sorted sentence in the current object void display() :
display the original sentence along with the sorted sentence by invoking the
method sort() Specify the class SortAlpha giving details of the constructor(),
ALGORITHM:
• The SortAlpha class has data members sent to store the input sentence
and n to store the number of words.
• The default constructor SortAlpha() initializes these data members with
legal initial values (empty string and 0).
• The acceptsent() method allows the user to input a sentence in uppercase
and counts the number of words in it.
• The sort(SortAlpha P) method takes another SortAlpha object P, splits
its sent into words, sorts them alphabetically, and stores the result in the
current object's sent member.
• The display() method displays both the original and sorted sentences by
invoking the sort() method.
• The main() function creates an instance of SortAlpha, accepts the
sentence, and displays both the original and sorted sentences.
SOURCE CODE:
import java.util.Arrays;
import java.util.Scanner;
class SortAlpha1
{ private String sent;
private int n; public
SortAlpha1() { sent =
"";
n = 0;
}
uppercase.
n int Stores the number of words
in the sentence.
OUTPUT: