C++ Read In Array with Fewer than 50 integers, sort, print Unique numbers and there number of occurrences.

C++ Read In Array with Fewer than 50 integers, sort, print Unique numbers and there number of occurrences.

LANGUAGE: C++

CHALLENGE:

C++ Write a program that reads in an array of type int. You may assume that there are fewer than 50 entries in the array. Your program determines how many entries are used. 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 int he first column, largest to smallest.

SAMPLE DATA:

Test Array Values:          -12 3 -12 4 1 1 -12 1 -1 1 2 3 4 -12

SAMPLE OUTPUT:

N Count
4 2
3 3
2 2
1 4
-1 1
-12 4

SOLUTION:

#include

using namespace std;

int main(){
   int numbers[50];
   int num;
   int i;
   do{
       cout << "How many integers do you want to input(1-50) : "; cin >> num;
       if(num <= 0 || num > 50)
           cout << endl << "Invalid number, try again."<<endl;
   }while(num <= 0 || num > 50);
   cout << endl << "Enter " << num << " numbers : " << endl;

   //Receive Numbers
   for(i=0;i<num;i++){ cin >> numbers[i];}

   //Sort Number
   for(i=0;i < num;i++){
       for(int j=0;j < num-i-1;j++){
           if(numbers[j] < numbers[j+1]){
               int tempNum = numbers[j];
               numbers[j] = numbers[j+1];
               numbers[j+1] = tempNum;
           }
       }
   }

   cout << "Sorted Result: " << endl;
   for(i=0;i < num;i++){
       cout << numbers[i] << endl;
   }
   int number;
   int count=0;
   int count2=0;

   //print result
   cout << endl << "N\tCount" << endl;
   for(i=0;i < num;i++){
       number=numbers[i];
       for(int j=0;j < num;j++){
           //count result
           if(number==numbers[j]){
               count2++;
               count=j;
           }
       }

       cout << endl << numbers[i] << "\t" << count2;
       i=count;
       count2=0;
   }

   cout << endl;
   system("pause");
   return 0;
}

Add comment