[go: up one dir, main page]

0% found this document useful (0 votes)
26 views29 pages

Java 29

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 29

Q1

package pgms29;

//Print Kth element in an Array


import java.util.Scanner;

public class KthElementInAnArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the size of the array


System.out.print("Enter the size of the array: ");
int n = scanner.nextInt();

// Input the elements of the array


int[] array = new int[n];
System.out.println("Enter the elements of the array:");

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


array[i] = scanner.nextInt();
}

// Input the value of K


System.out.print("Enter the value of K: ");
int k = scanner.nextInt();

// Check if K is a valid index


if (k >= 0 && k <= n-1) {
// Print the Kth element in the array
int kthElement = array[k];
System.out.println("The Kth element in the array is: " + kthElement);
} else {
System.out.println("Invalid value of K. Please enter a value between 1
and " + n);
}

scanner.close();
}
}
Q2 String Palindrome

package pgms29;

import java.util.Scanner;

public class PalindromeCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the string


System.out.print("Enter a string: ");
String inputString = scanner.nextLine();

// Check if the string is a palindrome


if (isPalindrome(inputString)) {
System.out.println("The entered string is a palindrome.");
} else {
System.out.println("The entered string is not a palindrome.");
}

scanner.close();
}

// Function to check if a string is a palindrome


private static boolean isPalindrome(String str) {
// Remove spaces and convert to lowercase for case-insensitive comparison
str = str.replaceAll("\\s", "").toLowerCase();

// Reverse the string using StringBuilder


String reversedString = new StringBuilder(str).reverse().toString();

// Compare the original and reversed strings


return str.equals(reversedString);
}
}
Q3

package teach1;

public class Prime {


public static void main(String[] args) {

int num = 20;


boolean flag = false;
for (int i = 2; i <= num / 2; ++i) {
// condition for nonprime number
if (num % i == 0) {
flag = true;
break;
}
}

if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}

Q4

package teach1;
import java.util.Scanner;
public class Leap
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Enter any year:");
int year = s.nextInt();
boolean flag = false;
if(year % 400 == 0)
flag = true;
else if (year % 100 == 0)
flag = false;
else if(year % 4 == 0)
flag = true;

else
flag = false;

if(flag)
System.out.println("Year "+year+" is a Leap Year");

else
System.out.println("Year "+year+" is not a Leap Year");

}
}

Q5

package pgms29;

import java.util.Scanner;

public class Odd1toN {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the value of N


System.out.print("Enter the value of N: ");
int N = scanner.nextInt();

// Print odd numbers from 1 to N


System.out.println("Odd numbers from 1 to " + N + ":");
for (int i = 1; i <= N; i += 2) {
System.out.print(i + " ");
}

scanner.close();
}

}
Q7.

package teach;

import java.util.Scanner;

public class MatrixMultiplication {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter the number of rows for the first matrix: ");


int rowsA = input.nextInt();
System.out.print("Enter the number of columns for the first matrix: ");
int colsA = input.nextInt();

System.out.print("Enter the number of rows for the second matrix: ");


int rowsB = input.nextInt();
System.out.print("Enter the number of columns for the second matrix: ");
int colsB = input.nextInt();

if (colsA != rowsB) {
System.out.println("Matrix multiplication is not possible. Number of
columns in the first matrix must be equal to the number of rows in the second
matrix.");
input.close();
return;
}

int[][] firstMatrix = new int[rowsA][colsA];


int[][] secondMatrix = new int[rowsB][colsB];

System.out.println("Enter the elements of the first matrix:");


for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
firstMatrix[i][j] = input.nextInt();
}
}
System.out.println("Enter the elements of the second matrix:");
for (int i = 0; i < rowsB; i++) {
for (int j = 0; j < colsB; j++) {
secondMatrix[i][j] = input.nextInt();
}
}

input.close();

// Check if multiplication is possible and multiply matrices


if (colsA != rowsB) {
System.out.println("Matrix multiplication is not possible.");
} else {
int[][] resultMatrix = multiplyMatrices(firstMatrix, secondMatrix);

// Display the result


System.out.println("Result Matrix:");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
}
}

public static int[][] multiplyMatrices(int[][] firstMatrix, int[][]


secondMatrix) {
int rowsA = firstMatrix.length;
int colsA = firstMatrix[0].length;
int colsB = secondMatrix[0].length;

int[][] resultMatrix = new int[rowsA][colsB];

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


for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
resultMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}

return resultMatrix;
}
}
//

Q8

package pgms29;

import java.util.Scanner;

public class BubbleSort {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the size of the array


System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

// Input the elements of the array


int[] array = new int[size];
System.out.println("Enter the elements of the array:");

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


array[i] = scanner.nextInt();
}

