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

Shivam DSA

The document contains a series of Java programming exercises that cover various topics including displaying user information, calculating averages, checking for palindromes, finding factorials, generating Fibonacci series, and implementing search and sort algorithms. Each exercise includes a complete Java class with methods and comments explaining the functionality. The exercises are designed to help users practice and understand fundamental programming concepts in Java.

Uploaded by

Shivam Singh
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)
35 views29 pages

Shivam DSA

The document contains a series of Java programming exercises that cover various topics including displaying user information, calculating averages, checking for palindromes, finding factorials, generating Fibonacci series, and implementing search and sort algorithms. Each exercise includes a complete Java class with methods and comments explaining the functionality. The exercises are designed to help users practice and understand fundamental programming concepts in Java.

Uploaded by

Shivam Singh
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

1.

Write a program to display your name and roll


number.

public class MyInfo {


public static void main(String[] args) {
// Declare and initialize variables
String name = Shivam Singh ";
int rollNumber = 22CSE1180113;

// Display name and roll number


System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
}
}
2. Write a program to find to average of three
numbers.

import java.util.Scanner;

public class AverageCalculator {


public static void main(String[] args) {
// Create a Scanner object to take input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter three numbers
System.out.print("Enter the first number: ");
double number1 = scanner.nextDouble();

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


double number2 = scanner.nextDouble();

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


double number3 = scanner.nextDouble();

// Close the Scanner to prevent resource leak


scanner.close();

// Calculate the average


double average = (number1 + number2 + number3) / 3;

// Display the result


System.out.println("The average of the three numbers is:
" + average);
}
}
3. Write a program to check number is palindrome
or not.

import java.util.Scanner;

public class PalindromeCheck {


public static void main(String[] args) {
// Create a Scanner object to take input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number


System.out.print("Enter a number: ");
int number = scanner.nextInt();

// Close the Scanner to prevent resource leak


scanner.close();

// Check if the number is a palindrome


if (isPalindrome(number)) {
System.out.println(number + " is a palindrome.");
} else {
System.out.println(number + " is not a palindrome.");
}
}

// Function to check if a number is a palindrome


private static boolean isPalindrome(int num) {
int originalNum = num;
int reversedNum = 0;

// Reverse the number


while (num != 0) {
int digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num /= 10;
}

// Check if the reversed number is equal to the original


number
return originalNum == reversedNum;
}
4. Write a program which will find all such
numbers which are divisible by 7 but are not
multiply by 5, between 220 and 320 (both include).

public class DivisibleBy7NotMultipleOf5 {


public static void main(String[] args) {
// Iterate through numbers from 220 to 320 (inclusive)
for (int number = 220; number <= 320; number++) {
// Check if the number is divisible by 7 and not a
multiple of 5
if (number % 7 == 0 && number % 5 != 0) {
System.out.println(number);
}
}
}
}
5. Write a program to find the factorial of a
number using function.

import java.util.Scanner;

public class FactorialCalculator {


public static void main(String[] args) {
// Create a Scanner object to take input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number


System.out.print("Enter a number to find its factorial: ");
int number = scanner.nextInt();

// Close the Scanner to prevent resource leak


scanner.close();

// Calculate and display the factorial


long factorial = calculateFactorial(number);
System.out.println("The factorial of " + number + " is: " +
factorial);
}

// Function to calculate the factorial of a number


private static long calculateFactorial(int num) {
if (num == 0 || num == 1) {
return 1;
} else {
return num * calculateFactorial(num - 1);
}
}
}
6. Write a program to get the Fibonacci series
between 15 and 50 using function.
public class FibonacciSeries {
public static void main(String[] args) {
// Define the range for the Fibonacci series
int start = 15;
int end = 50;

// Display the Fibonacci series within the given range


System.out.println("Fibonacci series between " + start + "
and " + end + ":");
for (int i = start; i <= end; i++) {
System.out.print(fibonacci(i) + " ");
}
}

// Function to calculate the nth Fibonacci number


private static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
7. Write a program to display prime numbers
between intervals using functions.

import java.util.Scanner;

public class PrimeNumberFinder {


public static void main(String[] args) {
// Create a Scanner object to take input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the intervals


System.out.print("Enter the starting interval: ");
int start = scanner.nextInt();

System.out.print("Enter the ending interval: ");


int end = scanner.nextInt();

// Close the Scanner to prevent resource leak


scanner.close();

// Display prime numbers within the given intervals


System.out.println("Prime numbers between " + start + "
and " + end + ":");
displayPrimeNumbers(start, end);
}

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

// Function to display prime numbers within a given range


private static void displayPrimeNumbers(int start, int end) {
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
System.out.println(); // Move to the next line after
printing the prime numbers
}
}
8. Write a program to create an array and
display it.

public class ArrayExample {


public static void main(String[] args) {
// Create an array of integers
int[] numbers = {5, 10, 15, 20, 25};

// Display the elements of the array


System.out.println("Array elements:");

for (int i = 0; i < numbers.length; i++) {


System.out.println("Element " + i + ": " + numbers[i]);
}
}
}
9. Write a program to concatenate of two array.

import java.util.Arrays;

public class ConcatenateArrays {


public static void main(String[] args) {
// Two arrays to be concatenated
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};

// Concatenate arrays
int[] resultArray = concatenateArrays(array1, array2);

// Display the concatenated array


System.out.println("Concatenated Array: " +
Arrays.toString(resultArray));
}

// Function to concatenate two arrays


private static int[] concatenateArrays(int[] arr1, int[] arr2) {
int len1 = arr1.length;
int len2 = arr2.length;
// Create a new array with the combined length
int[] result = new int[len1 + len2];

// Copy elements of the first array


System.arraycopy(arr1, 0, result, 0, len1);

// Copy elements of the second array


System.arraycopy(arr2, 0, result, len1, len2);

return result;
}
}
10. Write a program to display the array after
removing all the even numbers from the array.

import java.util.Arrays;

public class RemoveEvenNumbers {


public static void main(String[] args) {
// Original array with even and odd numbers
int[] originalArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// Display the original array


System.out.println("Original Array: " +
Arrays.toString(originalArray));

// Remove even numbers from the array


int[] newArray = removeEvenNumbers(originalArray);

// Display the modified array


System.out.println("Array after removing even numbers:
" + Arrays.toString(newArray));
}

// Function to remove even numbers from an array


private static int[] removeEvenNumbers(int[] arr) {
int oddCount = 0;

// Count the number of odd elements in the array


for (int num : arr) {
if (num % 2 != 0) {
oddCount++;
}
}
// Create a new array to store odd numbers
int[] newArray = new int[oddCount];
int index = 0;

// Copy odd numbers to the new array


for (int num : arr) {
if (num % 2 != 0) {
newArray[index++] = num;
}
}

return newArray;
}
}
11. Write a program to insert an element at the
specified position in the array.

import java.util.Arrays;
import java.util.Scanner;

public class InsertElementInArray {


public static void main(String[] args) {
// Original array
int[] originalArray = {1, 2, 3, 4, 5};

// Display the original array


System.out.println("Original Array: " +
Arrays.toString(originalArray));

// Get the element and position from the user


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the element to insert: ");
int elementToInsert = scanner.nextInt();
System.out.print("Enter the position to insert (1 to " +
(originalArray.length + 1) + "): ");
int position = scanner.nextInt();
scanner.close();

// Check if the position is valid


if (position < 1 || position > originalArray.length + 1) {
System.out.println("Invalid position. Position should be
between 1 and " + (originalArray.length + 1) + ".");
} else {
// Insert the element at the specified position
int[] newArray = insertElement(originalArray,
elementToInsert, position);
// Display the modified array
System.out.println("Array after inserting " +
elementToInsert + " at position " + position + ": " +
Arrays.toString(newArray));
}
}

// Function to insert an element at a specified position in


an array
private static int[] insertElement(int[] arr, int element, int
position) {
int len = arr.length + 1;
int[] newArray = new int[len];

// Copy elements before the specified position


System.arraycopy(arr, 0, newArray, 0, position - 1);

// Insert the new element at the specified position


newArray[position - 1] = element;

// Copy remaining elements after the specified position


System.arraycopy(arr, position - 1, newArray, position,
len - position);

return newArray;
}
}
12. Write a program to delete an element from the
specified position in the array

import java.util.Arrays;
import java.util.Scanner;

public class DeleteElementFromArray {


public static void main(String[] args) {
// Original array
int[] originalArray = {1, 2, 3, 4, 5};

// Display the original array


System.out.println("Original Array: " +
Arrays.toString(originalArray));

// Get the position to delete from the user


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the position to delete (1 to " +
originalArray.length + "): ");
int positionToDelete = scanner.nextInt();
scanner.close();

// Check if the position is valid


if (positionToDelete < 1 || positionToDelete >
originalArray.length) {
System.out.println("Invalid position. Position should be
between 1 and " + originalArray.length + ".");
} else {
// Delete the element at the specified position
int[] newArray = deleteElement(originalArray,
positionToDelete);

// Display the modified array


System.out.println("Array after deleting element at
position " + positionToDelete + ": " +
Arrays.toString(newArray));
}
}

// Function to delete an element from a specified position


in an array
private static int[] deleteElement(int[] arr, int position) {
int len = arr.length - 1;
int[] newArray = new int[len];

// Copy elements before the specified position


System.arraycopy(arr, 0, newArray, 0, position - 1);

// Copy remaining elements after the specified position


System.arraycopy(arr, position, newArray, position - 1,
len - position + 1);

return newArray;
}
}
13. With a program to implement linear search
algorithm.

import java.util.Scanner;

public class LinearSearch {


public static void main(String[] args) {
// Define an array
int[] array = {2, 7, 1, 8, 4, 6, 9, 3, 5};
// Get the element to search for from the user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the element to search for: ");
int target = scanner.nextInt();
scanner.close();

// Perform linear search


int index = linearSearch(array, target);

// Display the result


if (index != -1) {
System.out.println("Element " + target + " found at
index " + index + ".");
} else {
System.out.println("Element " + target + " not found in
the array.");
}
}

// Function to perform linear search in an array


private static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i; // Return the index if the element is found
}
}
return -1; // Return -1 if the element is not found
}
}
14. Write a program to implement binary search
algorithm.

import java.util.Arrays;
import java.util.Scanner;

public class BinarySearch {


public static void main(String[] args) {
// Define a sorted array
int[] array = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};

// Get the element to search for from the user


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the element to search for: ");
int target = scanner.nextInt();
scanner.close();

// Perform binary search


int index = binarySearch(array, target);

// Display the result


if (index != -1) {
System.out.println("Element " + target + " found at
index " + index + ".");
} else {
System.out.println("Element " + target + " not found in
the array.");
}
}

// Function to perform binary search in a sorted array


private static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2;
// Check if the target is present at the middle
if (arr[mid] == target) {
return mid;
}

// If the target is greater, ignore the left half


if (arr[mid] < target) {
left = mid + 1;
}
// If the target is smaller, ignore the right half
else {
right = mid - 1;
}
}

return -1; // Return -1 if the element is not found


}
}
15. Write a program to implement bubble sort.

import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
// Define an array
int[] array = {64, 34, 25, 12, 22, 11, 90};

// Display the original array


System.out.println("Original Array: " +
Arrays.toString(array));

// Perform bubble sort


bubbleSort(array);

// Display the sorted array


System.out.println("Sorted Array: " +
Arrays.toString(array));
}

// Function to perform bubble sort on an array


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++) {
// Swap if the element found is greater than the next
element
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;
}
}
}
}
}
16. Write a program to implement of selection
sort.

import java.util.Arrays;

public class SelectionSort {


public static void main(String[] args) {
// Define an array
int[] array = {64, 25, 12, 22, 11};
// Display the original array
System.out.println("Original Array: " +
Arrays.toString(array));

// Perform selection sort


selectionSort(array);

// Display the sorted array


System.out.println("Sorted Array: " +
Arrays.toString(array));
}

// Function to perform selection sort on an array


private static void selectionSort(int[] arr) {
int n = arr.length;

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


// Find the minimum element in the unsorted array
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;
}
}
}
17. Write a program to implement the insertion
sort.

import java.util.Arrays;

public class InsertionSort {


public static void main(String[] args) {
// Define an array
int[] array = {64, 25, 12, 22, 11};

// Display the original array


System.out.println("Original Array: " +
Arrays.toString(array));

// Perform insertion sort


insertionSort(array);

// Display the sorted array


System.out.println("Sorted Array: " +
Arrays.toString(array));
}

// Function to perform insertion sort on an array


private static void insertionSort(int[] arr) {
int n = arr.length;

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


int key = arr[i];
int j = i - 1;

// Move elements of arr[0..i-1] that are greater than


key to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}

arr[j + 1] = key;
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy