[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 945
  • Last Modified:

C++ Program to enter an array of integers

I need help with an issue. My assignment is to enter an array of integers, no more than 50. The program ask you how many numbers you want to enter and then prints the numbers entered and counts the number of occurrences of each. This sort of works. My problems is I need to be able to enter negative numbers too. When I enter a negative number it only counts the occurrences of the positive numbers and ignores the negative ones completely. I also need to print the numbers entered in descending order and not ascending. Please help.. Note: the system (pause) and return 0 are required content.

See code below:

#include<iostream>
#include<string>
using namespace std;

void inputData(int *myMainNum, int *pCount);  
void countNums(int *myMainNum, int **pCount, int count);
int sortNum(int  *myMainNum, int count);
const int MAX =50;

int main()
{
      
      int *myMainNum = NULL;
    int *pCount = NULL;
       
    inputData(myMainNum, pCount);
      
    return 0;
 
}
void inputData(int *myMainNum, int *pCount)
{
    int count = 0;
    cout << "How many numbers do you want to enter (up to 50)?";
    cin >> count;

      if (count > MAX){
     cout<< "Number can't be greater than "<<MAX<<"- Program Exiting!!"<<endl;
      
       exit(1);

            }else{
   
       myMainNum = new int [count];
     cout << "Enter the numbers:\n"<<endl;
       cout << "My Numbers:"<<endl;
        }
     for (int i = 0; i < count; i++)
      {
            cin>>myMainNum[i];
            /*  if (myMainNum[i] < 0){
          cin>>"-">>myMainNum[i];
              }else{
                    cin>>myMainNum[i];}*/
             cout << endl;
      }
    countNums(myMainNum, &pCount, count);
      
    for (int j = 0; j < (sortNum(myMainNum, count)+1); j++)

    {
        if (pCount[j]>0)
            //if (pCount[j]<0)
                  
            cout << j << ": " << pCount[j] << endl;
    }
}
void countNums(int *myMainNum, int **pCount, int count)
{
      cout <<"\nNumber Count:\n";
    (*pCount) = new int[sortNum(myMainNum, count)+1];
    for (int j = 0; j <= sortNum(myMainNum, count); j++)
        (*pCount)[j] = 0;
    for (int i = 0; i < count; i++)
        (*pCount)[myMainNum[i]]++;
}

int sortNum(int *myMainNum, int count)
{
   
      int  highnum = 0;
    for (int i = 0; i< count; i++)
    {
        if (myMainNum[i]> highnum)
            highnum = myMainNum[i];
    }
    return highnum;
}
 
ch5-edit.cpp
0
vixenmrb
Asked:
vixenmrb
  • 3
  • 2
  • 2
  • +1
1 Solution
 
mr_stevieCommented:
Hello!

The way you've implemented the code is interesting.. however you can make the following changes to get your desired output

In void inputData(), when you display your output, you are starting at the 0th element. You should start at the negative number of the maximum number:

    for ( int j = -( sortNum(myMainNum, count) + 1 ); j < ( sortNum(myMainNum, count) + 1 ); j++ )
    {
        if ( pCount[j] > 0 )
                  cout << j << ": " << pCount[j] << endl;
    }

Also, the same goes when you initialise all the elements in pCount to zero:

      for ( int j = -( sortNum(myMainNum, count) + 1 ); j < ( sortNum(myMainNum, count) + 1 ); j++ )
            (*pCount)[j] = 0;

0
 
mr_stevieCommented:
My apologies. I was looking into it further. It kind of works but having a "negative" number memory allocation is something you should never do. It was kind of quickly hacked up code.

Looking it into further, this should be the proper way to do it:

First, you must add another function that will find the lowest possible number in the data set provided by the user.

Second, you must change the maximum number of values to accommodate all the possible values. i.e. if your maximum number is 50 and minimum number is -30, you must allocate the count array to store 80 different numbers.

Therefore, when going through the array of pCount, your condition should be something like this:

     int j = 0; j < ( ( sortNum(myMainNum, count) + 1 ) + ( lowNum(myMainNum, count ) + 1 ) ); j++

lowNum() being a function that returns the lowest possible value in the data set.

You should do this event time you go through the elements of pCount and also when outputting "j" into the console.

Hope this helps!
0
 
phoffricCommented:
There are, of course, many ways to design this histogram assignment. Even if restricted to positive numbers  the OP design requires making potentially large sparse arrays:
========= scenario 1 ============
How many numbers do you want to enter (up to 50)? 6
My Numbers:
1
1234567
2
1234567
2
2
Number Count:
1: 1
2: 3
1234567: 2
=========
Now, is it really necessary to allocate an array that is over 4MB.

Instead, you could define a struct having two attributes, enteredNumber and count, and have an array of (for the above example) 6 structs (i.e., the number of entries chosen by the user). Now you don't have to worry about whether the number is negative or positive; and you don't have to preprocess the list to find the high and low numbers.

When a number is entered, the number is searched in the list to see if it exists. If it does, then the count is incremented; if it does not, then it is added with a count of 1.

But consider a different scenario:
========= scenario 2 ============
How many numbers do you want to enter (up to 50)? 6
My Numbers:
1
1
1
2
1
1
Number Count:
1: 5
2: 1
=========
Now, with the above struct approach you need 6 entries; whereas with the original OP, you only need 3 entries.

It is possible to create just one list using the struct approach that minimizes the number of entries whether it be scenario 1 or 2 by creating a linked list inserting a new entry (in sorted order, if desired) into the list if the entered number is not found.

Now, if the max entries went from 50 to say 1,000,000 (and the input was a file with a million lines in it), then instead of a linked list, it would be better to use a balanced binary tree. Maybe this sounds hard?? Well, if you start using STL, then you can use the map STL facility in which case this histogram should be doable in a few lines of code.

But for now, stick with a max of 50 as required by the assignment. If you would like to watch a good movie on linked lists, let me know and I'll provide the links.
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
phoffricCommented:
One more thing if sticking with your original design. About that line of code -
>>      for (int j = 0; j <= sortNum(myMainNum, count); j++)
Since sortNum() function is returning the same high value every time (or adjusted to handle negative numbers), you should take it out of the loop. Just define a variable and set it to sortNum(...), and use that variable. There is no reason to call this function every time you go through the loop.
0
 
itsmeandnobodyelseCommented:
I don't think your code is good. Especially the function sortNum doesn't seem to be well-defined (especially doesn't make what the name implies). I would suggest to redesign your program. Firstly, you should get rid of the pointers your were passing as arguments. In C++ you can pass by reference and I can't see any needs for using a pointer pCount or even a pointer to pointer. If you need a dynamic array you would use a std::vector<int>.  Following that your main would turn to

int main()
{
     std::vector<int> NumArr;
     std::vector<int> CountArr;
     // inputData would only take the inputs
     inputData(NumArr);
     // sortData would sort ascending or descending
     sortData(NumArr, false);  // false means descending
     // countData would count the occurrences and return the number of different data
     countData(NumArr, CountArr);
     // outputData would output the results
     outputData(numArr, CountArr);

     return 0;
}

Note, if you were not allowed to use std::vector, use fixed-sized arrays like

   int NumArr[MAX] = { 0 };
   int CountArr[MAX] = { 0 };

 
0
 
phoffricCommented:
If STL is acceptable, then the easiest way to handle your problem of counting distinct integers is to use STL map. You can define a variable of type map<int,int> - the first int is the entered number (the unique key), and the second int will be by your application the number of occurrences of that number.

Here is the STL map reference:
    http://www.cplusplus.com/reference/stl/map/

The nice thing about map for your application is that:
(1) you don't have to ask how many numbers you are going to enter - just allow the user to enter any positive or negative numbers as they wish; using some sentinel (e.g., using Visual Studio C++ it is Ctrl/z)
(2) the map insertion technique can be made to automatically detects if a new unique number has been entered, and if so, will automatically add this number to the list (actually it's a binary tree); and if the number is already in the map, then the count can be incremented by one
(3) the unique numbers are arranged in sorted order (by default)
(4) it keeps track of its size, so you don't have to
(5) the count is initialized to 0 automatically when the new unique number is inserted into the map, so you don't have to

This leads to a very simple and elegant histogram solution as can be seen here:
    http://www.fredosaurus.com/notes-cpp/stl-containers/map/map-ex-wordfreq.html

Hopefully this shows you the strength of using STL over writing the containers yourself.

For your purpose, you can modify it to work with integers rather than string.
Note that in the link, we don't even necessarily need to know the size; the program just iterates over all the elements of the map.

Even if you are not up to speed with map, it would be interesting for you to take this code, walk through it in your debugger, and see its output. Then make the minor modifications to convert this program to accept numbers instead of strings, and do the same thing. Maybe by doing this, even without using map, it may give you ideas on how to better design your program.
0
 
vixenmrbAuthor Commented:
Did not answer question directly because the subject reference was not covered yet but did give me insight on how to solve issue.
0
 
itsmeandnobodyelseCommented:
>>>> Did not answer question directly because the subject reference was not covered yet but did give me insight on how to solve issue.

Is there still something open? Did you solve the problem with negative numbers?

I assumed it would be solved when using a better sort function and waited for your feedback.
0

Featured Post

Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now