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

algorithms

The document outlines multiple Java programs for various functionalities including keystroke counting, date calculation, Goldbach's conjecture, anagram checking, pangram validation, and matrix row handling. Each program includes steps for user input, validation, processing, and output. The programs utilize methods for checking conditions such as prime numbers and leap years, and handle string manipulations for anagram and pangram checks.

Uploaded by

sahilpalit2478
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

algorithms

The document outlines multiple Java programs for various functionalities including keystroke counting, date calculation, Goldbach's conjecture, anagram checking, pangram validation, and matrix row handling. Each program includes steps for user input, validation, processing, and output. The programs utilize methods for checking conditions such as prime numbers and leap years, and handle string manipulations for anagram and pangram checks.

Uploaded by

sahilpalit2478
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

KEYPAD KEYSTROKE

 Start

 Input the word:

 Prompt the user to enter a word.


 Convert the word to uppercase.

 Validate the input:

 Iterate through each character in the word:


o Check if the character is a letter:
 If any character is not a letter, display "INVALID ENTRY" and terminate
the program.

 Initialize variables:

 Set count = 0 (to keep track of the total keystrokes).

 Iterate through each character in the word:

 For each character ch in the word:


o If ch belongs to "ADGJMPTW":
 Add 1 to count.
o Else if ch belongs to "BEHKNQUX":
 Add 2 to count.
o Else if ch belongs to "CFILORVY":
 Add 3 to count.
o Else (remaining letters such as "SZ"):
 Add 4 to count.

 Output the total keystrokes:

 Display "Number of keystrokes = <count>".

 End
import java.util.Scanner;

