1.
public class ArrayExample {
public static void main(String[] args) {
String[] data = {"PHP", "Java", "C++", "Python"};
// Creating a 2D array with a single row containing the data
String[][] dataArray = { data };
// Printing all elements using foreach
System.out.println("All elements:");
for (String[] row : dataArray) {
for (String element : row) {
System.out.println(element);
}
}
// Printing elements of the array in reverse
System.out.println("\nElements in reverse:");
for (int i = dataArray[0].length - 1; i >= 0; i--) {
System.out.println(dataArray[0][i]);
}
}
}
This Java program creates a two-dimensional array dataArray with a single row containing the given data. It then prints all the elements using a foreach loop and prints the elements in reverse by iterating through the array in reverse order.
2.
public class LinearSearch {
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i; // Return the index of the target element if found
}
}
return -1; // Return -1 if the target element is not found in the array
}
public static void main(String[] args) {
int[] elements = {50, 30, 80, 10, 20, 60, 70, 90, 40};
int targetElement = 80;
int resultIndex = linearSearch(elements, targetElement);
if (resultIndex != -1) {
System.out.println("Element " + targetElement + " found at index: " + resultIndex);
} else {
System.out.println("Element " + targetElement + " not found in the array.");
}
}
}
This Java program defines a linearSearch method that takes an array of integers and a target integer as arguments. It searches for the target integer using linear search and returns the index of the target element if found or -1 if the element is not present in the array.
In the main method, an array of integers is initialized, and the linearSearch method is called to find the specified element (80). The program then outputs the index where the element is found or a message indicating that the element is not present in the array.
3.
public class IntArrayExample {
public static void main(String[] args) {
// Declare an array of integers and assign values
int[] elements = {35, 70, 12, 80, 94};
// Output the elements of the array along with their indices
for (int i = 0; i < elements.length; i++) {
System.out.println("Element at index " + i + ": " + elements[i]);
}
}
}
This code defines an array elements of integers and initializes it with the specified values. It then uses a loop to go through the array, printing each element along with its corresponding index.