Related Topics

JAVA Programming
int[] numbers = {3, 5, 7, 11, 13};
int target = 7;
boolean found = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
found = true;
break;
}
}
if (found) {
System.out.println("Element found.");
} else {
System.out.println("Element not found.");
}
In this example, we have an array of integers called numbers
and a target integer called target
. We initialize a boolean variable called found
to false
, indicating that the target element has not yet been found. We then loop through the elements of the numbers
array using a for
loop and compare each element to the target element. If we find a match, we set the found
variable to true
and break out of the loop. After the loop, we check the value of found
to see if the target element was found or not.
Note that this algorithm performs a linear search of the array, which means that it checks each element of the array one at a time until it finds a match. If the array is sorted, you can use a binary search algorithm to search for the element more efficiently. A binary search algorithm works by dividing the array in half at each step and comparing the middle element to the target element. If the middle element is greater than the target element, the search is continued in the left half of the array; if the middle element is less than the target element, the search is continued in the right half of the array. This process is repeated until the target element is found or the search range is reduced to zero.
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = { 1, 2, 3, 4, 5 };
// Calling the method and passing the 'numbers' array
printArray(numbers);
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
In this example, we have a method called printArray
that takes an integer array (int[]
) as a parameter. The printArray
method simply iterates over the elements of the array and prints them.
In the main
method, we create an array called numbers
and initialize it with some values. Then, we call the printArray
method and pass the numbers
array as an argument.
When the printArray
method is called, it receives the reference to the numbers
array. It can access the array elements using the reference and perform operations on them. In this case, it prints each element of the array.
It’s important to note that when an array is passed as an argument, any modifications made to the elements of the array inside the method will be reflected outside the method as well. This is because the method receives a reference to the original array.




Popular Category
Topics for You
Go through our study material. Your Job is awaiting.