class Keypad{

public static void main(String[] args){

Scanner in = new Scanner(System.in);

System.out.print("Enter the word: ");

String word = in.next().toUpperCase();

int count = 0;

for(int i = 0; i < word.length(); i++){

char ch = word.charAt(i);

if(!Character.isLetter(ch)){

System.out.println("INVALID ENTRY");

return;

if("ADGJMPTW".indexOf(ch) >= 0)

count++;

else if("BEHKNQUX".indexOf(ch) >= 0)

count += 2;

else if("CFILORVY".indexOf(ch) >= 0)

count += 3;

else

count += 4;

System.out.println("Number of keystrokes = " + count);

}
DATE PROGRAM

1. Start
2. Input the day number, year, and value of N:
o Prompt the user to enter:
 dayNum (an integer representing the day of the year).
 year (an integer representing the year).
 n (an integer representing the number of days to add).
3. Validate the input values:
o Initialize validDayNum = true and validN = true.
o Check the validity of dayNum:
 If dayNum < 1 or:
 dayNum > 365 for a non-leap year.
 dayNum > 366 for a leap year.
 Set validDayNum = false and display "INCORRECT DAY
NUMBER".
o Check the validity of n:
 If n < 1 or n > 100:
 Set validN = false and display "INCORRECT VALUE OF
'N'".
o If either validDayNum or validN is false, terminate the program.
4. Set up month and day arrays:
o Initialize an array day with the number of days in each month for a non-leap
year:
 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}.
o Initialize an array month with the names of the months:
 {"JANUARY", "FEBRUARY", ..., "DECEMBER"}.
5. Adjust for leap year:
o If the year is a leap year (isLeap(year) returns true):
 Set day[1] = 29.
6. Calculate the entered date:
o Initialize index = 0 (to track the current month).
o While dayNum > day[index]:
 Subtract day[index] from dayNum.
 Increment index.
 If index reaches 12 (end of the year):
 Reset index = 0.
 Increment year.
 Adjust day[1] for the new year if it's a leap year.
7. Display the entered date:
o Print "ENTERED DATE: <month[index]> <dayNum>, <year>".
8. Calculate the date N days later:
o While n > 0:
 Increment dayNum.
 Decrement n.
 If dayNum > day[index]:
 Reset dayNum = 1.
 Increment index.
 If index reaches 12 (end of the year):
 Reset index = 0.
 Increment year.
 Adjust day[1] for the new year if it's a leap year.
9. Display the resulting date:
o Print "<n> DAYS LATER: <month[index]> <dayNum>, <year>".
10. Define the helper function isLeap(year) to determine if a year is a leap year:
o Return true if:
 (year % 4 == 0) and (year % 100 != 0), or (year % 400 == 0).
o Otherwise, return false.
11. End
import java.util.Scanner;

class LaterDate{

public static void main(String[] args){

Scanner in = new Scanner(System.in);

boolean validDayNum = true;

boolean validN = true;

System.out.print("DAY NUMBER: ");

int dayNum = Integer.parseInt(in.nextLine());

System.out.print("YEAR: ");

int year = Integer.parseInt(in.nextLine());

System.out.print("N: ");

int n = Integer.parseInt(in.nextLine());

if(dayNum < 1 || (dayNum > 365 && !isLeap(year))){

validDayNum = false;

System.out.println("INCORRECT DAY NUMBER");

else if(dayNum > 366 && isLeap(year)){

validDayNum = false;

System.out.println("INCORRECT DAY NUMBER");

if(n < 1 || n > 100){

validN = false;

System.out.println("INCORRECT VALUE OF 'N'");

if(!validDayNum || !validN)
return;

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

String month[] = {"JANUARY", "FEBRUARY", "MARCH", "APRIL",


"MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER",
"NOVEMBER", "DECEMBER"};

if(isLeap(year))

day[1] = 29;

int index = 0;

while(dayNum > day[index]){

dayNum -= day[index++];

if(index == 12){

index = 0;

year++;

if(isLeap(year))

day[1] = 29;

else

day[1] = 28;

System.out.println("ENTERED DATE: " + month[index] + " " + dayNum + ", "


+ year);

System.out.print(n + " DAYS LATER: ");

while(n > 0){

dayNum++;

n--;

if(dayNum > day[index]){

dayNum = 1;
index++;

if(index == 12){

index = 0;

year++;

if(isLeap(year))

day[1] = 29;

else

day[1] = 28;

System.out.println(month[index] + " " + dayNum + ", " + year);

public static boolean isLeap(int y){

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

return true;

return false;

}
GOLDBACH

 Start

 Input the even integer N:

 Prompt the user to enter an integer N.


 Convert the input to an integer.

 Validate the input:

 Check if N is greater than 50 or if N is odd:


o If true, display "INVALID INPUT" and terminate the program.

 Initialize variables:

 Set i = 3 (starting from the smallest odd prime number).

 Iterate to find prime pairs:

 While i is less than or equal to (N - i):


o Check if both i and (N - i) are prime using the isPrime method.
o If both numbers are prime:
 Print the pair (i, N - i).
o Increment i by 1.

 Prime-checking method (isPrime):

 Input: An integer n.
 Initialize a counter f = 0.
 Loop through integers from 1 to n:
o If n is divisible by the current integer, increment f.
 If f equals 2 (indicating only two divisors: 1 and itself):
o Return true (the number is prime).
 Else:
o Return false (the number is not prime).

 End
import java.util.Scanner;
class Goldbach{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("N = ");
int n = Integer.parseInt(in.nextLine());
if(n > 50 || n % 2 != 0){
System.out.println("INVALID INPUT");
return;
}
int i = 3;
while(i <= (n - i)){
if(isPrime(i) && isPrime(n - i))
System.out.println(i + ", " + (n - i));
i++;
}
}
public static boolean isPrime(int n){
int f = 0;
for(int i = 1; i <= n; i++){
if(n % i == 0)
f++;
}
return f == 2;
}
}
ANAGRAM

 Start

 Input two strings:

 Prompt the user to enter the first string a.


 Convert the string a to uppercase.
 Prompt the user to enter the second string b.
 Convert the string b to uppercase.

 Validate both strings using the valid method:

 For each string, iterate through its characters:


o If any character is neither a letter nor a whitespace, the input is invalid.
 If either string is invalid:
o Print "INVALID CHARACTERS IN STRING. INVALID INPUT".
o Terminate the program.

 Remove spaces from both strings using the removeSpaces method:

 For each string:


o Create an empty result string.
o Iterate through each character:
 Append the character to the result if it is not a whitespace.
 Update a and b to their space-free versions.

 Check if the strings are anagrams:

 Initialize status = true (to track if they are anagrams).


 While the length of a is greater than 0:
o Extract the first character x from a.
o Remove all occurrences of x from both a and b:
 Use the replace method.
o If the lengths of a and b differ at any point:
 Set status = false.
 Break the loop.

 Output the result:

 If status is true:
o Print "THEY ARE ANAGRAMS!".
 Otherwise:
o Print "THEY ARE NOT ANAGRAMS.".

 End
class Anagrams{

public static void main(String[] args){

Scanner in = new Scanner(System.in);

System.out.print("Enter first string: ");

String a = in.nextLine().toUpperCase();

System.out.print("Enter second string: ");

String b = in.nextLine().toUpperCase();

if(!valid(a) || !valid(b)){

System.out.println("INVALID CHARACTERS IN STRING. INVALID


INPUT");

return;

a = removeSpaces(a);

b = removeSpaces(b);

boolean status = true;

while(a.length() > 0){

String x = String.valueOf(a.charAt(0));

a = a.replace(x, "");

b = b.replace(x, "");

if(a.length() != b.length()){

status = false;

break;

if(status)
System.out.println("THEY ARE ANAGRAMS!");

else

System.out.println("THEY ARE NOT ANAGRAMS.");

public static boolean valid(String s){

for(int i = 0; i < s.length(); i++){

char ch = s.charAt(i);

if(!Character.isWhitespace(ch) && !Character.isLetter(ch))

return false;

return true;

public static String removeSpaces(String s){

String str = new String();

for(int i = 0; i < s.length(); i++){

char ch = s.charAt(i);

if(Character.isWhitespace(ch))

continue;

str += ch;

return str;

}
PANGRAM PROGRAM

 Start

 Input the sentence:

 Prompt the user to enter a sentence s.

 Validate the input:

 Check if the length of s is zero:


o If true, print "INVALID INPUT" and terminate the program.
 Check if the last character of s is one of ., ?, or !:
o If not, print "INVALID INPUT" and terminate the program.

 Initialize variables:

 shortest = s (to store the shortest word, initialize to the input sentence).
 longest = "" (to store the longest word).
 isPangram = true (to track if the sentence is a pangram).

 Check if the sentence is a pangram:

 Iterate through each character ch from 'a' to 'z':


o Initialize match = false.
o For each character in the sentence s:
 If ch matches any character in s (case-insensitive), set match = true
and break.
o If match = false for any letter, set isPangram = false and break the loop.
 If isPangram is true, print "IT IS A PANGRAM".
 Otherwise, print "IT IS NOT A PANGRAM".

 Find the shortest and longest words:

 Initialize word = "" (to accumulate characters of the current word).


 Iterate through each character ch in the sentence s:
o If ch is a letter or digit, append it to word.
o Otherwise (punctuation or space):
 If the length of word is greater than the length of longest, update
longest = word.
 If the length of word is less than the length of shortest, update
shortest = word.
 Reset word = "" to start a new word.
 After the loop, check if word (last word in the sentence) needs updating:
o Compare its length with shortest and longest.
 Output the longest and shortest words:

 Print "LONGEST WORD: <longest>".


 Print "SHORTEST WORD: <shortest>".

 End
import java.util.Scanner;

class Pangram{

public static void main(String[] args){

Scanner in = new Scanner(System.in);

System.out.print("Enter the sentence: ");

String s = in.nextLine();

if(s.length() == 0){

System.out.println("INVALID INPUT");

return;

char last = s.charAt(s.length() - 1);

if(".?!".indexOf(last) == -1){

System.out.println("INVALID INPUT");

return;

String shortest = new String(s);

String longest = new String();

boolean isPangram = true;

for(char ch = 'a'; ch <= 'z'; ch++){

boolean match = false;

for(int i = 0; i < s.length(); i++){

if(ch == Character.toLowerCase(s.charAt(i))){

match = true;

break;

}
}

if(!match){

isPangram = false;

break;

if(isPangram)

System.out.println("IT IS A PANGRAM");

else

System.out.println("IT IS NOT A PANGRAM");

String word = new String();

for(int i = 0; i < s.length(); i++){

char ch = s.charAt(i);

if(Character.isLetterOrDigit(ch))

word += ch;

else{

if(word.length() > longest.length())

longest = new String(word);

if(word.length() < shortest.length())

shortest = new String(word);

word = new String();

System.out.println("LONGEST WORD: " + longest);

System.out.println("SHORTEST WORD: " + shortest);


}

}
ROWS PROGRAM
 Start

 Input matrix dimensions M and N:

 Prompt the user to input:


o M (number of rows in the matrix).
o N (number of columns in the matrix).

 Validate the dimensions:

 Check if M and N are in the range [3, 9]:


o If not, print "SIZE IS OUT OF RANGE. INVALID ENTRY." and terminate the
program.

 Input matrix elements:

 Initialize a 2D array mat[M][N].


 Prompt the user to enter M × N elements:
o Store these elements in the matrix mat.

 Display the original matrix:

 Call the display method to print the matrix in tabular form.

 Rotate the matrix rows upward:

 Store the first row of the matrix in a temporary array a[N].


 For each row starting from the second:
o Copy the elements of the row into the previous row.
 Replace the last row of the matrix with the elements of a.

 Display the rotated matrix:

 Call the display method to print the matrix after rotation.

 Find the highest element in the matrix:

 Initialize r = 0 and c = 0 to store the row and column indices of the highest
element.
 Iterate through all elements of the matrix:
o If the current element is greater than the element at mat[r][c]:
 Update r and c with the indices of the current element.

 Display the highest element:

 Print the value of the highest element along with its row and column indices.
 End
import java.util.Scanner;

class ShiftRows{

public static void main(String[] args){

Scanner in = new Scanner(System.in);

System.out.print("M = ");

int m = Integer.parseInt(in.nextLine());

System.out.print("N = ");

int n = Integer.parseInt(in.nextLine());

if(m < 3 || m > 9 || n < 3 || n > 9){

System.out.println("SIZE IS OUT OF RANGE. INVALID ENTRY.");

return;

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

int r = 0;

int c = 0;

System.out.println("ENTER ELEMENTS IN THE MATRIX:");

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

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

mat[i][j] = Integer.parseInt(in.nextLine());

System.out.println("ORIGINAL MATRIX:");

display(mat);

int a[] = new int[n];


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

a[i] = mat[0][i];

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

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

mat[i - 1][j] = mat[i][j];

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

mat[m - 1][i] = a[i];

System.out.println("FORMED MATRIX AFTER ROTATING:");

display(mat);

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

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

if(mat[i][j] > mat[r][c]){

r = i;

c = j;

System.out.print("HIGHEST ELEMENT: " + mat[r][c]);

System.out.println(" (Row: " + r + " and Column: " + c + ")");

public static void display(int mat[][]){

for(int i = 0; i < mat.length; i++){

for(int j = 0; j < mat[0].length; j++){


System.out.print(mat[i][j] + "\t");

System.out.println();

You might also like