0% found this document useful (0 votes)
2 views124 pages

Comp Project

The document contains multiple Java programs that demonstrate various algorithms including finding Narcissistic numbers, checking for Smith numbers, identifying Mystery numbers, converting day numbers to dates, checking for palindrome sentences, and calculating keystrokes for text input. Each section includes an algorithm and source code for implementation. The programs cover a range of mathematical and string manipulation concepts.

Uploaded by

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

Comp Project

The document contains multiple Java programs that demonstrate various algorithms including finding Narcissistic numbers, checking for Smith numbers, identifying Mystery numbers, converting day numbers to dates, checking for palindrome sentences, and calculating keystrokes for text input. Each section includes an algorithm and source code for implementation. The programs cover a range of mathematical and string manipulation concepts.

Uploaded by

nithyaanandraj03
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

[Link] Number.

Write a program to accept the range of numbers M and N. Display the Narcissistic
numbers within that range. A narcissistic number is a number that is equal to the
sum of its own digits, each raised to the power of the total number of digits in the
number
ALGORITHM:
STEP 1: Start
STEP 2: Input two integers M and N
STEP 3: For each number i from M to N,do:
Set t=i , d=0;
Count Digits:
While t>0
Increment d
Divide t=t/10
Set t=i , s=0
Find sum of powers:
While t>0
Digits =t%10
s=s+(digit^ d)
s==i
Print i
STEP 4: End loop
STEP 5: Stop
SOURCE CODE:
import [Link].*;
public class Narcissistic
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
// Accept range
[Link]("Enter M: ");
int M = [Link]();
[Link]("Enter N: ");
int N = [Link]();
[Link]("Narcissistic Numbers:");
for (int i= M; i <= N; i++)
{
int t = i;
int d = 0;
// Count d
while (t > 0)
{
d++;
t /= 10;
}
int s = 0;
t = i;
// Calculate s of d raised to power
while (t > 0)
{
int digit = t % 10;
s+= [Link](digit, d);
t=t/10;
}
// Check condition
if (s == i)
{
[Link](i);
}
}
}
OUTPUT:

[Link] Number
A Smith number is a composite number, whose sum of the digits is equal to the sum
of its prime factors. For example:4, 22, 27, 58, 85, 94, 121 ………. are Smith
numbers. Write a program in Java to enter a number and check whether it is a Smith
number or not.
ALGORITHM:

Step 1: Start

Step 2: Input a number num

Step 3: Store the number in a variable temp

Step 4: Initialize c1 = 0

Step 5: For i = 1 to num


If num % i == 0, then increment c1

Step 6: If c1 ≤ 2, then
Print "Not a Smith Number" and go to Step 12

Step 7: Initialize sd = 0, t = temp

Step 8: While t > 0


Find remainder r = t % 10
Add to sum sd = sd + r
Update t = t / 10

Step 9: Initialize sf = 0, n = num

Step 10: For i = 2 to n


While n % i == 0
Initialize c2 = 0
For j = 1 to i
If i % j == 0, increment c2
If c2 == 2 (i is prime)
Find sum of digits of i and add to sf
Divide n = n / i
Step 11: If sd == sf
Print "Smith Number"
Else
Print "Not a Smith Number"

Step 12: Stop

SOURCE CODE:
import [Link].*;
public class smith
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
int num, c1 = 0, c2 = 0, sf = 0, sd = 0, r;
[Link]("Enter a number : ");
num = [Link]();
int temp = num;
// Check composite
for(int i = 1; i <= num; i++)
{
if(num % i == 0)
c1++;
}
if(c1 > 2)
{
int n = num;
for(int i = 2; i <= n; i++)
{
while(n % i == 0)
{
c2 = 0;
for(int j = 1; j <= i; j++)
{
if(i % j == 0)
c2++;
}
if(c2 == 2) // prime factor
{
int tf = i;
while(tf > 0)
{
r = tf % 10;
sf = sf + r;
tf = tf / 10;
}
}
n = n / i;
}
}
// Sum of digits of number
int t = temp;
while(t > 0)
{
r = t % 10;
sd = sd + r;
t = t / 10;
}
if(sd == sf)
[Link](temp + " is a Smith number");
else
[Link](temp + " is not a Smith number");
}
else
{
[Link](num + " is not a Smith Number");
}
}
}

OUTPUT:
[Link] Number
A mystery number is a number that can be expressed as the sum of two numbers
and those two numbers should be the reverse of each other.
ALGORITHM:
STEP 1: Start
STEP 2: Input n
STEP 3: For i = 1 to n
STEP 4: Find reverse of i ,rev
STEP 5: If i + rev == n then print pair, stop
STEP 6: If no pair found then not a mystery number
STEP 7: End

SOURCE CODE:
import [Link].*;
public class MysteryNumber
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
int n, i, t, rev, digit;
int c = 0;
[Link]("Enter number: ");
n = [Link]();
for (i = 1; i < n; i++)
{
t = i;
rev = 0;
while (t > 0)
{
digit = t % 10;
rev = rev * 10 + digit;
t = t / 10;
}
if (i + rev == n)
{
[Link]("Mystery Number");
c = 1;
break;
}
}
if (c == 0)
[Link]("Not a Mystery Number");
}
}
OUTPUT:
[Link] Number

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.

ALGORITHM:
STEP 1: Start

STEP 2: Input dayNo, year, N

STEP 3: If invalid → print error, stop

STEP 4: Check leap year

STEP 5: Set days in months (Feb = 28/29)

STEP 6: Convert dayNo → date

While dayNo > days[month]

dayNo = dayNo - days[month]

month++

STEP 7: Print date

STEP 8: Add N to date

STEP 9: While date > days[month]

date = date - days[month]


month++

If month > 12 → month = 1, year++

STEP 10: Print future date

STEP 11: End

SOURCE CODE:

import [Link].*;

public class DayToDate

public static void main(String[] args)

Scanner sc = new Scanner([Link]);

int dayNo, year, N;

[Link]("Enter day number: ");

dayNo = [Link]();

[Link]("Enter year: ");

year = [Link]();

[Link]("Enter N: ");

N = [Link]();

if (year < 1000 || year > 9999 || dayNo < 1 || dayNo > 366 || N < 1 || N > 100)

[Link]("Invalid Input");

return;
}

int days[] = {31,28,31,30,31,30,31,31,30,31,30,31};

// Leap year check

if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))

days[1] = 29;

int month = 0;

int d = dayNo;

while (d > days[month])

d = d - days[month];

month++;

int date = d;

month = month + 1;

[Link]("Date: " + date + "/" + month + "/" + year);

// Add N days

date = date + N;

while (date > days[month - 1])

date = date - days[month - 1];


month++;

if (month > 12)

month = 1;

year++;

// update leap year

if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))

days[1] = 29;

else

days[1] = 28;

[Link]("Future Date: " + date + "/" + month + "/" + year);

OUTPUT:
[Link]
Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or
‘!’ only. The words may be separated by a single blank space and should be case-
insensitive.
Perform the following tasks: (a) Check if the sentence is a Palindrome Sentence. A
sentence is a Palindrome Sentence if, after removing the spaces and punctuation,
the letters read the same forward and backward. Example: “Never odd or even.” (b)
Display the first-occurring most frequent word in the sentence (in lowercase). If
there is a tie, choose the word that appears first in the sentence and if no words are
repeated then print NONE.

ALGORITHM:

Step 1: Start

Step 2: Declare the required string variables, array, and integer variables

Step 3: Create a Scanner object

Step 4: Accept a sentence from the user

