Enter array elements: 1.5 2.3 3.9 4.1 5.6 6.7 7.8 8.0 9.2 10.5 11.3 12.6 13.7 14.8 15.9 16.4 17.5 18.3 19.0 20.1 Enter the number to search: 15.9
15.9 found at index 14
import java.util.Scanner;
public class RansariLinearSearch {
public static void main(String args[]) {
Scanner in = new Scanner(System.in); // Create Scanner object for input
double arr[] = new double[20]; // Declare an array of double data type with size 20
int l = arr.length; // Get the length of the array (which is 20)
int i = 0;
// Accept values for the array from the user
System.out.println("Enter array elements: ");
for (i = 0; i < l; i++) {
arr[i] = in.nextDouble(); // Accept each double value from the user and store it in the array
}
// Ask user for the number to search in the array
System.out.print("Enter the number to search: ");
double n = in.nextDouble(); // Accept the number to search for
// Linear search algorithm
for (i = 0; i < l; i++) {
if (arr[i] == n) { // If the current element is equal to the number being searched
break; // Exit the loop when the value is found
}
}
// Check if the number was found or not
if (i == l) {
System.out.println("Not found"); // If the loop goes through all elements and doesn't find the number
} else {
System.out.println(n + " found at index " + i); // If the number was found, display the index
}
in.close(); // Close the Scanner object
}
}
15.9 found at index 14
If the search value is not found in the array:
Not found
Output:
mathematica
Copy
Edit
double[] array of size 20 is created to store the user's input values.double values to populate the array.First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.