Write a program that dynamically allocates an array of integers. It first reads
ID: 3778011 • Letter: W
Question
Write a program that dynamically allocates an array of integers. It first reads an integer for the array size, then reads numbers into the array, and displays distinct numbers. (Hint: Read a number and store it to an array if it is new. If the number is already in the array, discard it. After the input, the array contains the distinct numbers.) Your program should have at least the following functions:
• showArray. This function displays the contents of the array.
• input: This function prompts the user to enter the numbers and stores the numbers in the array.
Explanation / Answer
import java.util.Scanner;
public class Exercise_05 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] numbers = new int[10]; int index = 0; System.out.print("Enter ten numbers: "); for (int i = 0; i < numbers.length; i++) { int num = input.nextInt(); if (isNew(numbers, num)) { numbers[index++] = num; } } System.out.println("The number of distinct number is " + index); System.out.print("The distinct numbers are: "); for (int i = 0; i < index; i++) { System.out.print(numbers[i] + " "); } } public static boolean isNew(int[] numbers, int n) { for (int i : numbers){ if (n == i) return false; }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.