Array_Notes (1)
Array_Notes (1)
Arraysare fundamental structures in Java that allow us to store multiple values of the
same type in a single variable. They are useful for storing and managing collections of
data.
For primitive arrays, elements are stored in a contiguous memory location. For non-
primitive arrays, references are stored at contiguous locations, but the actual objects
may be at different locations in memory.
Searching an element in array
Trace table questions
1) Simple Sum of Elements
public class ArraySum
int sum = 0;
sum += arr[i];
Answer
2) Counting Even Numbers
Answer
public class SquareNumbers
{
public static void main(String[] args)
{
int[] NUMBERS = new int[100]; // Assuming the array is already populated
int[] SQUARES = new int[100];
// Loop through NUMBERS array and store the square in SQUARES array
for (int i = 0; i < NUMBERS.length; i++)
{
SQUARES[i] = NUMBERS[i] * NUMBERS[i];
}
2)
An array contains 1000 names. Construct a search algorithm that asks a user to input a name and outputs the
number of times that name appears in the array.
ANSWER
import java.util.Scanner;
public class SearchName
{
public static void main(String[] args)
{
String[] names = new String[1000]; // Assuming the array is already populated
Scanner scanner = new Scanner(System.in);
3) Construct the pseudocode for a program that loops through an array called “NUMBERS” that contains 500
integers. All the odd numbers should be stored in a ARRAY called “ODDS” and all the even numbers should be stored
in a ARRAY called “EVENS”.
// Count the number of odd and even numbers to define the size of the arrays
int oddCount = 0;
int evenCount = 0;