Step 5: If the last character of the sentence is not '.', '!' or '?', then display
"INVALID INPUT" and terminate the program

Step 6: For each character in the sentence, check whether it is a space

Step 7: If the character is not a space, add it to the string st

Step 8: For each character in the sentence, check whether it is a space

Step 9: If the character is not a space, add it in reverse order to the string s1

Step 10: If st and s1 are equal ignoring case, display that the sentence is a
palindrome

Step 11: Else display that the sentence is not a palindrome

Step 12: For each character in the sentence, check whether it is a space

Step 13: If the character is not a space, add it to temporary string t

Step 14: Else store the word t into the array and reset t to empty

Step 15: For each word in the array, compare it with the remaining words in the
array

Step 16: If two words are equal ignoring case, increase the frequency count
Step 17: If the frequency count is greater than the maximum frequency, store that
word as the most frequent word

Step 18: If no word is repeated, store "NONE" as the result

Step 19: Display the most frequent word

Step 20: Stop

SOURCE CODE:
import [Link].*;
public class sentence
{
public static void main(String[] args)
{
// prepare variables for sentence processing
String st=""; // sentence without spaces for palindrome check
String s1=""; // reversed sentence without spaces
String t="";
String a[] = new String[100]; // array to store words
String maxword=""; // most frequent word output
int max=0,f=0,k=0; //max freq, current freq, number of words

Scanner sc = new Scanner([Link]);


[Link]("Enter a sentence:");
String s = [Link]();
// validate that sentence ends with punctuation
if([Link]([Link]() - 1)!=('.') && [Link]([Link]() - 1)!=('!') &&
[Link]([Link]() - 1)!=('?'))
{
[Link]("INVALID INPUT.");
[Link](0);
}

//to create string without spaces for palindrome comparison


for(int i=0; i<[Link]()-1; i++)
{
if([Link](i)!=' ')
{
st = st + [Link](i);
}
}
// to create reversed string without spaces for palindrome comparison
for(int i=0; i<[Link]()-1; i++)
{
if([Link](i)!=' ')
{
s1 = [Link](i) + s1;
}
}
// check palindrome result
if([Link](s1))
{
[Link]("The sentence is a palindrome.");
}
else
{
[Link]("The sentence is not a palindrome.");
}
// split the sentence into words and store each word in the array
for(int i=0; i<[Link]()-1; i++)
{
if([Link](i)!=' ')
{
t=t+[Link](i);
}
else
{
a[k]=t;
k++;
t="";
}
}

// determine the most frequent word from the collected words


for(int i=0; i<k; i++)
{
for(int j=i+1; j<k; j++)
{
if(a[i].equalsIgnoreCase(a[j]))
f++;
}
if(f>max)
{
max=f;
maxword=a[i];
}
}
if(f==0)
{
maxword="NONE";
}
[Link]("The most frequent word is: " + maxword);
}
}
OUTPUT:
[Link]
Most (not all) cell phone keypads look like the following arrangement (the letters
are above the respective number):
For sending text/SMS, the common problem is the number of keystrokes to type a
particular text.
For example, in the word “STOP”, there are a total of 9 keystrokes needed to type
the word. You need to press the key 7 four times, the key 8 once, the key 6 three
times and the key 7 once to get it.
Develop a program code to find the number of keystrokes needed to type the text.
For this problem, accept just one word without any punctuation marks, numbers or
whitespaces and the text message would consist of just 1 word.
ALGORITHM:

Step 1: Start

Step 2: Declare integer variable s and initialize it to 0

Step 3: Create a Scanner object

Step 4: Display a message to enter a word

Step 5: Accept the word from the user

Step 6: Repeat the process for each character of the word

Step 7: Store the current character in variable ch

Step 8: Check whether ch belongs to the group A, B, or C

Step 9: If ch is A or a, add 1 to s

Step 10: If ch is B or b, add 2 to s

Step 11: If ch is C or c, add 3 to s

Step 12: Check whether ch belongs to the group D, E, or F


Step 13: Add the corresponding keystroke value to s

Step 14: Check whether ch belongs to the group G, H, or I

Step 15: Add the corresponding keystroke value to s

Step 16: Continue the same process for all remaining alphabet groups

Step 17: Repeat the steps until all characters are checked

Step 18: Display the total number of keystrokes

Step 19: Stop

SOURCE CODE:

import [Link].*;

public class Keystrokes

public static void main(String[] args)

// total keystroke count

int s=0;

// read the input word

Scanner sc = new Scanner([Link]);

[Link]("Enter a word");

String word = [Link]();


// count keystrokes for each character

for(int i=0; i<[Link](); i++)

char ch = [Link](i);

if(ch=='A' || ch=='B' || ch=='C' || ch=='a' || ch=='b' || ch=='c')

if(ch=='A'||ch=='a')

s=s+1;

else if(ch=='B'||ch=='b')

s=s+2;

else

s=s+3;

if(ch=='D' || ch=='E' || ch=='F' || ch=='d' || ch=='e' || ch=='f')

if(ch=='D'||ch=='d')

s=s+1;

else if(ch=='E'||ch=='e')

s=s+2;

else

s=s+3;

}
if(ch=='G' || ch=='H' || ch=='I' || ch=='g' || ch=='h' || ch=='i')

if(ch=='G'||ch=='g')

s=s+1;

else if(ch=='H'||ch=='h')

s=s+2;

else

s=s+3;

if(ch=='J' || ch=='K' || ch=='L' || ch=='j' || ch=='k' || ch=='l')

if(ch=='J'||ch=='j')

s=s+1;

else if(ch=='K' || ch=='k')

s=s+2;

else

s=s+3;

if(ch=='M' || ch=='N' || ch=='O' || ch=='m' || ch=='n' || ch=='o')

if(ch=='M'||ch=='m')

s=s+1;
else if(ch=='N'||ch=='n')

s=s+2;

else

s=s+3;

if(ch=='P' || ch=='Q' || ch=='R' || ch=='S' || ch=='p' || ch=='q' || ch=='r' ||


ch=='s')

if(ch=='P'||ch=='p')

s=s+1;

else if(ch=='Q' || ch=='q')

s=s+2;

else if(ch=='R'||ch=='r')

s=s+3;

else

s=s+4;

if(ch=='T' || ch=='U' || ch=='V' || ch=='t' || ch=='u' || ch=='v')

if(ch=='T'||ch=='t')

s=s+1;

else if(ch=='U'||ch=='u')
s=s+2;

else

s=s+3;

if(ch=='W' || ch=='X' || ch=='Y' || ch=='Z' || ch=='w' || ch=='x' || ch=='y' ||


ch=='z')

if(ch=='W'||ch=='w')

s=s+1;

else if(ch=='X'||ch=='x')

s=s+2;

else if(ch=='Y'||ch=='y')

s=s+3;

else

s=s+4;

[Link]("The total keystrokes is: " + s);

}}
OUTPUT:
[Link] IN STRING
Write a program to accept a sentence which may be terminated by either ‘.’ or ‘?’ or
‘!’ only. Any other character may be ignored. The words may be separated by more
than one blank space and are in uppercase.

Perform the following tasks: (a) Accept a sentence and remove all the extra blank
space between two words to a single blank space. (b) Accept any word from the
user along with its position and insert the word in the given position. The position is
calculated by place value of each word where first word is in

5|Page

position 1, second word in position 2 and so on. (c) Display the modified sentence.

ALGORITHM:

Step 1: Start

Step 2: Declare the required string and integer variables

Step 3: Create a Scanner object

Step 4: Accept a sentence from the user

