import java.util.Scanner;
public class AddTwoNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1, num2, sum;
System.out.print("Enter the first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
sum = num1 + num2;
System.out.println("The sum is: " + sum);
input.close();
}
}
3. Write a Java program to find the largest among three numbers.
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1, num2, num3, largest;
System.out.print("Enter the first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
System.out.print("Enter the third number: ");
num3 = input.nextInt();
largest = (num1 > num2) ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
System.out.println("The largest number is: " + largest);
input.close();
}
}
4. Write a Java program to check if a number is prime or not.
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
boolean isPrime = true;
System.out.print("Enter a number: ");
num = input.nextInt();
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
input.close();
}
}
5. Write a Java program to print the Fibonacci series up to a given number.
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n, t1 = 0, t2 = 1;
System.out.print("Enter the number of terms: ");
n = input.nextInt();
System.out.print("Fibonacci series up to " + n + " terms: ");
for (int i = 1; i <= n; i++) {
System.out.print(t1 + " ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
input.close();
}
}
6. Write a Java program to reverse a string.
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String original, reverse = "";
System.out.print("Enter a string: ");
original = input.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--) {
reverse += original.charAt(i);
}
System.out.println("The reverse of the string is: " + reverse);
input.close();
}
}
This program prompts the user to enter a string and reads the input using a Scanner object. It then uses a for loop to iterate through the string in reverse order and concatenate each character to a new string called reverse. Finally, it prints the reversed string to the console.
7. Write a Java program to sort an array in ascending order.
import java.util.Scanner;
public class SortArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int size;
System.out.print("Enter the size of the array: ");
size = input.nextInt();
int[] arr = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = input.nextInt();
}
// Bubble sort algorithm
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("The sorted array in ascending order is:");
for (int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
input.close();
}
}
This program prompts the user to enter the size of the array and the elements of the array. It then uses the bubble sort algorithm to sort the array in ascending order. The sorted array is then printed to the console.
8. Write a Java program to find the factorial of a number.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num, fact = 1;
System.out.print("Enter a number: ");
num = input.nextInt();
for (int i = 1; i <= num; i++) {
fact *= i;
}
System.out.println("The factorial of " + num + " is: " + fact);
input.close();
}
}
This program prompts the user to enter a number and reads the input using a Scanner object. It then uses a for loop to calculate the factorial of the number by multiplying all the integers from 1 to the number. Finally, it prints the factorial to the console.
9. Write a Java program to check if a given string is a palindrome or not.
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String original, reverse = "";
System.out.print("Enter a string: ");
original = input.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--) {
reverse += original.charAt(i);
}
if (original.equals(reverse)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
input.close();
}
}
This program prompts the user to enter a string and reads the input using a Scanner object. It then uses a for loop to reverse the string and stores the reversed string in a new string called reverse. Finally, it compares the original string with the reversed string using the equals() method and prints whether the string is a palindrome or not.
10. Write a Java program to convert temperature from Fahrenheit to Celsius.
import java.util.Scanner;
public class FahrenheitToCelsius {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double fahrenheit, celsius;
System.out.print("Enter temperature in Fahrenheit: ");
fahrenheit = input.nextDouble();
celsius = (fahrenheit - 32) * 5 / 9;
System.out.printf("%.2f Fahrenheit = %.2f Celsius", fahrenheit, celsius);
input.close();
}
}
This program prompts the user to enter the temperature in Fahrenheit and reads the input using a Scanner object. It then uses the formula (Fahrenheit - 32) * 5 / 9 to convert the temperature to Celsius and stores the result in the variable celsius. Finally, it prints the original temperature in Fahrenheit and the converted temperature in Celsius to the console using the printf() method. The %.2f specifier is used to print the values up to two decimal places.
11. Write a Java program to calculate the area of a circle.
import java.util.Scanner;
public class CircleArea {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double radius, area;
System.out.print("Enter the radius of the circle: ");
radius = input.nextDouble();
area = Math.PI * radius * radius;
System.out.printf("The area of the circle is: %.2f", area);
input.close();
}
}
This program prompts the user to enter the radius of the circle and reads the input using a Scanner object. It then uses the formula pi * r^2 to calculate the area of the circle, where pi is the mathematical constant Pi and r is the radius of the circle. The Math.PI method is used to get the value of Pi. Finally, it prints the area of the circle to the console using the printf() method. The %.2f specifier is used to print the value up to two decimal places.
12. Write a Java program to implement a binary search algorithm.
import java.util.Arrays;
import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] array = { 3, 6, 9, 12, 15, 18, 21, 24, 27, 30 };
System.out.print("Enter the value to be searched: ");
int searchValue = input.nextInt();
int index = binarySearch(array, searchValue);
if (index == -1) {
System.out.println("Value not found in the array.");
} else {
System.out.println("Value found at index: " + index);
}
input.close();
}
public static int binarySearch(int[] array, int searchValue) {
int low = 0;
int high = array.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (array[mid] == searchValue) {
return mid;
} else if (array[mid] < searchValue) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}
This program implements a binary search algorithm to search for a value in a sorted array of integers. The array is first initialized with some values. The user is then prompted to enter the value to be searched using a Scanner object. The binarySearch() method is then called with the array and the search value as arguments. The method returns the index of the search value if it is found in the array, or -1 if it is not found.
The binarySearch() method uses a while loop to search for the value in the array. It first initializes the low and high variables to the first and last indices of the array, respectively. It then repeatedly calculates the mid index by averaging the low and high indices, and checks if the value at the mid index is equal to the search value. If it is, the method returns the mid index. If not, it checks if the value at the mid index is less than the search value. If it is, the low index is updated to mid + 1 and the loop continues. Otherwise, the high index is updated to mid - 1 and the loop continues. If the loop completes without finding the search value, the method returns -1.
The Arrays class is imported to allow the use of the binarySearch() method of the class, but this method is not used in this implementation of binary search.
13. Write a Java program to find the second largest number in an array.
import java.util.Arrays;
public class SecondLargestNumber {
public static void main(String[] args) {
int[] array = { 5, 8, 3, 12, 15, 6, 10 };
int secondLargest = findSecondLargest(array);
System.out.println("The second largest number in the array is: " + secondLargest);
}
public static int findSecondLargest(int[] array) {
Arrays.sort(array);
return array[array.length - 2];
}
}
This program finds the second largest number in an array of integers. The array is first initialized with some values. The findSecondLargest() method is then called with the array as an argument. The method sorts the array in ascending order using the sort() method of the Arrays class, which modifies the original array. The second largest number in the sorted array is then returned, which is the second-to-last element of the array.
The Arrays class is imported to allow the use of the sort() method of the class. The program assumes that the array contains at least two distinct values, and does not handle the case where the array has less than two values. If the array has less than two values, the program will throw an ArrayIndexOutOfBoundsException.
14. Write a Java program to check if two strings are anagrams or not.
import java.util.Arrays;
import java.util.Scanner;
public class AnagramCheck {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the first string: ");
String str1 = input.nextLine();
System.out.print("Enter the second string: ");
String str2 = input.nextLine();
if (areAnagrams(str1, str2)) {
System.out.println("The two strings are anagrams.");
} else {
System.out.println("The two strings are not anagrams.");
}
input.close();
}
public static boolean areAnagrams(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
return Arrays.equals(charArray1, charArray2);
}
}
This program checks if two strings are anagrams of each other. The user is prompted to enter the two strings using a Scanner object. The areAnagrams() method is then called with the two strings as arguments. The method first checks if the two strings have the same length. If they do not have the same length, they cannot be anagrams, so the method returns false. If they have the same length, the method converts the strings to character arrays using the toCharArray() method of the String class, which returns a new character array that contains the characters of the string. The character arrays are then sorted in ascending order using the sort() method of the Arrays class, which modifies the original arrays. Finally, the equals() method of the Arrays class is used to check if the two sorted arrays are equal. If they are equal, the two strings are anagrams, so the method returns true. If they are not equal, the two strings are not anagrams, so the method returns false.
The Arrays and Scanner classes are imported to allow the use of the sort() and equals() methods of the Arrays class and the nextLine() method of the Scanner class, respectively. This program assumes that the input strings contain only letters and have no spaces or special characters. If the input strings contain spaces or special characters, the program will consider them as part of the string and may not correctly identify anagrams.
15. Write a Java program to remove duplicate elements from an array.
import java.util.Arrays;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] array = { 1, 2, 3, 2, 1, 4, 5, 4, 6 };
int[] result = removeDuplicates(array);
System.out.print("The array without duplicates is: ");
System.out.println(Arrays.toString(result));
}
public static int[] removeDuplicates(int[] array) {
int[] temp = new int[array.length];
int j = 0;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] != array[i + 1]) {
temp[j++] = array[i];
}
}
temp[j++] = array[array.length - 1];
int[] result = new int[j];
for (int i = 0; i < j; i++) {
result[i] = temp[i];
}
return result;
}
}
This program removes duplicate elements from an array of integers. The array is first initialized with some values. The removeDuplicates() method is then called with the array as an argument. The method creates a new temporary array temp of the same length as the input array, and initializes a variable j to 0. The method then loops through the input array, comparing each element to the next element. If the current element is not equal to the next element, it is added to the temp array at index j, and j is incremented by 1. The last element of the input array is then added to the temp array at index j. The method then creates a new array result of length j, copies the elements of the temp array into the result array, and returns the result array.
The Arrays class is imported to allow the use of the toString() method of the class, which returns a string representation of the array. This program assumes that the input array is not sorted, and removes only consecutive duplicates. If the input array contains non-consecutive duplicates, the program will not remove them.
16. Write a Java program to find the sum of all elements in an array.
public class ArraySum {
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5 };
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
System.out.println("The sum of the elements in the array is: " + sum);
}
}
This program calculates the sum of all elements in an array of integers. The array is first initialized with some values. A variable sum is then initialized to 0. The program loops through the array using a for loop, adding each element to sum. Finally, the program prints out the value of sum.
This program assumes that the input array contains only integers. If the input array contains elements of other types, the program will not work correctly.
17. Write a Java program to count the occurrence of a given character in a string.
public class CountChar {
public static void main(String[] args) {
String str = "Hello, World!";
char ch = 'l';
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
}
}
System.out.println("The character '" + ch + "' appears " + count + " times in the string.");
}
}
This program counts the number of times a given character appears in a string. The string and character are first initialized with some values. A variable count is then initialized to 0. The program loops through the string using a for loop, checking each character to see if it is equal to the given character. If the character is equal to the given character, count is incremented by 1. Finally, the program prints out the count of the character.
This program assumes that the input string and character are not null. If the input string or character is null, the program will throw a NullPointerException. If the input character is a whitespace character, the program may not work as expected, depending on the requirements of the problem.
18. Write a Java program to calculate the power of a number.
import java.util.Scanner;
public class Power {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the base number: ");
double base = input.nextDouble();
System.out.print("Enter the exponent: ");
int exponent = input.nextInt();
double result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
System.out.println(base + " raised to the power of " + exponent + " is " + result);
}
}
This program calculates the power of a given base number raised to a given exponent. The program prompts the user to enter the base number and exponent. A variable result is then initialized to 1. The program loops through the exponent using a for loop, multiplying the base number by itself for each iteration. Finally, the program prints out the result.
This program assumes that the input base number and exponent are valid numbers. If the input base number is 0, the result will always be 0. If the input exponent is negative, the result will be 1 divided by the power of the base number raised to the positive exponent.
19. Write a Java program to find the length of a string without using the length() method.
public class StringLength {
public static void main(String[] args) {
String str = "Hello, World!";
int count = 0;
for (char c : str.toCharArray()) {
count++;
}
System.out.println("The length of the string is " + count);
}
}
This program finds the length of a given string without using the length() method. The string is first initialized with some value. A variable count is then initialized to 0. The program loops through the characters of the string using a for-each loop, incrementing count by 1 for each character. Finally, the program prints out the count of the characters.
This program assumes that the input string is not null. If the input string is null, the program will throw a NullPointerException. Also, note that this method of finding the length of a string is not efficient, and it is always better to use the built-in length() method of the String class.
20. Write a Java program to print the ASCII value of a character.
import java.util.Scanner;
public class ASCIIValue {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = input.next().charAt(0);
int asciiValue = (int) ch;
System.out.println("The ASCII value of " + ch + " is " + asciiValue);
}
}
This program prints the ASCII value of a given character. The program prompts the user to enter a character. The next() method of the Scanner class is used to read the input as a string, and the charAt() method is used to extract the first character of the string. The character is then converted to its ASCII value using a type cast. Finally, the program prints out the ASCII value of the character.
This program assumes that the input character is a valid character. If the input character is a special character that cannot be displayed, the program will print out the ASCII value of the character.
======
No comments:
Post a Comment