Write a program that reads a list of integers into an array with base type int. Provide the
capability to either read the list of integers into the array from the keyboard, or from a file, at
the user’s option. If the user chooses file input, the program should request a file name. You
may assume that there are fewer than 50 entries in the array. Your program determines how
many entries there are. The output is to be a two column list. The first column is a list of the
distinct array element; the second column is the count of the number of times each element
occurs in the array.
For example, for the input:
-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
Basically, a problem like this would need to be broken down into steps. I agree with Luntri that sorting won't do much good.
First you'll need to find which numbers are the duplicates and store them. Then you'll need to find out how many times each of show up and store those values. At the end you'll be able to display the vectors/lists/arrays together to get all the values.
#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <iomanip>
#include <functional>
usingnamespace std;
int main()
{
string input = "-12 3 -12 4 1 1 -12 1 -1 1 2 3 4 2 3 -12";
stringstream ss(input);
constint SPACING = 3;
const size_t SIZE = 50;
int myArray[SIZE] = { 0 };
int count = -1;
//fills the array with integers
while (ss >> myArray[++count]);//NULL statement
//create pointers to the beginning and end of the array
int *beg = myArray;
int *end = myArray + count;
//Sorts the array
sort(beg, end, greater<int>());
int current = myArray[0];
count = 1;
//counts the number of each value in the array
while (++beg != end)
{
if (current != *beg)
{
cout << setw(SPACING) << current << setw(SPACING) << count << endl;
current = *beg;
count = 0;
}
++count;
}
//outputs the final value
cout << setw(SPACING) << current << setw(SPACING) << count << endl;
cin.ignore();
return 0;
}