Step 5: If the last character of the sentence is not '.', '!' or '?', display "INVALID
INPUT" and terminate the program

Step 6: Remove extra spaces from the sentence and store it in st

Step 7: Accept the word to be inserted from the user

Step 8: Accept the position value from the user

Step 9: Initialize the word counter variable k to 0

Step 10: For each character in the sentence, check whether the character is a space

Step 11: If the character is a space, increase the value of k by 1


Step 12: If k becomes equal to p-1, insert the new word at that position using
substring operation

Step 13: Break the loop after inserting the word

Step 14: Display the modified sentence

Step 15: Stop

SOURCE CODE:

import [Link].*;

public class Position

public static void main(String[] args)

// Create a scanner to read input from the user

Scanner sc = new Scanner([Link]);

// Read the sentence from the user

[Link]("Enter a Sentence:");

String s = [Link]();

int k = 0;

// Validate sentence terminator: only ., ? or ! are allowed


if([Link]([Link]() - 1) != '.' && [Link]([Link]() - 1) != '!' &&
[Link]([Link]() - 1) != '?')

[Link]("INVALID INPUT.");

[Link](0);

// Remove extra spaces so that only single spaces remain between words

String st = [Link]().replaceAll(" +", " ");

// Read the word and position to insert

[Link]("Enter a word to be inserted:");

String w = [Link]();

[Link]("Enter the position:");

int p = [Link]();

// Find the insertion point based on word count

for(int i = 0; i < [Link](); i++)

if([Link](i) == ' ')

k++;

if(k == p-1)

