public class SequentialSearch {
// Method to perform sequential search
public static int sequentialSearch(int[] array, int key) {
// Traverse the array from start to end
for (int i = 0; i < array.length; i++) {
// If the key is found, return its index
if (array[i] == key) {
return i;
}
}
// Return -1 if the key is not found
return -1;
}
public static void main(String[] args) {
// Sample array
int[] array = {5, 2, 9, 1, 3, 8, 4};
// Key to search for
int key = 3;
// Call the sequentialSearch method
int result = sequentialSearch(array, key);
// Output the result
if (result != -1) {
System.out.println("Key " + key + " found at index " + result);
} else {
System.out.println("Key " + key + " not found in the array.");
}
}
}
Output
Key 3 found at index 4
-------------------------------------
Stack ADTs
// Java Program Implementing Stack Class
import java.util.Stack;
public class StackExample
{
public static void main(String[] args)
{
// Create a new stack
Stack<Integer> s = new Stack<>();
// Push elements onto the stack
s.push(1);
s.push(2);
s.push(3);
s.push(4);
// Pop elements from the stack
while(!s.isEmpty()) {
System.out.println(s.pop());
}
}
}
Output
4
3
2
1
-----‐-------------‐-----------------
public class OddEvenChecker {
// Instance variable to hold the number
private int number;
// Constructor to initialize the number
public OddEvenChecker(int number) {
this.number = number;
}
// Method to check if the number is odd or even
public void checkOddEven() {
// If the number is divisible by 2 with no remainder, it's even
if (number % 2 == 0) {
System.out.println(number + " is Even");
} else {
// If there is a remainder, the number is odd
System.out.println(number + " is Odd");
}
}
public static void main(String[] args) {
// Create an object of OddEvenChecker and pass a number to the constructor
OddEvenChecker checker = new OddEvenChecker(10); // You can change the
number here
// Call the checkOddEven method to check if the number is odd or even
checker.checkOddEven();
}
}
Output
7 is Odd
10 is Even
-------------------------------------
import java.util.Scanner;
public class SortTwoElements {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt user to enter two numbers
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
// Sort the two numbers
if (num1 > num2) {
// Swap the numbers if num1 is greater than num2
int temp = num1;
num1 = num2;
num2 = temp;
}
// Output the sorted numbers
System.out.println("Sorted order: " + num1 + ", " + num2);
}
}
Output
Enter first number: 5
Enter second number: 3
Sorted order: 3, 5
-------------------------------------