Write a Java program that reads numbers from the keyboard into an array of type
ID: 3643597 • Letter: W
Question
Write a Java program that reads numbers from the keyboard into an array of type int[]. You may assume that there will be 50 or fewer entries in the array. Your program should allow any number of numbers to be entered up to 50 numbers. The output is to be a two-column list. The first column is a list of the distinct array elements; the second column is the count of the number of occurrences of each element. The list should be sorted on entries in the first column, largest to smallest.e.g. for the array: {-12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12}
The output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
Explanation / Answer
#include <iostream>
#include <stdlib.h>
using namespace std;
void fillArray(int a[], int size, int& numberUsed);
void showFrequency (int a[], int SIZE);
void CheckDuplicate( int num, int arry[], int SIZE, int index);
int main( )
{
int sampleArray[50]={-12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12};
int numberUsed; //the index
fillArray (sampleArray, 50 , numberUsed);
showFrequency (sampleArray, numberUsed);
return 0;
}
void fillArray(int a[], int SIZE, int& numberUsed)
{
int nums=16;
cout << "Enter up to " << SIZE << " whole numbers. ";
cout << "How many numbers do you want to enter? ";
cin >> nums;
for(int index; index < nums; ++index)
{
//cin >> a[index];
}
numberUsed=nums;
}
void showFrequency (int a[], int SIZE)
{
int prev = a[0], count = 0;
cout << " Number count ";
//cout << a[0] << " ";
for (int i=0; i< SIZE; i++)
{
CheckDuplicate(a[i], a, SIZE, i);
}
}
void CheckDuplicate( int num, int arry[], int SIZE, int index)
{
bool duplicate=false;
bool hasNumAppeard=false;
int counter=0;
static int *temp = new int[SIZE];
temp[index]=num;
for(int x=0; x < index; ++x)
{
if(temp[x]==num){
hasNumAppeard=true;
}
}
for(int x=0; x < SIZE; ++x)
{
if(arry[x]==num){
duplicate = true;
++counter;
}
}
if(duplicate==true && hasNumAppeard==false){
cout<<num<<" "<<counter<<endl;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.