// Perform bubble sort to sort the array in ascending order


bubbleSort(array);

// Display the sorted array


System.out.println("Sorted array in ascending order:");
for (int element : array) {
System.out.print(element + " ");
}

scanner.close();
}

// Function to perform Bubble Sort


private 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;
}
}
}
}
}

Q9
package pgms29;

import java.util.Scanner;

public class ReverseArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the size of the array


System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

// Input the elements of the array


int[] array = new int[size];
System.out.println("Enter the elements of the array:");

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


array[i] = scanner.nextInt();
}

// Reverse the array


reverseArray(array);

// Display the reversed array


System.out.println("Reversed array:");
for (int element : array) {
System.out.print(element + " ");
}

scanner.close();
}

// Function to reverse the elements of an array


private static void reverseArray(int[] arr) {
int start = 0;
int end = arr.length - 1;

while (start < end) {


// Swap elements at start and end indices
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;

// Move towards the center of the array


start++;
end--;
}
}
}

Q10

package teach1;

import java.util.Scanner;

public class Fibonacci {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of terms: ");


int n = scanner.nextInt();

int firstTerm = 0, secondTerm = 1;

System.out.print("Fibonacci Series: " + firstTerm + ", " + secondTerm);


for (int i = 2; i < n; i++) {
int nextTerm = firstTerm + secondTerm;
System.out.print(", " + nextTerm);
firstTerm = secondTerm;
secondTerm = nextTerm;
}

scanner.close();
}
}

Q11
package pgms29;

import java.util.Scanner;

public class RemoveDuplicatesFromArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the size of the array


System.out.print("Enter the size of the
array: ");
int size = scanner.nextInt();

// Input the elements of the array


int[] array = new int[size];
System.out.println("Enter the elements of the
array:");

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


array[i] = scanner.nextInt();
}

// Remove duplicates from the array


int[] uniqueArray = removeDuplicates(array);

// Display the result


System.out.println("Array after removing
duplicates:");
displayArray(uniqueArray);
scanner.close();
}

// Function to remove duplicates from an array


without inbuilt functions
private static int[] removeDuplicates(int[]
array) {
int size = array.length;
int uniqueCount = 0;

// Count unique elements in the array


for (int i = 0; i < size; i++) {
boolean isDuplicate = false;

// Check if the current element is a


duplicate
for (int j = 0; j < i; j++) {
if (array[i] == array[j]) {
isDuplicate = true;
break;
}
}

// If not a duplicate, increment


uniqueCount
if (!isDuplicate) {
uniqueCount++;
}
}

// Create a new array to store unique


elements
int[] uniqueArray = new int[uniqueCount];
int index = 0;

// Copy unique elements to the new array


for (int i = 0; i < size; i++) {
boolean isDuplicate = false;

// Check if the current element is a


duplicate
for (int j = 0; j < i; j++) {
if (array[i] == array[j]) {
isDuplicate = true;
break;
}
}

// If not a duplicate, add to uniqueArray


if (!isDuplicate) {
uniqueArray[index++] = array[i];
}
}

return uniqueArray;
}

// Function to display an array


private static void displayArray(int[] array) {
for (int element : array) {
System.out.print(element + " ");
}
System.out.println();
}
}

Q12

package pgms29;

import java.util.Scanner;

public class DiamondPattern {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the number of rows for the diamond


System.out.print("Enter the number of rows for the diamond: ");
int rows = scanner.nextInt();

// Print the upper half of the diamond


for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}

// Print the lower half of the diamond (excluding the central row)
for (int i = rows - 1; i >= 1; i--) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}

scanner.close();
}
}

Q13

package pgms29;

import java.util.Scanner;

public class CountEvenOdd {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the size of the array


System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

// Input the elements of the array


int[] array = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}

// Count even and odd numbers


int evenCount = 0;
int oddCount = 0;

for (int number : array) {


if (number % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}

// Display the counts


System.out.println("Number of even numbers: " + evenCount);
System.out.println("Number of odd numbers: " + oddCount);

scanner.close();
}
}

Q14

package pgms29;

import java.util.Scanner;

public class MatrixSum {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the number of rows and columns of the matrix


System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int columns = scanner.nextInt();
// Input the elements of the matrix
int[][] matrix = new int[rows][columns];
System.out.println("Enter the elements of the matrix:");

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


for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Calculate and display the sum of rows


System.out.println("Sum of rows:");
for (int i = 0; i < rows; i++) {
int rowSum = 0;
for (int j = 0; j < columns; j++) {
rowSum += matrix[i][j];
}
System.out.println("Row " + (i + 1) + ": " + rowSum);
}

// Calculate and display the sum of columns


System.out.println("Sum of columns:");
for (int j = 0; j < columns; j++) {
int columnSum = 0;
for (int i = 0; i < rows; i++) {
columnSum += matrix[i][j];
}
System.out.println("Column " + (j + 1) + ": " + columnSum);
}

scanner.close();
}
}

