[Go to site: main page, start]

0% found this document useful (0 votes)
13 views18 pages

Java Programs for Common Algorithms

The document contains multiple Java programs demonstrating various algorithms and functionalities, including finding the largest and smallest numbers in an array, generating Fibonacci series, checking for prime numbers, counting character occurrences in a string, and more. Each program is self-contained with a main method for execution and covers topics like sorting, searching, string manipulation, and linked list operations. Overall, it serves as a comprehensive guide to fundamental programming concepts in Java.

Uploaded by

Darshan Hn
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)
13 views18 pages

Java Programs for Common Algorithms

The document contains multiple Java programs demonstrating various algorithms and functionalities, including finding the largest and smallest numbers in an array, generating Fibonacci series, checking for prime numbers, counting character occurrences in a string, and more. Each program is self-contained with a main method for execution and covers topics like sorting, searching, string manipulation, and linked list operations. Overall, it serves as a comprehensive guide to fundamental programming concepts in Java.

Uploaded by

Darshan Hn
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

1. Find largest and smallest numbers in an array of integers.

public class FindLargestSmallest {


public static void main(String[] args) {
int[] numbers = {12, 34, 5, 67, 23, 78, 2, 89};
int largest = numbers[0];
int smallest = numbers[0];

for (int i = 1; i < [Link]; i++) {


// Update largest if current element is larger
if (numbers[i] > largest) {
largest = numbers[i];
}
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
// Output the results
[Link]("Largest number: " + largest);
[Link]("Smallest number: " + smallest);
}
}
2. Java program to print Fibonacci Series upto a given number.
import [Link];
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of terms: ");
int n = [Link]();
int firstTerm = 0, secondTerm = 1;
[Link]("Fibonacci Series up to " + n + " terms:");
for (int i = 1; i <= n; i++) {
[Link](firstTerm + " ");
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
[Link]();
}
}
3. Program to print to check whether the given number is prime or not.
public class PrimeNumberCheck {
static void PrimeNo() {
boolean prime = true;
int no = 7;
for (int i = 2; i < no; i++) {
if (no % i == 0) {
prime = false;
[Link](i); // Print the factor
}
}
if (prime == true) {
[Link](no + " is a Prime Number");
} else {
[Link](no + " is not a Prime Number");
}
}
public static void main(String[] args) {
PrimeNo(); // Call the PrimeNo method to check prime
}
}
4. program to count the occurrence of a character in a string
import [Link];
public class CharacterCount {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String inputString = [Link]();
[Link]("Enter the character to count: ");
char characterToCount = [Link]().charAt(0);
int count = 0;

for (int i = 0; i < [Link](); i++) {


if ([Link](i) == characterToCount) {
count++;
}
}
[Link]("The character '" + characterToCount + "' appears " + count + " times
in the string.");

// Close the scanner object


[Link]();
}
}
5. program to find the Factorial of a number using recursion.
class Factorial{
public static void main(String[] args){
int num = 5;
long fact = 1;
for(int i=1; i<=num; i++){
fact*=i;
}
[Link]("Factorial of "+num+" is: "+fact);
}
}
6. Program to merge 2 sorted arrays into a single sorted array.
import [Link];
public class MergeSortedArrays {
// Method to merge two sorted arrays
static int[] mergeSortedArrays(int[] arr1, int[] arr2) {
// Create a new array to hold the merged result
int[] mergedArray = new int[[Link] + [Link]];
int i = 0, j = 0, k = 0;
// Merge the two arrays
while (i < [Link] && j < [Link]) {
if (arr1[i] <= arr2[j]) {
mergedArray[k++] = arr1[i++];
} else {
mergedArray[k++] = arr2[j++];
}
}
// Copy remaining elements of arr1, if any
while (i < [Link]) {
mergedArray[k++] = arr1[i++];
}
// Copy remaining elements of arr2, if any
while (j < [Link]) {
mergedArray[k++] = arr2[j++];
}
return mergedArray;
}
public static void main(String[] args) {
// Example sorted arrays
int[] arr1 = {1, 3, 5, 7, 9};
int[] arr2 = {2, 4, 6, 8, 10};
// Call the merge method
int[] mergedArray = mergeSortedArrays(arr1, arr2);
// Print the merged array
[Link]("Merged sorted array: " + [Link](mergedArray));
}
}

7. write a program, given an array of n-1 integers in the range of 1 to n, write a


program to find missing number.
public class FindMissingNumber {
// Method to find the missing number
static int findMissingNumber(int[] arr, int n) {
// Calculate the sum of numbers from 1 to n using the formula
int expectedSum = n * (n + 1) / 2;
// Calculate the sum of elements in the array
int actualSum = 0;
for (int i = 0; i < [Link]; i++) {
actualSum += arr[i];
}
// The missing number is the difference between expectedSum and actualSum
return expectedSum - actualSum;
}
public static void main(String[] args) {
// Example array with missing number
int[] arr = {1, 2, 4, 6, 3, 7, 8}; // n = 8, so the missing number is 5
int n = 8; // The number range is from 1 to 8
// Call the findMissingNumber method
int missingNumber = findMissingNumber(arr, n);
// Output the missing number
[Link]("The missing number is: " + missingNumber); }}
8. program to find all duplicate elements in an array.
import [Link];
public class FindDuplicates {
// Method to find duplicates using HashSet
static void findDuplicates(int[] arr) {
// Create a set to store unique elements
HashSet<Integer> set = new HashSet<>();

// Loop through the array to find duplicates


[Link]("Duplicate elements are:");
for (int i = 0; i < [Link]; i++) {
// If the element is already in the set, it's a duplicate
if (![Link](arr[i])) {
[Link](arr[i]);
}
}
}

public static void main(String[] args) {


// Example array with duplicate elements
int[] arr = {4, 3, 2, 7, 8, 2, 4, 9, 3};

// Call the findDuplicates method


findDuplicates(arr);
}
}
9. simple java program to find sum of digits of given a number.
class SumOfDigit{
public static void main(String[] args){
int num = 1234;
int sum = 0;
int temp = num;
while(temp != 0){
int digit = temp%10;
sum = sum+digit;
temp = temp/10;
}
[Link]("Sum of the digits of "+num+" is "+ sum);
}
}
10. Bubble Sort algorithm.
import [Link];