{
st = [Link](0, i + 1) + w + " " + [Link](i + 1);

break;

// Print the modified sentence

[Link]("Modified Sentence: " + st);

OUTPUT:
[Link] WORDS
Write a program to accept a sentence which may be terminated by either '.', '?' or '!'
[Link] words may be separated by more than one blank space and are in UPPER
CASE.

Perform the following tasks:

1. Find the number of words beginning and ending with a consonant.

2. Place the words which begin and end with a consonant at the beginning, followed
by the remaining words as they occur in the sentence.

ALGORITHM:

Consonants Algorithm

Step 1: Start
Step 2: Declare the required string and integer variables
Step 3: Create a Scanner object
Step 4: Accept a sentence from the user
Step 5: Remove extra spaces and convert the sentence into uppercase
Step 6: If the sentence does not end with '.', '!' or '?', display "INVALID INPUT"
and terminate the program
Step 7: For each character in the sentence, check whether it is a space
Step 8: If the character is not a space, add it to string s1
Step 9: If a space or the end of sentence is reached, process the word stored in s1
Step 10: If the word contains only one letter, check whether it is a vowel or
consonant
Step 11: If the word begins and ends with consonants, increase the count and add it
to string sc
Step 12: Else add the word to string sv
Step 13: Reset s1 to empty after processing each word
Step 14: Repeat the process until all words are checked
Step 15: Combine consonant words and remaining words into string sf
Step 16: Display the total number of consonant words
Step 17: Display the rearranged sentence
Step 18: Stop

SOURCE CODE:

import [Link].*;

public class Consonants

public static void main(String[] args)

// Create a scanner to read input from the user

Scanner in = new Scanner([Link]);

String s1="",sc="",sv="",sf="";

// Read the sentence from the user

[Link]("Enter a Sentence:");

String s = [Link]();

String ss=[Link]().replaceAll(" +", " ");

ss=[Link]();

int count = 0;

// Validate sentence terminator: only ., ? or ! are allowed

if([Link]([Link]() - 1) != '.' && [Link]([Link]() - 1) != '!' &&


[Link]([Link]() - 1) != '?')

{
[Link]("INVALID INPUT.");

[Link](0);

// Count the number of consonants beginning and ending

for(int i = 0; i < [Link]()-1; i++)

if([Link](i)!=' ')

s1=s1+[Link](i);

if(i<[Link]()-2)

continue;

if([Link]()==1)

if("AEIOU".indexOf([Link](0))==-1)

count++;

sc=sc+s1+" ";

s1="";
continue;

else

sv=sv+s1+" ";

s1="";

continue;

if([Link]()>1 &&"AEIOU".indexOf([Link](0))==-1 &&


"AEIOU".indexOf([Link]([Link]()-1))==-1)

count++;

sc=sc+s1+" ";

s1="";

else

sv=sv+s1+" ";

s1="";

}
sf=sc+sv;

[Link]("Number of consonants beginning and ending with


consonants: " + count);

[Link]("Sentences: " + sf);

OUTPUT:
[Link] TO NUMBERS
Write a program in java to accept a string s representing a Roman numeral, find it's
corresponding integer value. Roman numerals are formed using the following
symbols: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, and M = 1000. Numbers
are typically formed by combining these symbols from left to right, adding or
subtracting their values based on specific rules.

ALGORITHM:

Step 1: Start
Step 2: Declare the required integer variables
Step 3: Create a Scanner object
Step 4: Accept a Roman numeral from the user
Step 5: Initialize total to 0
Step 6: For each character in the Roman numeral, determine its integer value
Step 7: Store the value of the current Roman symbol in n1
Step 8: If the next symbol exists, determine its integer value and store it in n2
Step 9: If n1 < n2, perform subtraction and add (n2 - n1) to total
Step 10: Increase the loop counter to skip the next symbol after subtraction
Step 11: Else add n1 to total
Step 12: If no next symbol exists, add n1 to total
Step 13: Repeat the process until all symbols are processed
Step 14: Display the integer value
Step 15: Stop

SOURCE CODE:

import [Link].*;

public class RomanToInteger

public static void main(String args[])


{

Scanner sc = new Scanner([Link]);

[Link]("Enter Roman Numeral: ");

String s = [Link]();

int total = 0, n1 = 0, n2 = 0;

for(int i = 0; i < [Link](); i++)

char ch = [Link](i);

// Value of current symbol

if(ch == 'I')

n1 = 1;

else if(ch == 'V')

n1 = 5;

else if(ch == 'X')

n1 = 10;

else if(ch == 'L')

n1 = 50;

else if(ch == 'C')


n1 = 100;

else if(ch == 'D')

n1 = 500;

else if(ch == 'M')

n1 = 1000;

// Check next symbol

if(i + 1 < [Link]())

char ch2 = [Link](i + 1);

// Value of next symbol

if(ch2 == 'I')

n2 = 1;

else if(ch2 == 'V')

n2 = 5;

else if(ch2 == 'X')

n2 = 10;

else if(ch2 == 'L')

n2 = 50;

else if(ch2 == 'C')

n2 = 100;
else if(ch2 == 'D')

n2 = 500;

else if(ch2 == 'M')

n2 = 1000;

// Subtraction case

if(n1 < n2)

total = total + (n2 - n1);

i++;

else

total = total + n1;

else

total = total + n1;

}
[Link]("Integer Value = " + total);

OUTPUT:
[Link] ADDITION
Given two binary strings s1 and s2, the task is to return their sum. The input strings
may contain leading zeros but the output string should not have any leading zeros.

ALGORITHM:

Step 1: Start
Step 2: Declare the required string and integer variables
Step 3: Create a Scanner object
Step 4: Accept the first binary number from the user
Step 5: Accept the second binary number from the user
Step 6: Initialize i and j to the last index positions of both strings
Step 7: Initialize carry to 0 and ans to an empty string
Step 8: While i >= 0 or j >= 0 or carry == 1, repeat the process
Step 9: Store the value of carry in variable sum
Step 10: If i >= 0 and the current bit of first binary number is 1, add 1 to sum
Step 11: Decrease the value of i by 1
Step 12: If j >= 0 and the current bit of second binary number is 1, add 1 to sum
Step 13: Decrease the value of j by 1
Step 14: If sum % 2 == 0, add 0 at the beginning of ans
Step 15: Else add 1 at the beginning of ans
Step 16: Store sum / 2 as the new carry
Step 17: Repeat the process until all bits are added
Step 18: Remove leading zeros from the result
Step 19: Display the binary sum
Step 20: Stop

SOURCE CODE:

import [Link].*;

public class BinarySum


{

public static void main(String args[])

// Read two binary strings from the user

Scanner sc = new Scanner([Link]);

[Link]("Enter first binary number: ");

String s1 = [Link]();

[Link]("Enter second binary number: ");

String s2 = [Link]();

// Start from the least significant digit of each string

int i = [Link]() - 1;

int j = [Link]() - 1;

int carry = 0;

String ans = "";

// Add bits while there are digits left or a carry remains

while(i >= 0 || j >= 0 || carry == 1)

{
int sum = carry;

if(i >= 0)

if([Link](i) == '1')

sum = sum + 1;

i--;

if(j >= 0)

if([Link](j) == '1')

sum = sum + 1;

j--;

if(sum % 2 == 0)

ans = "0" + ans;

else

ans = "1" + ans;

carry = sum / 2;
}

// Remove leading zeros from the computed sum

String result = "";

int p = 0;

for(int k = 0; k < [Link](); k++)

if([Link](k) == '1')

p = k;

result = [Link](p - 1);

// Print the final binary sum

[Link]("Sum of the two binary numbers: " + result);

}
OUTPUT:
[Link] TO WORD
Write a java program to accept a number and convert the given number into words.
The number should not be a negative number, if so, give an error message.

ALGORITHM:

Step 1: Start
Step 2: Declare the required arrays and integer variables
Step 3: Create a Scanner object
Step 4: Accept a number from the user
Step 5: If the number is negative, display "INVALID INPUT" and terminate the
program
Step 6: Find the highest place value of the number
Step 7: If the number is in crores, extract the digit and display its word form
Step 8: Reduce the number and update the divisor value
Step 9: If the number is in lakhs, extract the digit and display its word form
Step 10: Reduce the number and update the divisor value
Step 11: If the number is in thousands, extract the digit and display its word form
Step 12: Reduce the number and update the divisor value
Step 13: If the number is in hundreds, extract the digit and display its word form
Step 14: If the number is between 20 and 99, display the tens and units word form
Step 15: If the number is between 10 and 19, display the teen word form
Step 16: Else display the unit word form
Step 17: Stop

SOURCE CODE:

import [Link].*;

public class NumToWord

public static void main(String[] args)

{
Scanner sc = new Scanner([Link]);

[Link]("Enter a number:");

int num = [Link]();

String unit[] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine"};

String ten[] = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty",


"Seventy", "Eighty", "Ninety"};

String teen[] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",


"Sixteen", "Seventeen", "Eighteen", "Nineteen"};

int n=num,d=1,r=0;

while(n>0)

n=n/10;

d=d*10;

d=d/10;

if(num<0)

[Link]("INVALID INPUT");

[Link](0);

else

{
if(num>=100000000 && num<=999999999)

r=num/d;

num=num%d;

d=d/10;

[Link](ten[r]+" ");

if(num>=10000000 && num<=99999999)

r=num/d;

num=num%d;

d=d/10;

[Link](unit[r]+" crore ");

if(num>=1000000 && num<=9999999)

r=num/d;

num=num%d;

d=d/10;

[Link](ten[r]+ " ");

if(num>=100000 && num<=999999)


{

r=num/d;

num=num%d;

d=d/10;

[Link](unit[r]+" lakh ");

if(num>=10000 && num<=99999)

r=num/d;

num=num%d;

d=d/10;

[Link](ten[r]+" ");

if(num>=1000 && num<=9999)

r=num/d;

num=num%d;

d=d/10;

[Link](unit[r]+" thousand ");

if(num>=100 && num<=999)

{
r=num/d;

num=num%d;

d=d/10;

[Link](unit[r]+" hundred ");

if(num>=20 && num<=99)

r=num/d;

num=num%d;

d=d/10;

[Link](ten[r]+" "+unit[num%10]);

[Link](0);

if(num>=10 && num<=19)

r=num/d;

num=num%d;

[Link](teen[r]);

else

[Link](unit[num]);
}

OUTPUT:
[Link] ROTATION
Write a program to accept two strings s1 and s2 of equal length, determine whether
s2 is a rotation of s1.A string is said to be a rotation of another if it can be obtained
by shifting some leading characters of the original string to its end without changing
the order of characters.

ALGORITHM:

Step 1: Start
Step 2: Declare the required string variables
Step 3: Create a Scanner object
Step 4: Accept the first string from the user
Step 5: Accept the second string from the user
Step 6: If the lengths of both strings are not equal, display that they are not
rotations and terminate the program
Step 7: Initialize temporary strings for left and right rotations
Step 8: For each position in the string, perform rotation operations
Step 9: Create the right rotated string by moving the last character to the front
Step 10: Create the left rotated string by moving the first character to the end
Step 11: If the right rotated string becomes equal to the second string, display the
number of right rotations
Step 12: Terminate the program after displaying the result
Step 13: If the left rotated string becomes equal to the second string, display the
number of left rotations
Step 14: Terminate the program after displaying the result
Step 15: Update the strings for the next rotation
Step 16: Repeat the process until all rotations are checked
Step 17: If no match is found, display that the strings are not rotations of each other
Step 18: Stop
SOURCE CODE:

import [Link].*;

public class Rotation

public static void main(String[] args)

// Create Scanner to read input

Scanner sc = new Scanner([Link]);

[Link]("Enter first string:");

String s1 = [Link]();

[Link]("Enter second string:");

String s2 = [Link]();

// Check if both strings have same length

if([Link]() != [Link]())

[Link]("Strings are not rotations of each other.");

[Link](0);

else

{
// Initialize variables for rotation

String a=s1,b=s1;

String t1 = "",t2="";

// Loop to rotate strings

for(int i=0; i<[Link](); i++)

// Right rotation: move last character to front

t1=[Link]([Link]()-1)+[Link](0, [Link]()-1);

// Left rotation: move first character to end

t2=[Link](1, [Link]())+[Link](0);

// Check if right rotation matches s2

if([Link](s2))

[Link]("After "+(i+1)+" right rotations, s1 will become


equal to s2.");

[Link](0);

// Check if left rotation matches s2

if([Link](s2))

[Link]("After "+(i+1)+" left rotations, s1 will become equal


to s2.");
[Link](0);

// Update for next iteration

a=t1;

b=t2;

[Link]("Strings are not rotations of each other.");

OUTPUT:
[Link] ROTATION
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 both M and N must be
greater than 2 and less than 10. Allow the user to input integers into this matrix.
Display appropriate error message for an invalid input.

Perform the following tasks on the matrix: (a) Display the input matrix. (b) Shift
each row one step upwards so the first row becomes the last row, 2nd row will be
the 1st row and so on. (c) Display the rotated matrix along with the highest element
and its location in the matrix.

ALGORITHM:

STEP 1: Start
STEP 2: Declare variables M, N, i, j, m, n, max, x and y
STEP 3: Input number of rows M and columns N
STEP 4: Check whether M and N are greater than 2 and less than 10
STEP 5: If condition is false, display “INVALID INPUT” and go to Step 20
STEP 6: Create matrices a1[M][N] and a2[M][N]
STEP 7: Initialize m = 1 and n = 0
STEP 8: Display message to enter matrix elements
STEP 9: Read elements into matrix a1[][]
STEP 10: Repeat for i = 0 to M-1
STEP 11: Repeat for j = 0 to N-1
STEP 12: Copy a1[m][n] into a2[i][j]
STEP 13: Increment n
STEP 14: After inner loop set n = 0
STEP 15: Update m value for rotation
STEP 16: Display rotated matrix a2[][]
STEP 17: Find the maximum element and its position
STEP 18: Display maximum element and its position
STEP 19: End of if condition
STEP 20: Stop
SOURCE CODE:

import [Link].*;

public class ArrayRoatation

public static void main(String[] args)

Scanner sc = new Scanner([Link]);

[Link]("Enter the Rows and Columns size:");

int M = [Link]();

int N = [Link]();

int m=1,n=0; // m: source row index, n: source column index

// Validate input: rows and columns must be between 2 and 10

if(M>2 && N>2 && M<10 && N<10)

int i, j;

int a1[][] = new int[M][N];

int a2[][] = new int[M][N];

// Read input array from user

[Link]("Enter the elements of the array:");

for(i=0; i<M; i++)

for(j=0; j<N; j++)


{

a1[i][j] = [Link]();

[Link]();

// Copy and rotate array elements

for(i=0; i<M; i++)

for(j=0; j<N; j++)

a2[i][j]=a1[m][n];

n++;

n=0;

if(m==M-1)

m=0;

else

m++;

// Display rotated array

int max=0,x=0,y=0;

[Link]("The rotated array is:");


for(i=0; i<M; i++)

for(j=0; j<N; j++)

[Link](a2[i][j]+" ");

if(a2[i][j]>max)

max=a2[i][j];

x=i+1;

y=j+1;

[Link]();

[Link]("Maximum element in the array is: " + max);

[Link]("Position of the maximum element is: (" + x + ", " + y +


")");

else

// Invalid dimensions

[Link]("INVALID INPUT");
}

OUTPUT:
[Link]
Write a java program to accept the order of square matrix. Accept the array
elements and fill the elements in the following manner. Display the resultant matrix.

ALGORITHM:

STEP 1: Start
STEP 2: Declare variables n, i, j, k and arrays a[][] and a1[]
STEP 3: Input the size of the square matrix n
STEP 4: Create matrix a[n][n] and array a1[nn]
STEP 5: Display message to enter array elements
STEP 6: Read nn elements into array a1[]
STEP 7: Display the entered array elements
STEP 8: Initialize k = 0
STEP 9: Repeat for i = 0 to n-1
STEP 10: Check if i is even
STEP 11: If even, repeat for j = 0 to n-1
STEP 12: Store a1[k] into a[i][j] and increment k
STEP 13: Else repeat for j = n-1 to 0
STEP 14: Store a1[k] into a[i][j] and increment k
STEP 15: End of if condition
STEP 16: End of outer loop
STEP 17: Display the matrix in zigzag form
STEP 18: Stop

SOURCE CODE:

import [Link].*;

public class ArrayIntialization

public static void main(String[] args)

{
Scanner sc=new Scanner([Link]);

// read matrix size

[Link]("Enter the number of rows and columns of a square


matriix:");

int n=[Link]();

int i,j;

int a[][]=new int[n][n];

int a1[]=new int [n*n];

// read flat array values

[Link]("Enter array elements :");

for(i=0;i<n*n;i++)

a1[i]=[Link]();

for(i=0;i<n*n;i++)

[Link](a1[i]+" ");

[Link]();

// convert flat list to zigzag matrix

[Link]("Array in matrix form:");

int k=0;
for(i=0;i<n;i++)

if(i%2==0)

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

a[i][j]=a1[k];

k++;

else

for(j=n-1;j>=0;j--)

a[i][j]=a1[k];

k++;

for(i=0;i<n;i++)

for(j=0;j<n;j++)
{

[Link](a[i][j]+" ");

[Link]();

OUTPUT:
[Link] SQUARE
A wondrous square is an n by n grid which fulfils the following conditions: 1. It
contains integers from 1 to n2, where each integer appears only once. 2. The sum of
integers in any row or column must add up to 0.5 x n x (n2 + 1). For example, the
following grid is a wondrous square where the sum of each row or column is 65
when n=5.

17 24 1 8 15

23 5 7 14 16

4 6 13 20 22

10 12 19 21 3

11 18 25 2 9

Write a program to read n (2 <= n <= 10) and the values stored in these n by n cells
and output if the grid represents a wondrous square. Also output all the prime
numbers in the grid along with their row index and column index as shown in the
output. A natural number is said to be prime if it has exactly two divisors. For
example, 2, 3, 5, 7, 11 The first element of the given grid i.e. 17 is stored at row
index 0 and column index 0 and the next element in the row i.e. 24 is stored at row
index 0 and column index 1.

ALGORITHM:

STEP 1: Start
STEP 2: Declare variables n, i, j, rowSum, colSum and valid
STEP 3: Input the size of the square matrix n
STEP 4: Create matrix a[n][n]
STEP 5: Display message to enter matrix elements
STEP 6: Read elements into matrix a[][]
STEP 7: Calculate magicSum = n × (n² + 1) / 2
STEP 8: Initialize valid = 1
STEP 9: Find the sum of each row
STEP 10: Compare row sum with magicSum
STEP 11: If unequal, set valid = 0
STEP 12: Find the sum of each column
STEP 13: Compare column sum with magicSum
STEP 14: If unequal, set valid = 0
STEP 15: Check whether numbers from 1 to n² appear only once
STEP 16: If any number repeats or is invalid, set valid = 0
STEP 17: If valid = 1 display “Wondrous Square”
STEP 18: Else display “Not a Wondrous Square”
STEP 19: Find and display all prime numbers with row and column index
STEP 20: Stop

SOURCE CODE:

import [Link];

public class WondrousSquare

public static void main(String[] args)

Scanner sc = new Scanner([Link]);


[Link]("Enter the size of the square matrix:");
int n = [Link]();

int a[][] = new int[n][n];

int i, j;
[Link]("Enter the elements of the matrix:");
// Reading matrix
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
a[i][j] = [Link]();
}
}

int magicSum = (n * (n * n + 1)) / 2;

int valid = 1;

// Check row sums


for(i = 0; i < n; i++)
{

int rowSum = 0;

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


{
rowSum = rowSum + a[i][j];
}

if(rowSum != magicSum)
{
valid = 0;
}
}

// Check column sums


for(i = 0; i < n; i++)
{

int colSum = 0;

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


{
colSum = colSum + a[j][i];
}
if(colSum != magicSum)
{
valid = 0;
}
}

// Check numbers from 1 to n*n appear only once


int size = n * n;

int count[] = new int[size + 1];

for(i = 0; i < n; i++) {


for(j = 0; j < n; j++)
{

int value = a[i][j];

if(value < 1 || value > size)


{
valid = 0;
}
else {
count[value]++;

if(count[value] > 1)
{
valid = 0;
}
}
}
}

// Output result
if(valid == 1)
{
[Link]("Wondrous Square");
}
else
{
[Link]("Not a Wondrous Square");
}

// Print prime numbers with row and column index


[Link]("Prime Numbers in the grid:");

for(i = 0; i < n; i++) {


for(j = 0; j < n; j++)
{

int num = a[i][j];

int factors = 0;

int k;

for(k = 1; k <= num; k++)


{
if(num % k == 0)
{
factors++;
}
}

if(factors == 2)
{
[Link](num + " Row=" + i + " Column=" + j);
}
}
}
}
}

OUTPUT:
[Link]
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: 1. Display the original matrix. 2.
Sort each column of the matrix in ascending order using Selection sort technique. 3.
Display the changed matrix after sorting each column.

ALGORITHM:

STEP 1: Start
STEP 2: Declare variables m, n, i, j, k, min and temp
STEP 3: Input number of rows m and columns n
STEP 4: Check whether m and n are greater than 2 and less than 10
STEP 5: If condition is false, display “Invalid Input” and go to Step 19
STEP 6: Create matrix a[m][n]
STEP 7: Display message to enter matrix elements
STEP 8: Read elements into matrix a[][]
STEP 9: Display the original matrix
STEP 10: Repeat for each column j = 0 to n-1
STEP 11: Repeat for each row i = 0 to m-2
STEP 12: Assume min = i
STEP 13: Repeat for k = i+1 to m-1
STEP 14: Compare a[k][j] with a[min][j]
STEP 15: Update min if smaller element is found
STEP 16: Swap a[i][j] and a[min][j]
STEP 17: Repeat until all columns are sorted
STEP 18: Display the sorted matrix
STEP 19: Stop
SOURCE CODE:

import [Link];

public class MatrixSort

public static void main(String args[])

Scanner sc = new Scanner([Link]);

int m, n;

// Input rows and columns

[Link]("Enter number of rows : ");

m = [Link]();

[Link]("Enter number of columns : ");

n = [Link]();

// Check validity

if (m <= 2 || m >= 10 || n <= 2 || n >= 10)

[Link]("Invalid Input");
}

else

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

// Input matrix elements

[Link]("Enter the elements of the matrix:");

for (int i = 0; i < m; i++)

for (int j = 0; j < n; j++)

a[i][j] = [Link]();

// Display original matrix

[Link]("Original Matrix:");

for (int i = 0; i < m; i++)

for (int j = 0; j < n; j++)


{

[Link](a[i][j] + "\t");

[Link]();

// Selection Sort column-wise

for (int j = 0; j < n; j++)

for (int i = 0; i < m - 1; i++)

int min = i;

for (int k = i + 1; k < m; k++)

if (a[k][j] < a[min][j])

min = k;

// Swap elements
int temp = a[i][j];

a[i][j] = a[min][j];

a[min][j] = temp;

// Display sorted matrix

[Link]("Matrix after column-wise sorting:");

for (int i = 0; i < m; i++)

for (int j = 0; j < n; j++)

[Link](a[i][j] + "\t");

[Link]();

}
OUTPUT:
[Link]-CLOCKWISE INTIALIZATION
A square matrix is the matrix in which the number of rows is equal to the number of
columns. Thus, a matrix of order n* n is called as Square matrix. Write a program
in java to fill the numbers in a circular fashion (anti-clockwise) with natural
numbers from 1 to n2, taking n as an input.

14 | P a g e

e.g if n=5, then n2 is=25, then the array is filled as:

21 20 19 18 17

22 7 6 5 16

23 8 1 4 15

24 9 2 3 14

25 10 11 12 13

ALGORITHM:

STEP 1: Start
STEP 2: Declare variables n, r, c, num and step
STEP 3: Input the size of the matrix n
STEP 4: Create matrix a[n][n]
STEP 5: Set r = n/2 and c = n/2
STEP 6: Store 1 at the center position a[r][c]
STEP 7: Initialize num = 2 and step = 1
STEP 8: Repeat while num ≤ n*n
STEP 9: Move downward step times and store numbers
STEP 10: Increment num after each insertion
STEP 11: Move right step times and store numbers
STEP 12: Increment step by 1
STEP 13: Move upward step times and store numbers
STEP 14: Increment num after each insertion
STEP 15: Move left step times and store numbers
STEP 16: Increment step by 1
STEP 17: Repeat until all numbers are filled
STEP 18: Display the circular matrix
STEP 19: Stop

SOURCE CODE:

import [Link];

class CircularMatrix

public static void main(String[] args)

Scanner sc = new Scanner([Link]);

[Link]("Enter n: ");

int n = [Link]();

int[][] a = new int[n][n];

int r = n / 2;

int c = n / 2;

a[r][c] = 1;

int num = 2;

int step = 1;
while (num <= n * n)

// Move DOWN 'step' times

for (int i = 0; i < step && num <= n * n; i++)

r++;

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

// Move RIGHT 'step' times

for (int i = 0; i < step && num <= n * n; i++)

c++;

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

step++; // increase step after every DOWN+RIGHT pair

// Move UP 'step' times

for (int i = 0; i < step && num <= n * n; i++)


{

r--;

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

// Move LEFT 'step' times

for (int i = 0; i < step && num <= n * n; i++)

c--;

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

step++; // increase step after every UP+LEFT pair

// Print the arix

for (int i = 0; i < n; i++)

for (int j = 0; j < n; j++)

if (a[i][j] < 10)

[Link](" " + a[i][j] + " ");


else

[Link](" " + a[i][j] + " ");

[Link]();

OUTPUT:
[Link]-COLUMN SUM
Write a program to create a double dimensional array of size n x m. Input the
numbers in first (n-1) x (m-1) cells. Find and place the sum of each row and each
column in corresponding cells of last column and last row respectively. Finally,
display the array elements along with the sum of rows and columns.

ALGORITHM:

STEP 1: Start
STEP 2: Declare variables n, m, i, j, rowSum and colSum
STEP 3: Input number of rows n
STEP 4: Input number of columns m
STEP 5: Create matrix arr[n][m]
STEP 6: Display message to enter matrix elements
STEP 7: Read elements in first (n−1) × (m−1) positions
STEP 8: Repeat for each row i from 0 to n−2
STEP 9: Initialize rowSum = 0
STEP 10: Add all elements of the row
STEP 11: Store rowSum in last column of the row
STEP 12: Repeat for each column j from 0 to m−2
STEP 13: Initialize colSum = 0
STEP 14: Add all elements of the column
STEP 15: Store colSum in last row of the column
STEP 16: Display heading for final matrix
STEP 17: Print matrix with row sums and column sums
STEP 18: Leave bottom-right corner blank
STEP 19: End of program
STEP 20: Stop
SOURCE CODE:

import [Link];

public class RowColumn

public static void main(String[] args)

Scanner sc = new Scanner([Link]);

[Link]("Enter number of rows (n): ");

int n = [Link]();

[Link]("Enter number of columns (m): ");

int m = [Link]();

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

// Input numbers in first (n-1) x (m-1) cells

[Link]("Enter " + (n-1) + " x " + (m-1) + " elements:");

for (int i = 0; i < n - 1; i++)

for (int j = 0; j < m - 1; j++)

arr[i][j] = [Link]();
}

// Calculate row sums → store in last column

for (int i = 0; i < n - 1; i++)

int rowSum = 0;

for (int j = 0; j < m - 1; j++)

rowSum += arr[i][j];

arr[i][m - 1] = rowSum;

// Calculate column sums → store in last row

for (int j = 0; j < m - 1; j++)

int colSum = 0;

for (int i = 0; i < n - 1; i++)

colSum += arr[i][j];

}
arr[n - 1][j] = colSum;

// Display the array

[Link]("\nArray with Row and Column Sums:");

for (int i = 0; i < n; i++)

for (int j = 0; j < m; j++)

if (i == n - 1 && j == m - 1)

[Link]("\t"); // bottom-right corner left blank

else

[Link](arr[i][j] + "\t");

[Link]();

}
OUTPUT:
[Link] FREQUENCY
Input a paragraph containing 'n' number of sentences where (1 < = n < 4). The
words are to be separated with a single blank space and are in UPPERCASE. A
sentence may be terminated either with a full stop '.' Or a question mark '?' only.
Any other character may be ignored. Perform the following operations:

Accept the number of sentences. If the number of sentences exceeds the limit, an
appropriate error message must be displayed.

Find the number of words in the whole paragraph.

Display the words in ascending order of their frequency. Words with same
frequency may appear in any order.

ALGORITHM:

STEP 1: Start
STEP 2: Declare variables n, i, j, k, c and strings p, s and word
STEP 3: Input number of sentences n
STEP 4: Check whether n is between 1 and 4
STEP 5: If invalid, display error message and stop
STEP 6: Initialize empty string p
STEP 7: Input all sentences and combine them into p
STEP 8: Remove full stop and question mark characters
STEP 9: Count total number of words manually
STEP 10: Display total number of words
STEP 11: Create string array w[] to store words
STEP 12: Extract words one by one without using split()
STEP 13: Store extracted words into array w[]
STEP 14: Create frequency array freq[]
STEP 15: Compare words and count frequency of each word
STEP 16: Mark repeated words with −1
STEP 17: Sort words according to frequency
STEP 18: Display heading “Word Frequency”
STEP 19: Print each word with its frequency
STEP 20: Stop

SOURCE CODE:

import [Link];

public class WordFrequency

public static void main(String args[])

Scanner sc = new Scanner([Link]);

int n, i, j, k = 0, c = 0;

[Link]("Enter number of sentences:");

n = [Link]();

[Link]();

if(n < 1 || n > 4)

[Link]("Invalid number of sentences");

return;

}
String p = "", s;

[Link]("Enter sentences:");

// Input sentences

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

s = [Link]();

p = p + " " + s;

// Remove . and ?

String temp = "";

for(i = 0; i < [Link](); i++)

char ch = [Link](i);

if(ch != '.' && ch != '?')

temp = temp + ch;

}
}

p = temp;

// Count words manually

int words = 0;

for(i = 0; i < [Link](); i++)

if(i == 0 && [Link](i) != ' ')

words++;

else if([Link](i) != ' ' && [Link](i - 1) == ' ')

words++;

[Link]("Total number of words: " + words);

// Store words manually without split()


String w[] = new String[words];

String word = "";

for(i = 0; i < [Link](); i++)

char ch = [Link](i);

if(ch != ' ')

word = word + ch;

else

if([Link]() > 0)

w[k] = word;

k++;

word = "";

}
// Last word

if([Link]() > 0)

w[k] = word;

int freq[] = new int[words];

// Find frequency

for(i = 0; i < words; i++)

c = 1;

if(freq[i] != -1)

for(j = i + 1; j < words; j++)

if(w[i].equals(w[j]))

c++;

freq[j] = -1;
}

freq[i] = c;

// Sort according to frequency

for(i = 0; i < words - 1; i++)

for(j = i + 1; j < words; j++)

if(freq[i] > freq[j] && freq[j] != -1)

int t = freq[i];

freq[i] = freq[j];

freq[j] = t;

String x = w[i];

w[i] = w[j];

w[j] = x;

}
}

// Display result

[Link]("\nWord\tFrequency");

for(i = 0; i < words; i++)