Q21
import java.util.Scanner;

public class HollowRhombus {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the number of rows for the rhombus


System.out.print("Enter the number of rows for the hollow rhombus: ");
int rows = scanner.nextInt();

// Print the hollow rhombus pattern


for (int i = 1; i <= rows; i++) {
// Print spaces for the current row
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}

// Print stars for the first and last rows


if (i == 1 || i == rows) {
for (int j = 1; j <= rows; j++) {
System.out.print("*");
}
} else {
// Print stars and spaces for the middle rows
for (int j = 1; j <= rows; j++) {
if (j == 1 || j == rows) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}

System.out.println();
}

scanner.close();
}
}

Q22
import java.util.Scanner;

public class RhombusPattern {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the number of rows for the rhombus


System.out.print("Enter the number of rows for the rhombus: ");
int rows = scanner.nextInt();

// Print the rhombus pattern


for (int i = 1; i <= rows; i++) {
// Print spaces for the current row
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}

// Print stars for the current row


for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}

System.out.println();
}

for (int i = rows - 1; i >= 1; i--) {


// Print spaces for the current row
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}

// Print stars for the current row


for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}

System.out.println();
}

scanner.close();
}
}

Q26
public class PrimeNumbers {
public static void main(String[] args) {
System.out.println("Prime numbers between 1 and 100:");

for (int i = 2; i <= 100; i++) {


if (isPrime(i)) {
System.out.print(i + " ");
}
}
}

// Function to check if a number is prime


private static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}

Q15
package pgms29;

import java.util.Scanner;

public class SecondLargestArray{


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the size of the array


System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

// Input the elements of the array


int[] array = new int[size];
System.out.println("Enter the elements of the array:");

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


array[i] = scanner.nextInt();
}

// Find the second largest number


int firstLargest = 0;

int secondLargest = 0;

for (int number : array) {


if (number > firstLargest) {
secondLargest = firstLargest;
firstLargest = number;
} else if (number > secondLargest && number != firstLargest) {
secondLargest = number;
}
}

// Display the second largest number


if (secondLargest == 0) {
System.out.println("No second largest element exists.");
} else {
System.out.println("The second largest element is: " + secondLargest);
}

scanner.close();
}
}

Q16
import java.util.Scanner;

public class SymmetricMatrix {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the order of the square matrix


System.out.print("Enter the order of the square matrix: ");
int order = scanner.nextInt();

// Input the elements of the matrix


int[][] matrix = new int[order][order];
System.out.println("Enter the elements of the matrix:");

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


for (int j = 0; j < order; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Check if the matrix is symmetric


if (isSymmetric(matrix, order)) {
System.out.println("The matrix is symmetric.");
} else {
System.out.println("The matrix is not symmetric.");
}

scanner.close();
}

// Function to check if a matrix is symmetric


private static boolean isSymmetric(int[][] matrix, int order) {
for (int i = 0; i < order; i++) {
for (int j = 0; j < order; j++) {
// Check if the element at (i, j) is equal to the element at (j, i)
if (matrix[i][j] != matrix[j][i]) {
return false;
}
}
}
return true;
}
}

Q17

package pgms29;

import java.util.Scanner;

public class WordCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the string


System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
// Count the total number of words
int wordCount = countWords(inputString);

// Display the result


System.out.println("Total number of words in the string: " + wordCount);

scanner.close();
}

// Function to count the total number of words in a string without using


inbuilt functions
private static int countWords(String str) {
int wordCount = 0;
boolean inWord = false;

// Iterate through each character in the string


for (int i = 0; i < str.length(); i++) {
char currentChar = str.charAt(i);

// Check if the current character is a whitespace


if (Character.isWhitespace(currentChar)) {
// If we were in a word, increment the word count
if (inWord) {
wordCount++;
inWord = false;
}
} else {
// We are in a word
inWord = true;

// If we are at the end of the string, increment the word count


if (i == str.length() - 1) {
wordCount++;
}
}
}

return wordCount;
}
}
Q29 and Q6
package pgms29;
import java.util.Scanner;

public class Lcm {

// Function to find the GCD (Greatest Common Divisor)


private static int findGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}System.out.println("GCD = " + a);

return a;
}

// Function to find the LCM (Least Common Multiple)