public class BubbleSort {

// Method to implement the Bubble Sort algorithm


static void bubbleSort(int[] arr) {
int n = [Link];

// Outer loop for each pass through the array


for (int i = 0; i < n - 1; i++) {
// Inner loop to compare adjacent elements
for (int j = 0; j < n - i - 1; j++) {
// If the current element is greater than the next element, swap them
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) {
// Example array to be sorted
int[] arr = {64, 34, 25, 12, 22, 11, 90};

// Print the original array


[Link]("Original Array: " + [Link](arr));

// Call the bubbleSort method to sort the array


bubbleSort(arr);

// Print the sorted array


[Link]("Sorted Array: " + [Link](arr));
}
}
11. Reverse singly Linked List.
public class LinkedListReverse {
// Node class to represent a node in the linked list
static class Node {
int data;
Node next;

// Constructor to create a new node


Node(int data) {
[Link] = data;
[Link] = null;
}
}

// Method to reverse the linked list


static Node reverseLinkedList(Node head) {
Node prev = null;
Node current = head;
Node next = null;

// Iterate through the list and reverse the links


while (current != null) {
next = [Link]; // Store the next node
[Link] = prev; // Reverse the current node's pointer
prev = current; // Move prev to current node
current = next; // Move to the next node
}

// At the end, prev will be the new head of the reversed list
return prev;
}

// Method to print the linked list


static void printList(Node head) {
Node temp = head;
while (temp != null) {
[Link]([Link] + " ");
temp = [Link];
}
[Link]();
}
public static void main(String[] args) {
// Creating a simple linked list: 1 -> 2 -> 3 -> 4 -> 5
Node head = new Node(1);
[Link] = new Node(2);
[Link] = new Node(3);
[Link] = new Node(4);
[Link] = new Node(5);

// Print the original linked list


[Link]("Original Linked List: ");
printList(head);

// Reverse the linked list


head = reverseLinkedList(head);
// Print the reversed linked list
[Link]("Reversed Linked List: ");
printList(head);
}
}
12. Implement Linear Search.
public class LinearSearch {

// Method to implement Linear Search


static int linearSearch(int[] arr, int target) {
// Traverse the array
for (int i = 0; i < [Link]; i++) {
// If target is found, return the index
if (arr[i] == target) {
return i; // Return the index of the target element
}
}
return -1; // Return -1 if the target is not found
}

public static void main(String[] args) {


// Example array
int[] arr = {12, 34, 23, 56, 78, 9, 67};
// Target element to search for
int target = 56;

// Call the linearSearch method


int result = linearSearch(arr, target);
// Output the result
if (result != -1) {
[Link]("Element found at index: " + result);
} else {
[Link]("Element not found in the array.");
}
}}
13. Implement Binary Search.
import [Link];

public class BinarySearch {

// Method to perform Binary Search


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

while (left <= right) {


// Find the middle index
int mid = left + (right - left) / 2;

// If the target is found at mid


if (arr[mid] == target) {
return mid; // Return the index of the target element
}

// If the target is smaller than mid, discard the right half


if (arr[mid] > target) {
right = mid - 1;
}
// If the target is larger than mid, discard the left half
else {
left = mid + 1;
}
}

// If the target is not found


return -1;
}

public static void main(String[] args) {


// Create a scanner object for user input
Scanner sc = new Scanner([Link]);

// Taking the size of the array


[Link]("Enter the number of elements in the array: ");
int n = [Link]();

// Initialize the array


int[] arr = new int[n];

// Taking sorted array elements as input


[Link]("Enter the elements of the sorted array:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

// Taking the target element to search for


[Link]("Enter the element to search for: ");
int target = [Link]();

// Calling the binarySearch method


int result = binarySearch(arr, target);

// Output the result


if (result != -1) {
[Link]("Element found at index: " + result);
} else {
[Link]("Element not found in the array.");
}

// Closing the scanner object


[Link]();
}
}

[Link] the length of the string


import [Link].*;
public class StringLength {
public static void main(String[] args) {
String str = "Hello, World!";
int length = [Link]();
[Link]("Length of the String: " + length);
}
}

[Link] a String to an Integer

import [Link].*;
public class StringToInt {
public static void main(String[] args) {
String str = "12345";
int num = [Link](str);
[Link]("Converted Integer: " + num);
}
}
16. Sort an Array

import [Link].*;
public class SortArray {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 3};
[Link](arr);
[Link]("Sorted Array: " + [Link](arr));
}
}

17. Find the Maximum in an Array


class MaxInArray{
public static void main(String[] args){
int arr[]={6,58,42,60,15,24,51};
int max=arr[0];

for (int i=1; i<[Link]; i++){


if(arr[i]>max){
max=arr[i];
}
}
[Link]("The maximum value is: "+max);
}
}
18. Check if a String is Palindrome
import [Link].*;
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();
if([Link](reversed)) {
[Link](str + " is a palindrome");
} else {
[Link](str + " is not a palindrome");
}
}
}

19. Reverse a String

import [Link].*;
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
String reversed = new StringBuilder(str).reverse().toString();
[Link]("Reversed String: " + reversed);
}
}

You might also like