SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Arrays
Exercise:
Programming Projects
Question:4 | ISBN:9780132846813 | Edition: 5

Question

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 in the first column, largest to smallest.

For the array values

–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









TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

#include <iostream>  
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;  
           }  
       }  
   }  
   
   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;  
} 

 

0 0

Discussions

Post the discussion to improve the above solution.