Write a program that dynamically allocates an array of integers. It first reads
ID: 3774333 • 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 HelloWorld{
//showArray method to print values stored in array
public static void showArray(int[] arr){
System.out.println("Elements of the Array: ");
//loop till the length of the passed array
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
//input method for taking input from the user
public static void input(int[] arr){
Scanner sc=new Scanner(System.in);
System.out.println("Please enter elements of the Array: ");
//loop variable
int index=0;
//loop till length of the array
while(index < arr.length){
//variable input for storing user entered variable
int input=sc.nextInt();
//variable for keep track of duplicate entry
int pos=0;
//loop to check whether entered integer is already available in array or not
for(int i=0;i<arr.length;i++){
if(arr[i]!=input)//if integer is not available in array
pos++; //increase pos variable
}
if(pos==arr.length)//if pos=length of array,it means no duplicate element
{arr[index]=input; //hence store the user entered integer in array
index++;
}
else //else tell the user to enter distinct integer
System.out.println("Please enter distinct element !!");
}
}
public static void main(String []args){
//variable to store size of array
int n;
Scanner sc=new Scanner(System.in);
//asking user to enter size of array
System.out.println("Size of the Array: ");
//storing user entered value in n
n=sc.nextInt();
//defining an array of size n
int[] arr=new int[n];
//calling input function
input(arr);
//calling showArray function
showArray(arr);
}
}
*******OUTPUT******
Size of the Array:
5
Please enter elements of the Array:
1
2
3
4
4
Please enter distinct element !!
4
Please enter distinct element !!
5
Elements of the Array:
1 2 3 4 5
************OUTPUT******
Note:As there is no any instruction regarding coding language,i have implemented this in java.
Code has been tested on eclipse.Please do comment in case of any doubt,Thanks.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.