Challenging Java programs and succeeding in coding interviews-3

Write a program that takes an integer as input and prints all prime numbers between 1 and the input integer

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 num = input.nextInt();
      
      System.out.println("Prime numbers between 1 and " + num + ":");
      for (int i = 2; i <= num; i++) {
         boolean isPrime = true;
         for (int j = 2; j <= Math.sqrt(i); j++) {
            if (i % j == 0) {
               isPrime = false;
               break;
            }
         }
         if (isPrime) {
            System.out.print(i + " ");
         }
      }
   }
}

Output:

Enter a number: 10
Prime numbers between 1 and 10:
2 3 5 7

Explanation of above java code:

This Java program prompts the user to enter a number and then outputs all the prime numbers between 1 and the entered number.

The program uses a nested for loop to iterate through all the numbers between 2 and the entered number. The outer loop iterates through the numbers, and the inner loop checks whether each number is prime.

Inside the inner loop, the program declares a boolean variable named “isPrime” and initializes it to true. The inner loop then checks whether each number between 2 and the square root of the current number divides the current number evenly. If any of these numbers divide the current number evenly, then the current number is not prime and the “isPrime” variable is set to false. If the number is prime, the “isPrime” variable remains true.

After the inner loop completes, the program checks whether the “isPrime” variable is true. If it is true, then the current number is prime and the program outputs it using the System.out.print() method.

The program repeats steps 6-8 for each number between 2 and the entered number.

Once all the prime numbers between 1 and the entered number have been output, the program terminates.

Therefore, the output of the program will depend on the user’s input. For example, if the user enters 10, the program will output: “Prime numbers between 1 and 10: 2 3 5 7”. This is because 2, 3, 5, and 7 are the prime numbers between 1 and 10.

Write a program that takes an array of integers as input and finds the second largest number in the array

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 elements in the array: ");
      int n = input.nextInt();
      
      int[] arr = new int[n];
      System.out.println("Enter the elements of the array:");
      for (int i = 0; i < n; i++) {
         arr[i] = input.nextInt();
      }
      
      int largest = arr[0], secondLargest = arr[0];
      for (int i = 1; i < n; i++) {
         if (arr[i] > largest) {
            secondLargest = largest;
            largest = arr[i];
         } else if (arr[i] > secondLargest && arr[i] != largest) {
            secondLargest = arr[i];
         }
      }
      
      System.out.println("The second largest number in the array is " + secondLargest + ".");
   }
}

Output:

Enter the number of elements in the array: 10
Enter the elements of the array:
8
6
4
3
1
0
9
6
5
2
The second largest number in the array is 8.

Explanation of above java code:

This Java program finds the second largest number in an array of integers input by the user.

First, the program prompts the user to enter the number of elements in the array and reads the input using a Scanner object.

Then, an integer array of size n is created and initialized with elements entered by the user using a for loop.

Two variables named “largest” and “secondLargest” are created and initialized to the first element of the array.

A for loop is used to traverse the array and compare each element with the current value of “largest” and “secondLargest”.

If the current element is greater than “largest”, the value of “largest” is assigned to “secondLargest” and the current element is assigned to “largest”.

If the current element is greater than “secondLargest” but less than “largest”, the value of “secondLargest” is updated.

Finally, the program prints the value of “secondLargest”, which is the second largest element in the array.

Write a program that takes a sentence as input and capitalizes the first letter of each word

import java.util.Scanner;

public class javatechypid {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      
      System.out.print("Enter a sentence: ");
      String sentence = input.nextLine();
      
      String[] words = sentence.split(" ");
      String capitalizedSentence = "";
      for (String word : words) {
         if (!word.isEmpty()) {
            String firstLetter = word.substring(0, 1);
            String restOfWord = word.substring(1);
            capitalizedSentence += firstLetter.toUpperCase() + restOfWord.toLowerCase() + " ";
         }
      }
      
      System.out.println("The capitalized sentence is: " + capitalizedSentence.trim());
   }
}

Output:

Enter a sentence: techy pid
The capitalized sentence is: Techy Pid

Explanation of above java code:

The Java program above prompts the user to input a sentence, then capitalizes the first letter of each word in the sentence and converts the remaining letters to lowercase. Finally, it outputs the capitalized sentence.

The program splits the sentence into an array of words using the split() method with a space delimiter. The resulting array is stored in the “words” variable.

A variable named “capitalizedSentence” is created to store the resulting capitalized sentence.

The program starts a for-each loop to iterate through each word in the “words” array.

Inside the loop, the program checks if the current word is not empty using the String method isEmpty(). If the word is not empty, it capitalizes the first letter of the word and converts the remaining letters to lowercase using the String methods substring(), toUpperCase(), and toLowerCase(). The resulting capitalized word is appended to the “capitalizedSentence” variable along with a space.

After iterating through all words in the sentence, the program trims any extra whitespace from the beginning or end of the “capitalizedSentence” variable using the String method trim().

Finally, the program outputs the capitalized sentence using the System.out.println() method.

Therefore, the output of the program will be the capitalized sentence, where the first letter of each word in the input sentence is capitalized and the rest of the letters are converted to lowercase.

Leave a Reply