if(freq[i] != -1)

[Link](w[i] + "\t" + freq[i]);

}
OUTPUT:
[Link] MARKOV
Write a program to declare a square matrix M[][] of order ‘N’. Check if the matrix
is a Doubly Markov matrix or not. A matrix which satisfies the following
conditions is Doubly Markov Matrix: (i) All elements are >= 0 (ii) Sum of each row
= 1 (iii) Sum of each column = 1 Accept ‘N’ from the user where 3 <= N <= 9.
Display an appropriate error message if ‘N’ is not in the given range or the entered
numbers are negative. Allow the user to create a matrix and check whether the
created matrix is a Doubly Markov Matrix or [Link] your program for the
following data and some random data:

ALGORITHM:

STEP 1: Start
STEP 2: Declare variables n, i, j, sum and flag f
STEP 3: Input the size of the matrix n
STEP 4: Check whether n is between 3 and 9
STEP 5: If invalid, display “INVALID INPUT”
STEP 6: Else create matrix m[n][n]
STEP 7: Initialize flag f = 0
STEP 8: Display message to enter matrix elements
STEP 9: Read elements into matrix m[][]
STEP 10: Check whether any element is negative
STEP 11: If negative element found, set f = 1
STEP 12: Display the formed matrix
STEP 13: Find sum of each row
STEP 14: If row sum is not equal to 1, set f = 1
STEP 15: Find sum of each column
STEP 16: If column sum is not equal to 1, set f = 1
STEP 17: Check value of flag f
STEP 18: If f = 0 display “IT IS A DOUBLY MARKOV MATRIX”
STEP 19: Else display “IT IS NOT A DOUBLY MARKOV MATRIX”
STEP 20: Stop
SOURCE CODE:

import [Link].*;

class DoublyMarkov

public static void main(String args[])

Scanner sc = new Scanner([Link]);

[Link]("Enter N");

int n = [Link]();

if(n < 3 || n > 9)

[Link]("INVALID INPUT");

else

double m[][] = new double[n][n];

int f = 0;
[Link]("Enter elements in the matrix");

// Input matrix

for(int i = 0; i < n; i++)

for(int j = 0; j < n; j++)

m[i][j] = [Link]();

if(m[i][j] < 0)

f = 1;

// Display matrix

[Link]("FORMED MATRIX");

for(int i = 0; i < n; i++)

for(int j = 0; j < n; j++)


{

[Link](m[i][j] + "\t");

[Link]();

// Check row sum

for(int i = 0; i < n; i++)

double sum = 0;

for(int j = 0; j < n; j++)

sum = sum + m[i][j];

if(sum != 1)

f = 1;

}
// Check column sum

for(int j = 0; j < n; j++)

double sum = 0;

for(int i = 0; i < n; i++)

sum = sum + m[i][j];

if(sum != 1)

f = 1;

// Final result

if(f == 0)

[Link]("IT IS A DOUBLY MARKOV MATRIX");

else
{

[Link]("IT IS NOT A DOUBLY MARKOV MATRIX");

OUTPUT:
[Link] SUBTRACTION
A class Matrix contains a two-dimensional integer array of order [m × n]. The
maximum value possible for both ‘m’ and ‘n’ is 25.

Design a class Matrix to find the difference of the two matrices. The details of the
members of the class are given below:

Class name : Matrix

Data members/instance variables: arr[ ][ ] : stores the matrix elements m : integer to


store the number of rows n : integer to store the number of columns

Member functions: Matrix(int mm, int nn) : to initialize the size of the matrix m =
mm and n = nn void fillArray( ) : to enter the elements of the matrix Matrix
subMat(Matrix a) : subtract the current object from the matrix of

parameterized object and return the resulting object void display( ) : display the
matrix elements

Specify the class Matrix giving details of the constructor(int, int), void fillArray(),
Matrix subMat(Matrix) and void display(). Define the main() function to create
objects and call the methods accordingly to enable the task.

ALGORITHM:

STEP 1: Start
STEP 2: Declare variables r, c, i and j
STEP 3: Input number of rows r
STEP 4: Input number of columns c
STEP 5: Check whether r and c are less than or equal to 25
STEP 6: If invalid, display error message and stop
STEP 7: Create matrices A[r][c], B[r][c] and C[r][c]
STEP 8: Display message to enter first matrix
STEP 9: Read elements into matrix A[][]
STEP 10: Display message to enter second matrix
STEP 11: Read elements into matrix B[][]
STEP 12: Repeat for i = 0 to r-1
STEP 13: Repeat for j = 0 to c-1
STEP 14: Subtract corresponding elements of matrices
STEP 15: Store result in matrix C[][]
STEP 16: End inner and outer loops
STEP 17: Display the resultant matrix
STEP 18: Print all elements of matrix C[][]
STEP 19: End of program
STEP 20: Stop

SOURCE CODE:

class Matrix

int arr[][];

int m, n;

// Constructor

Matrix(int mm, int nn)

m = mm;

n = nn;

arr = new int[m][n];

// Input matrix elements

void fillArray()
{

Scanner sc = new Scanner([Link]);

[Link]("Enter matrix elements:");

for(int i = 0; i < m; i++)

for(int j = 0; j < n; j++)

arr[i][j] = [Link]();

// Subtract matrices

Matrix subMat(Matrix a)

Matrix res = new Matrix(m, n);

for(int i = 0; i < m; i++)

for(int j = 0; j < n; j++)


{

[Link][i][j] = [Link][i][j] - [Link][i][j];

return res;

// Display matrix

void display()

for(int i = 0; i < m; i++)

for(int j = 0; j < n; j++)

[Link](arr[i][j] + "\t");

[Link]();

}
// Main method

public static void main(String args[])

Scanner sc = new Scanner([Link]);

int r, c;

[Link]("Enter number of rows:");

r = [Link]();

[Link]("Enter number of columns:");

c = [Link]();

if(r > 25 || c > 25)

[Link]("Matrix size should not exceed 25");

return;

Matrix A = new Matrix(r, c);

Matrix B = new Matrix(r, c);


[Link]("Enter first matrix:");

[Link]();

[Link]("Enter second matrix:");

[Link]();

Matrix C = [Link](B);

[Link]("Resultant Matrix:");

[Link]();

}
OUTPUT:
[Link] INTEGER
Given two positive numbers M and N, such that M is between 100 and 10000 and N
is less than 100. Find the smallest integer that is greater than M and whose digits
add up to N. For example, if M = 100 and N = 11, then the smallest integer greater
than 100 whose digits add up to 11 is [Link] a program to accept the numbers M
and N from the user and print the smallest required number whose sum of all its
digits is equal to N. Also, print the total number of digits present in the required
number. The program should check for the validity of the inputs and display an
appropriate message for an invalid input. For sum of digits and counting the
numbers of digits use recursive technique.

ALGORITHM:

STEP 1: Start
STEP 2: Declare variables M, N, num, sum, temp and count
STEP 3: Input value of M
STEP 4: Input value of N
STEP 5: Check whether M is between 100 and 10000
STEP 6: Check whether N is between 1 and 99
STEP 7: If invalid, display “Invalid Input” and stop
STEP 8: Initialize num = M + 1
STEP 9: Repeat indefinitely
STEP 10: Store num in temp and initialize sum = 0
STEP 11: Find sum of digits of temp
STEP 12: Add each digit to sum
STEP 13: Compare sum with N
STEP 14: If sum equals N, stop loop
STEP 15: Else increment num by 1
STEP 16: Count number of digits in num
STEP 17: Store total digits in count
STEP 18: Display the required number
STEP 19: Display total number of digits
STEP 20: Stop
SOURCE CODE:

import [Link];

class SmallestInt

public static void main(String args[])

Scanner sc = new Scanner([Link]);

int M, N;

[Link]("Enter value of M:");

M = [Link]();

[Link]("Enter value of N:");

N = [Link]();

// Checking validity

if(M < 100 || M > 10000 || N <= 0 || N >= 100)

[Link]("Invalid Input");

return;
}

