Videos
-
Write a program in Java to accept 10 integers into a one-dimensional array. Sort the array using Selection Sort and display the sorted array. answer
import java.util.Scanner;
public class SortArray { private int[] arr = new int[10];
// Method to accept values into the array
public void acceptValues() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 10 integers:");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
}
// Method to perform selection sort
public void selectionSort() {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
// Method to display the sorted array
public void displaySortedArray() {
System.out.println("Sorted Array in Ascending Order:");
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] args) {
SortArray obj = new SortArray();
obj.acceptValues();
obj.selectionSort();
obj.displaySortedArray();
}}
2. Write a Java program to accept 9 integers Into a 3x3 array. Check whether the array is a special array where the sum of diagonal elements is equal to the sum of the non-diagonal elements. answer import java.util.Scanner;
public class SpecialArray { private int[][] arr = new int[3][3];
// Method to accept values into the array
public void acceptValues() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 9 integers for a 3x3 array:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
arr[i][j] = sc.nextInt();
}
}
}
// Method to check if it is a special array
public void checkSpecialArray() {
int diagonalSum = arr[0][0] + arr[1][1] + arr[2][2];
int totalSum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
totalSum += arr[i][j];
}
}
if (diagonalSum == (totalSum - diagonalSum)) {
System.out.println("It is a special array.");
} else {
System.out.println("It is not a special array.");
}
}
public static void main(String[] args) {
SpecialArray obj = new SpecialArray();
obj.acceptValues();
obj.checkSpecialArray();
}}
3. Design a class Student in Java to store the name, age, marks, and stream of a student. Implement methods to accept and display the student details. answer import java.util.Scanner;
public class Student { // Data members String name; int age; int marks; String stream;
// Method to accept data
public void acceptData() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
name = sc.nextLine();
System.out.print("Enter age: ");
age = sc.nextInt();
System.out.print("Enter marks: ");
marks = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Enter stream: ");
stream = sc.nextLine();
}
// Method to display data
public void displayData() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Marks: " + marks);
System.out.println("Stream: " + stream);
}
public static void main(String[] args) {
Student student = new Student();
student.acceptData();
student.displayData();
}}
4. Write a Java program to accept 25 integers into an array. Input a value from the user and search for the value in the array, displaying its position. If the value is not found, display an appropriate message. answer import java.util.Scanner;
public class SearchValue { private int[] arr = new int[25];
// Method to accept values into the array
public void acceptValues() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 25 integers:");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
}
// Method to search for a value and display position
public void searchValue(int key) {
boolean found = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) {
System.out.println("Found " + key + " at position: " + (i + 1));
found = true;
break;
}
}
if (!found) {
System.out.println("Value not found in the array.");
}
}
public static void main(String[] args) {
SearchValue obj = new SearchValue();
obj.acceptValues();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value to search: ");
int key = sc.nextInt();
obj.searchValue(key);
}}
5. Write a Java program to:
-
Print Floyd's Triangle for a given number of rows.
-
Display the following pattern for a given number of rows:
I I I C S E I I I C S E
answer import java.util.Scanner;
public class Patterns { // Method to print Floyd's Triangle public void floydsTriangle(int n) { int num = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print(num + " "); num++; } System.out.println(); } }
// Method to display the pattern
public void displayPattern(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("I ");
}
System.out.println("C S E");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Patterns obj = new Patterns();
System.out.println("Menu:");
System.out.println("1. Print Floyd's Triangle");
System.out.println("2. Display Pattern");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter the number of rows: ");
int rows = sc.nextInt();
obj.floydsTriangle(rows);
break;
case 2:
System.out.print("Enter the number of rows for the pattern: ");
int n = sc.nextInt();
obj.displayPattern(n);
break;
default:
System.out.println("Invalid choice.");
}
}}
6. Write a Java program to accept a country name from the user and display the corresponding Wonder of the World from a predefined list. If the country is not in the list, display an appropriate message. answer import java.util.Scanner;
public class SevenWonders { // List of wonders and corresponding countries String[] wonders = {"CHRIST THE REDEEMER", "TAJ MAHAL", "GREAT WALL OF CHINA", "MACHU PICCHU", "PETRA", "COLOSSEUM"}; String[] countries = {"BRAZIL", "INDIA", "CHINA", "PERU", "JORDAN", "ITALY"};
// Method to find the wonder by country
public void findWonder(String country) {
boolean found = false;
for (int i = 0; i < countries.length; i++) {
if (countries[i].equalsIgnoreCase(country)) {
System.out.println("Wonder: " + wonders[i] + ", Country: " + countries[i]);
found = true;
break;
}
}
if (!found) {
System.out.println("Sorry, wonder not found for the given country.");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SevenWonders obj = new SevenWonders();
System.out.print("Enter a country name: ");
String country = sc.nextLine();
obj.findWonder(country);
}}
7. Design a class Movie in Java with attributes year, title, and rating. Implement methods to accept and display movie details. answerimport java.util.Scanner;
public class Movie { int year; String title; double rating;
// Default constructor
public Movie() {
year = 0;
title = "";
rating = 0.0;
}
// Method to accept movie details
public void acceptDetails() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter movie title: ");
title = sc.nextLine();
System.out.print("Enter year of release: ");
year = sc.nextInt();
System.out.print("Enter movie rating (1.0 to 5.0): ");
rating = sc.nextDouble();
}
// Method to display movie details
public void displayDetails() {
System.out.println("Movie Title: " + title);
System.out.println("Year of Release: " + year);
System.out.println("Rating: " + rating);
}
public static void main(String[] args) {
Movie obj = new Movie();
obj.acceptDetails();
obj.displayDetails();
}}
8. Write a Java program to accept the name and salary of 3 employees. Display the details of the employee with the highest salary. answer import java.util.Scanner;
public class Employee { String name; int salary;
// Default constructor
public Employee() {
name = "";
salary = 0;
}
// Method to accept employee details
public void acceptDetails() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter employee name: ");
name = sc.nextLine();
System.out.print("Enter employee salary: ");
salary = sc.nextInt();
}
// Method to find the employee with the highest salary
public static void findHighest(Employee[] empArray) {
Employee highest = empArray[0];
for (Employee emp : empArray) {
if (emp.salary > highest.salary) {
highest = emp;
}
}
System.out.println("Employee with the highest salary: " + highest.name + " (" + highest.salary + ")");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Employee[] employees = new Employee[3];
// Accepting details of 3 employees
for (int i = 0; i < employees.length; i++) {
employees[i] = new Employee();
System.out.println("Enter details for employee " + (i + 1) + ":");
employees[i].acceptDetails();
}
// Find and display the employee with the highest salary
findHighest(employees);
}}
9. The weekly hours of all employees of ABC Consulting Ltd. are stored in a two-dimensional array. Each row records an employee's 7-day work hours with seven columns. For example, the following array stores the work hours of five employees. Write a program that displays employees and their total hours in decreasing order of the total hours.
| S. No. | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|---|---|---|---|---|---|---|---|
| Employee 0 | 8 | 5 | 1 | 11 | 1 | 0 | 0 |
| Employee 1 | 11 | 6 | 0 | 2 | 2 | 2 | 4 |
| Employee 2 | 4 | 5 | 4 | 10 | 4 | 3 | 1 |
| Employee 3 | 4 | 7 | 3 | 12 | 6 | 2 | 0 |
| Employee 4 | 3 | 8 | 3 | 2 | 4 | 4 | 0 |
| answer | |||||||
| import java.util.Arrays; | |||||||
| import java.util.Comparator; |
public class EmployeeHours { public static void main(String[] args) { int[][] hours = { {8, 5, 1, 11, 1, 0, 0}, // Employee 0 {11, 6, 0, 2, 2, 2, 4}, // Employee 1 {4, 5, 4, 10, 4, 3, 1}, // Employee 2 {4, 7, 3, 12, 6, 2, 0}, // Employee 3 {3, 8, 3, 2, 4, 4, 0} // Employee 4 };
int[][] totalHours = new int[hours.length][2];
// Calculate total hours for each employee
for (int i = 0; i < hours.length; i++) {
int sum = 0;
for (int j = 0; j < hours[i].length; j++) {
sum += hours[i][j];
}
totalHours[i][0] = i; // Employee number
totalHours[i][1] = sum; // Total hours
}
// Sort by total hours in decreasing order
Arrays.sort(totalHours, (a, b) -> Integer.compare(b[1], a[1]));
// Display employees and their total hours
System.out.println("Employee\tTotal Hours");
for (int i = 0; i < totalHours.length; i++) {
System.out.println("Employee " + totalHours[i][0] + "\t\t" + totalHours[i][1]);
}
}}
10. Write a program that reads a 4 x 5 two-dimensional array and then prints the column sums of the array along with the array printed in matrix form. answer import java.util.Scanner;
public class MatrixColumnSum { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[][] matrix = new int[4][5];
// Reading the matrix
System.out.println("Enter the elements of the 4x5 matrix:");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
matrix[i][j] = sc.nextInt();
}
}
// Printing the matrix
System.out.println("Matrix:");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
// Calculating and printing column sums
System.out.println("Column sums:");
for (int j = 0; j < 5; j++) {
int sum = 0;
for (int i = 0; i < 4; i++) {
sum += matrix[i][j];
}
System.out.println("Column " + (j + 1) + ": " + sum);
}
}}
11. A palindromic prime is a prime number and also palindromic. For example, 131, 313, and 757 are prime numbers and also palindromic prime numbers. Write a program that displays the first 100 palindromic prime numbers. answer public class PalindromicPrime { public static boolean isPrime(int num) { if (num < 2) return false; for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) return false; } return true; }
public static boolean isPalindrome(int num) {
String str = Integer.toString(num);
return str.equals(new StringBuilder(str).reverse().toString());
}
public static void main(String[] args) {
int count = 0;
int num = 2;
System.out.println("First 100 Palindromic Prime Numbers:");
while (count < 100) {
if (isPrime(num) && isPalindrome(num)) {
System.out.print(num + " ");
count++;
}
num++;
}
}}
12. Write a program in Java to read a number, remove all zeros from it, and display the new number. For example:
Sample Input: 45407703
Sample Output: 454773 answer import java.util.Scanner;
public class RemoveZeros { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); String number = sc.nextLine();
String result = number.replace("0", "");
System.out.println("New number: " + result);
}}
13. Define a class to accept values in an integer array of size 10 and perform a binary search on it. answer import java.util.Arrays; import java.util.Scanner;
public class BinarySearchArray { public static int binarySearch(int[] arr, int key) { int low = 0, high = arr.length - 1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == key) return mid; else if (arr[mid] < key) low = mid + 1; else high = mid - 1; } return -1; }
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[10];
// Accept array values
System.out.println("Enter 10 integers:");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
// Sort the array
Arrays.sort(arr);
// Search for a number
System.out.print("Enter the number to search: ");
int key = sc.nextInt();
int index = binarySearch(arr, key);
if (index != -1) {
System.out.println("Number found at position: " + (index + 1));
} else {
System.out.println("Number not found.");
}
}}
14. Write a program to input a sentence and convert it into uppercase and count and display the total number of words starting with the letter 'A'.
Example:
Sample Input: ADVANCEMENT AND APPLICATION OF INFORMATION TECHNOLOGY ARE EVER CHANGING.
Sample Output: Total number of words starting with letter 'A' = 4. answer import java.util.Scanner;
public class CountWordsWithA { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a sentence: "); String sentence = sc.nextLine().toUpperCase();
String[] words = sentence.split(" ");
int count = 0;
for (String word : words) {
if (word.startsWith("A")) {
count++;
}
}
System.out.println("Total number of words starting with 'A': " + count);
}}
15. Define a class to accept values in an integer array of size 10. Sort them in ascending order using the bubble sort technique. Display the sorted array. answer import java.util.Scanner;
public class BubbleSortArray { public static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap arr[j] and arr[j+1] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[10];
// Accept array values
System.out.println("Enter 10 integers:");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
// Sort the array
bubbleSort(arr);
// Display sorted array
System.out.println("Sorted array:");
for (int i : arr) {
System.out.print(i + " ");
}
}}