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

Assignment - 2

The document contains a series of Java programming assignments, each with a specific task such as checking for prime numbers, finding the second largest element in an array, counting vowels and consonants in a string, and implementing various algorithms like Bubble Sort and Binary Search. Each assignment includes a program code snippet and an expected output. The tasks cover fundamental programming concepts such as loops, conditionals, recursion, and exception handling.

Uploaded by

sobhiyasobhi63
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views29 pages

Assignment - 2

The document contains a series of Java programming assignments, each with a specific task such as checking for prime numbers, finding the second largest element in an array, counting vowels and consonants in a string, and implementing various algorithms like Bubble Sort and Binary Search. Each assignment includes a program code snippet and an expected output. The tasks cover fundamental programming concepts such as loops, conditionals, recursion, and exception handling.

Uploaded by

sobhiyasobhi63
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Assignment – 2

1. Write a Java program to check if a given number is prime.


PROGRAM:

import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
boolean isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime && num > 1) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}

OUTPUT:

2. Write a program to find the second largest element in an array.


PROGRAM:

class SecondLargest {
public static void main(String[] args) {
int[] arr = {3, 5, 1, 2, 4};
int largest = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > largest) {
second = largest;
largest = num;
} else if (num > second && num != largest) {
second = num;
}
}
System.out.println("Second Largest: " + second);
}
}
OUTPUT:

3. Write a Java program to count the number of vowels and consonants in a given string.
PROGRAM:
import java.util.Scanner;
public class VowelConsonantCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine().toLowerCase();
int vowels = 0, consonants = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}
OUTPUT:

4. Write a program to reverse a string without using built-in methods.


PROGRAM:
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println("Reversed string: " + reversed);
}
}

OUTPUT:

5. Write a program to find the factorial of a number using recursion.


PROGRAM:
public class Factorial {
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
int number = 6;
System.out.println("Factorial of " + number + " is " + factorial(number));
}
}

OUTPUT:

6. Write a program to implement a simple calculator using switch-case.


PROGRAM:
import java.util.Scanner;
public class calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = sc.nextInt();
System.out.print("Enter second number: ");
int num2 = sc.nextInt();
System.out.println("Choose operation (+, -, *, /): ");
char operation = sc.next().charAt(0);
int result = 0;
switch (operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Invalid operation.");
}
System.out.println("Result: " + result);
}
}

OUTPUT:
7. Write a Java program to check if a given string is a palindrome.
PROGRAM:
import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine().toLowerCase();
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
if (str.equals(reversed)) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
}
}
OUTPUT:

8. Write a program to sort an array using Bubble Sort.


PROGRAM:
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
OUTPUT:

9. Write a program to find the GCD (Greatest Common Divisor) of two numbers.
PROGRAM:
import java.util.Scanner;
public class GCD {
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, 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();
scanner.close();
int gcdResult = gcd(num1, num2);
System.out.println("The GCD of " + num1 + " and " + num2 + " is " + gcdResult);
}
}
OUTPUT:

10. Write a program to implement the Fibonacci sequence up to n terms using iteration.
PROGRAM:
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = sc.nextInt();
int a = 0, b = 1;
System.out.print("Fibonacci sequence: ");
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}

OUTPUT:

11. Write a program to remove duplicates from an array.

PROGRAM:
import java.util.HashSet;
import java.util.Scanner;
public class RemoveDuplicates {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.print("Enter the elements: ");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
set.add(arr[i]);
}
System.out.println("Array after removing duplicates: " + set);
}
}
OUTPUT:

12. Write a program to demonstrate the use of constructors in Java.


PROGRAM:
public class Constructor {
private String name;
public Constructor(String name) {
this.name = name;
}
public void display() {
System.out.println("Name: " + name);
}
public static void main(String[] args) {
Constructor obj = new Constructor("kavin");
obj.display();
}
}
OUTPUT:

13. Write a Java program to find the largest and smallest numbers in an array.
PROGRAM:
import java.util.Scanner;
public class LargestSmallest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.print("Enter the elements: ");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int largest = arr[0];
int smallest = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
if (arr[i] < smallest) {
smallest = arr[i];
}
}
System.out.println("Largest: " + largest);
System.out.println("Smallest: " + smallest);
}
}
OUTPUT:

14. Write a program to count the number of words in a given string.


PROGRAM:
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
String[] words = str.split("\s+");
System.out.println("Number of words: " + words.length);
}
}
OUTPUT:

15. Write a Java program to implement a binary search on a sorted array.


PROGRAM:
import java.util.Scanner;
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}

return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.print("Enter the elements (sorted): ");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.print("Enter the element to search: ");
int target = sc.nextInt();
int result = binarySearch(arr, target);
if (result == -1) {
System.out.println("Element not found.");
} else {
System.out.println("Element found at index: " + result);
}
}
}

OUTPUT:
16. Write a program to demonstrate the concept of method overloading.
PROGRAM:
public class MethodOverloading {
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println("Sum of integers: " + add(9, 18));
System.out.println("Sum of doubles: " + add(9.5, 10.6));
}
}
OUTPUT:
17. Write a program to read a file and count the number of lines in it.
PROGRAM:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class count{
public static void main(String[] args) {
String filePath = "C:\\Users\\PC\\Desktop\\so.txt";
int lineCount = 0;
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
lineCount++;
}
System.out.println("Number of lines: " + lineCount);
} catch (IOException e) {
System.out.println("Error reading file.");
}
}
}

OUTPUT:

18. Write a Java program to sort a list of strings in alphabetical order.


PROGRAM:
import java.util.ArrayList;
import java.util.Collections;
public class SortStrings {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Grapes");
list.add("Apple");
list.add("Banana");
Collections.sort(list);
System.out.println("Sorted list: " + list);
}
}

OUTPUT:

19. Write a program to implement a Stack using an array.

PROGRAM:
public class Stack {
private int[] stack;
private int top;
public Stack(int size) {
stack = new int[size];
top = -1;
}
public void push(int value) {
if (top == stack.length - 1) {
System.out.println("Stack Overflow");
} else {
stack[++top] = value;
System.out.println(value + " pushed to stack");
}
}
public void pop() {
if (top == -1) {
System.out.println("Stack Underflow");
} else {
System.out.println(stack[top--] + " popped from stack");
}
}
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(10);
stack.push(20);
stack.pop();
}
}
OUTPUT:

20. Write a Java program to create a custom exception and handle it.
PROGRAM:
public class CustomException {
public static void main(String[] args) {
try {
int number = -9;
if (number < 0) {
throw new Exception("Negative number not allowed.");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

OUTPUT:

You might also like