Challenging Java programs and succeeding in coding interviews-4

Write a program that takes a string as input and checks if it is a palindrome

import java.util.Scanner;

public class javatechypid {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      
      System.out.print("Enter a string: ");
      String str = input.nextLine();
      
      boolean isPalindrome = true;
      int n = str.length();
      for (int i = 0; i < n/2; i++) {
         if (str.charAt(i) != str.charAt(n-i-1)) {
            isPalindrome = false;
            break;
         }
      }
      
      if (isPalindrome) {
         System.out.println(str + " is a palindrome.");
      } else {
         System.out.println(str + " is not a palindrome.");
      }
   }
}

Output:

Enter a string: techypid
techypid is not a palindrome.

Enter a string: madam
madam is a palindrome.

Explanation of above java code:

The above Java program checks whether a given string is a palindrome or not. A palindrome is a word, phrase, or sequence of characters that reads the same backwards as forwards.

Here’s how the program works:

A boolean variable named “isPalindrome” is declared and initialized to true.

The program determines the length of the input string using the length() method and stores it in a variable called “n”.

The program uses a for loop to iterate through the first half of the string (up to n/2 characters). For each character at index i, the program checks whether the character at the corresponding position in the second half of the string (n-i-1) is the same. If it is not the same, the “isPalindrome” variable is set to false and the loop is terminated using the “break” statement.

After the loop, the program uses an if-else statement to check whether “isPalindrome” is true or false. If it is true, the program prints “str is a palindrome.” If it is false, the program prints “str is not a palindrome.”

Write a program that takes two matrices as input and calculates:

import java.util.Scanner;

public class javatechypid {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      
      System.out.print("Enter the number of rows in the first matrix: ");
      int n1 = input.nextInt();
      System.out.print("Enter the number of columns in the first matrix: ");
      int m1 = input.nextInt();
      
      int[][] mat1 = new int[n1][m1];
      System.out.println("Enter the elements of the first matrix:");
      for (int i = 0; i < n1; i++) {
         for (int j = 0; j < m1; j++) {
            mat1[i][j] = input.nextInt();
         }
      }
      
      System.out.print("Enter the number of rows in the second matrix: ");
      int n2 = input.nextInt();
      System.out.print("Enter the number of columns in the second matrix: ");
      int m2 = input.nextInt();
      
      int[][] mat2 = new int[n2][m2];
      System.out.println("Enter the elements of the second matrix:");
      for (int i = 0; i < n2; i++) {
         for (int j = 0; j < m2; j++) {
            mat2[i][j] = input.nextInt();
         }
      }
      
      if (m1 != n2) {
         System.out.println("Error: The matrices cannot be multiplied.");
         return;
      }
      
      int[][] result = new int[n1][m2];
      for (int i = 0; i < n1; i++) {
         for (int j = 0; j < m2; j++) {
            int sum = 0;
            for (int k = 0; k < m1; k++) {
               sum += mat1[i][k] * mat2[k][j];
            }
            result[i][j] = sum;
         }
      }
      
      System.out.println("The product of the matrices is:");
      for (int i = 0; i < n1; i++) {
         for (int j = 0; j < m2; j++) {
            System.out.print(result[i][j] + " ");
         }
         System.out.println();
      }
   }
}

Output:

Enter the number of rows in the first matrix: 2
Enter the number of columns in the first matrix: 3
Enter the elements of the first matrix:
1
2
3
4
5
6
Enter the number of rows in the second matrix: 3
Enter the number of columns in the second matrix: 2
Enter the elements of the second matrix:
7
8
9
10
11
12
The product of the matrices is:
58 64
139 154

Explanation of above java code:

The program performs matrix multiplication of two matrices entered by the user.

First, the user is prompted to enter the number of rows and columns for the first matrix, and the elements of the matrix are taken as input. Similarly, the user is prompted to enter the number of rows and columns for the second matrix, and the elements of the matrix are taken as input.

Next, the program checks whether the number of columns in the first matrix is equal to the number of rows in the second matrix. If they are not equal, the matrices cannot be multiplied, and an error message is displayed.

Next, the program checks whether the number of columns in the first matrix is equal to the number of rows in the second matrix. If they are not equal, the matrices cannot be multiplied, and an error message is displayed.

Finally, the program prints the product matrix result to the console. The output shows the product matrix in the form of a matrix, where each row is printed on a separate line and the elements of each row are separated by spaces.

Write a program that takes a string as input and finds the most frequent character

import java.util.HashMap;
import java.util.Scanner;

public class javatechypid {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      
      System.out.print("Enter a string: ");
      String str = input.nextLine();
      
      HashMap<Character, Integer> frequencyMap = new HashMap<Character, Integer>();
      for (int i = 0; i < str.length(); i++) {
         char c = str.charAt(i);
         if (frequencyMap.containsKey(c)) {
            frequencyMap.put(c, frequencyMap.get(c)+1);
         } else {
            frequencyMap.put(c, 1);
         }
      }
      
      char mostFrequentChar = ' ';
      int maxFrequency = 0;
      for (char c : frequencyMap.keySet()) {
         int frequency = frequencyMap.get(c);
         if (frequency > maxFrequency) {
            mostFrequentChar = c;
            maxFrequency = frequency;
         }
      }
      
      System.out.println("The most frequent character in the string is: " + mostFrequentChar);
   }
}

Output:

Enter a string: techypid
The most frequent character in the string is: p

Explanation of above java code:

This program takes a string input from the user and finds the most frequent character in the string using a HashMap.

A HashMap is created to store the frequency of each character in the string. The program iterates through each character of the string and checks whether it already exists in the HashMap. If it does, the count for that character is incremented by 1. If it does not exist, a new key-value pair is added to the map, with the character as the key and a value of 1.

Once the frequency map has been populated, the program iterates through the keys in the map to find the character with the highest frequency. It does this by comparing the frequency of each character to the current maximum frequency. If the frequency of a character is higher than the current maximum, that character becomes the new most frequent character.

Finally, the program outputs the most frequent character in the string to the console.

Write a program that takes a number as input and checks if it is a prime number

How to Find Prime number between 1 to 100.

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
are prime numbers

import java.util.Scanner;

public class javatechypid {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      
      System.out.print("Enter a number: ");
      int n = input.nextInt();
      
      boolean isPrime = true;
      if (n < 2) {
         isPrime = false;
      } else {
         for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
               isPrime = false;
               break;
            }
         }
      }
      
      if (isPrime) {
         System.out.println(n + " is a prime number.");
      } else {
         System.out.println(n + " is not a prime number.");
      }
   }
}

Output:

Enter a number: 5
5 is a prime number.

Enter a number: 10
10 is not a prime number.

Explanation of above java code:

This Java program determines whether a given input number is a prime number or not.

The program uses an if-else statement to check whether the input number is less than 2. If the number is less than 2, then it is not prime, so the “isPrime” variable is set to false. Otherwise, the program proceeds to check if the number is prime using a for loop.

Therefore, the output of the program will depend on the user’s input. If the input number is a prime number, the program will print a message indicating that it is a prime number. If it is not a prime number, the program will print a message indicating that it is not a prime number.

Leave a Reply