How do I fix the assigning numbers to the variable and the number of occurrence?

I managed to formulate a code but I still cannot figure out where I'm getting it wrong, there are two problems the numbers and the number of occurrence. If one is working the other is not.

Task: Using while loop, write a program that asks a user to input for a positive number let’s say N. The program then asks the user for N number of positive integers. The program is to determine the largest value among the numbers and the number of times it occurred.

What I've Worked on So Far:

    #include <iostream>

using namespace std;

int main()
{
    int nnum, x = 1, unum, sum, max = 0,  anum, occ = 0, rem, quo;

    cout << "Input number of positive integers: ";
    cin >> nnum;
    cout << "Input " << nnum << " positive numbers: ";

    while (x<=nnum) {
            cin >> unum;
            anum = unum;
            quo = anum;
            sum += unum;
            if (max < unum) {
                max = unum;
            }
            x++;

            while (quo != 0) {
                    rem = quo%10;
                    quo = quo/10;

                    if (anum == rem) {
                            occ += 1;
                    }
            }
    }



    cout << "Highest: " << max << endl;
    cout << "Occurrence: " << occ;


    return 0;
}

Solution 1:

I'm not sure what your code is trying to do. The approach I'd take is simple: keep track of the maximum and the number of occurrences as you read numbers.

  • If you read a number greater than the current maximum, update the current maximum and reset the occurrence counter.
  • If you read a number equal to the current maximum, increment the occurrence counter.

You should also use a for loop instead of a while loop here, and you might want to validate your input as well.

#include <iostream>

int main()
{
    int n, max_number = -1, occurrences = 0;

    std::cin >> n;

    for(int i = 1; i <= n; i++)
    {
        int temp;

        std::cin >> temp;

        if(temp > max_number)
        {
            max_number = temp;
            occurrences = 0;
        }

        if(temp == max_number)
        {
            occurrences++;
        }
    }

    std::cout << max_number << ' ' << occurrences;

    return 0;
}