private static int findLCM(int a, int b) {
return (a * b) / findGCD(a, b);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");


int num1 = scanner.nextInt();

System.out.print("Enter the second number: ");


int num2 = scanner.nextInt();

// Calculate and display the LCM


int lcm = findLCM(num1, num2);
System.out.println("LCM = " + lcm);

scanner.close();
}
}

Q19
package pgms29;

import java.util.Scanner;

public class SquareRoot {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input a number
System.out.print("Enter a number: ");
double number = scanner.nextDouble();

// Calculate and display the square root


if (number >= 0) {
double squareRoot = Math.sqrt(number);
System.out.println("Square root of " + number + " is: " + squareRoot);
} else {
System.out.println("Cannot calculate square root of a negative
number.");
}

scanner.close();
}
}

Q20

package teach1;

import java.util.Scanner;
public class ArmstrongNumber {
public static void main(String[] args) {
int a,b = 0,
temp,
n,
num;
Scanner sc = new Scanner(System. in );

System.out.println("Enter the value of n: ");


n = sc.nextInt();
for (int i = 1; i <= n; i++) {
num = i;
b = 0;
while (num > 0) {
a = num%10;
b = b + (a * a * a);
num = num / 10;
}
if (i == b) System.out.println(i);
}
}
}

Q28
package teach1;

import java.util.Scanner;

public class Factorial{


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");


int n = scanner.nextInt();

int factorial = 1;
int i = 1;

do {
factorial *= i;

i++;
} while (i <= n);

System.out.println("Factorial of " + n + ": " + factorial);

scanner.close();
}
}
Q25

package pgms29;

public class MaxMin {


public static void main(String[] args) {
int[] array = {3, 7, 2, 8, 5, 1, 9, 4, 6};

// Find first maximum and minimum in the array


int max = array[0], min = array[0];

for (int num : array) {


if (num > max) {
max = num;
} else if (num < min) {
min = num;
}
}

// Display the results


System.out.println("First Maximum: " + max);
System.out.println("First Minimum: " + min);
}
}

Q23

package pgms29;

import java.util.Arrays;

public class SwapArrayWithoutTemp {


public static void main(String[] args) {
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {6, 7, 8, 9, 10};

System.out.println("Before swapping:");
System.out.println("Array1: " + Arrays.toString(array1));
System.out.println("Array2: " + Arrays.toString(array2));
// Swap arrays without using a temporary variable
for (int i = 0; i < array1.length; i++) {
array1[i] = array1[i] + array2[i];
array2[i] = array1[i] - array2[i];
array1[i] = array1[i] - array2[i];
}

System.out.println("\nAfter swapping:");
System.out.println("Array1: " + Arrays.toString(array1));
System.out.println("Array2: " + Arrays.toString(array2));
}
}

Q27

package pgms29;

import java.util.Scanner;

public class MatrixTranspose {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the number of rows and columns of the matrix


System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int columns = scanner.nextInt();

// Input the elements of the matrix


int[][] matrix = new int[rows][columns];
System.out.println("Enter the elements of the matrix:");

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


for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Transpose the matrix


int[][] transposedMatrix = transposeMatrix(matrix, rows, columns);
// Display the original matrix
System.out.println("Original Matrix:");
displayMatrix(matrix, rows, columns);

// Display the transposed matrix


System.out.println("Transposed Matrix:");
displayMatrix(transposedMatrix, columns, rows);

scanner.close();
}

// Function to transpose a matrix without inbuilt functions


private static int[][] transposeMatrix(int[][] matrix, int rows, int columns) {
int[][] resultMatrix = new int[columns][rows];

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


for (int j = 0; j < columns; j++) {
resultMatrix[j][i] = matrix[i][j];
}
}

return resultMatrix;
}

// Function to display a matrix


private static void displayMatrix(int[][] matrix, int rows, int columns) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

Q24
package pgms29;

import java.util.Scanner;

public class CountArrayDuplicate {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the size of the array


System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

// Input the elements of the array


int[] array = new int[size];
System.out.println("Enter the elements of the array:");

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


array[i] = scanner.nextInt();
}

// Count duplicates in the array


int duplicateCount = countDuplicates(array);

// Display the result


System.out.println("Number of duplicates in the array: " +
duplicateCount);

scanner.close();
}

// Function to count duplicates in an array without inbuilt functions


private static int countDuplicates(int[] array) {
int duplicateCount = 0;

// Iterate through each element in the array


for (int i = 0; i < array.length - 1; i++) {
// Check for duplicates starting from the next element
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) {
duplicateCount++;
break; // Break to avoid counting the same duplicate multiple times
}
}
}

return duplicateCount;
}
}

You might also like