C ++ Finding the largest number in an array

My problem with homework:

An array of integers called parkingTickets was declared and initialized by the number of parking tickets issued by city police every day since the beginning of this year. (Thus, the first element of the array contains the number of tickets issued on January 1, the last element contains the number of tickets provided today.)

 A variable named ndays was declared and initialized to store the size of the array. (Thus, if today was January 18th, ndays would have a value of 18, if today was February 3rd, ndays would have a value of 34.)

In addition, a variable named mostTickets was declared along with the variable k.

Without using any additional variables and without changing the ndays values ​​or elements of the parkingTickets array, write some code that will cause most talismas to contain the highest value found in parkingTickets.

For this, I have the following code:

for(k = 0; k < ndays; k++) {
    if (parkingTickets[k] > parkingTickets[ndays]) {
        mostTickets = parkingTickets[k];
    }
}

But my clerk says it wrong. What happened to my code? I also tried parkingTickets[ndays - 1], but this does not work either.

+5
source share
3 answers

Your comparison is incorrect. Each time you compare the current item with the last item. What you need to do is compare the current item with mostTickets. i.e.

if(parkingTickets[k] > mostTickets)

Also, for good measure, I would recommend initializing mostTickets for parking tickets [0].

+9
source

++ std:: max_element. , , , , , .

mostTickets = *std::max_element(parking_tickets, parking_tickets + ndays)
+11

int parkingTickets[] = {3,6,7,4,8,10,0};
int ndays = 7;
for(k = 0; k < ndays; k++) {
    if (parkingTickets[k] > parkingTickets[ndays]) {
    mostTickets = parkingTickets[k]; 
    }
}

The problem with this solution is that you did not initialize the mostTickets variable and you have no else clause. This code will work for you.

 int parkingTickets[] = {3,6,7,4,8,10,0};
 int ndays = 7;
 int mostTickets = -1;
 for(int k = 0; k < ndays; k++) {
    if (parkingTickets[k] > mostTickets) {
    mostTickets = parkingTickets[k]; 
    }
 }

After that, mostTickets will contain the value of the largest number in the array. This solution will take O (n) to complete, as we iterate over the array and some work for comparison.

+1
source

All Articles