int num = M + 1;

while(true)

int temp = num;

int sum = 0;

// Finding sum of digits without function

while(temp > 0)

int d = temp % 10;

sum = sum + d;

temp = temp / 10;

if(sum == N)

break;

}
num++;

// Counting digits without function

int temp2 = num;

int count = 0;

while(temp2 > 0)

count++;

temp2 = temp2 / 10;

[Link]("The required number = " + num);

[Link]("Total number of digits = " + count);

}
OUTPUT:
[Link](QUEUE)
A linear data structure enables the user to add address from rear end and remove
address from front. Define a class Diary with the following details: Class name :
Diary Data members/instance variables: Q[ ] : array to store the addresses size :
stores the maximum capacity of the array start : to point the index of the front end
end : to point the index of the rear end Member functions: Diary(int max) :
constructor to initialize the data member size = max, start = 0 and end = 0 void
pushadd(String n) : to add address in the diary from the rear end if possible,
otherwise display the message “NO SPACE” String popadd( ) : removes and
returns the address from the front end of the diary if any, else returns “?????” void
show( ) : displays all the addresses in the diary (a) Specify the class Diary giving
details of the functions void pushadd(String) and String popadd(). Assume that the
other functions have been defined. Create a main function and call all the functions
accordingly.

ALGORITHM:

STEP 1: Start
STEP 2: Declare array Q[] and variables size, start and end
STEP 3: Input the maximum size of the diary
STEP 4: Create a Diary object with given size
STEP 5: Initialize start = 0 and end = 0
STEP 6: Display menu options for user choices
STEP 7: Input the user’s choice
STEP 8: If choice is 1, input address from user
STEP 9: Check whether end is equal to size
STEP 10: If true, display “NO SPACE”
STEP 11: Else insert address at Q[end]
STEP 12: Increment end by 1
STEP 13: If choice is 2, check whether start equals end
STEP 14: If true, display “Diary is Empty”
STEP 15: Else remove address from Q[start]
STEP 16: Increment start by 1
STEP 17: Display removed address
STEP 18: If choice is 3, display all addresses from start to end
STEP 19: Repeat steps until choice becomes 4
STEP 20: Stop

SOURCE CODE:

import [Link];

class Diary

String Q[];

int size;

int start;

int end;

// Constructor

Diary(int max)

size = max;

start = 0;

end = 0;

Q = new String[size];

}
// Add address from rear end

void pushadd(String n)

if(end == size)

[Link]("NO SPACE");

else

Q[end] = n;

end++;

// Remove address from front end

String popadd()

if(start == end)

return "?????";

}
else

String val = Q[start];

start++;

return val;

// Display all addresses

void show()

if(start == end)

[Link]("Diary is Empty");

else

[Link]("Addresses in Diary:");

for(int i = start; i < end; i++)

[Link](Q[i]);
}

// Main method

public static void main(String args[])

Scanner sc = new Scanner([Link]);

[Link]("Enter size of diary:");

int n = [Link]();

[Link]();

Diary obj = new Diary(n);

int ch;

String add;

do

[Link]("\n1. ADD ADDRESS");

[Link]("2. REMOVE ADDRESS");


[Link]("3. DISPLAY");

[Link]("4. EXIT");

[Link]("Enter choice:");

ch = [Link]();

[Link]();

switch(ch)

case 1:

[Link]("Enter Address:");

add = [Link]();

[Link](add);

break;

case 2:

add = [Link]();

if([Link]("?????"))

[Link]("Diary is Empty");

}
else

[Link]("Removed Address:");

[Link](add);

break;

case 3:

[Link]();

break;

case 4:

[Link]("Program Ended");

break;

default:

[Link]("Invalid Choice");

} while(ch != 4);

}
}

OUTPUT:

You might also like