118k views
5 votes
An array of integers named parkingTickets has been declared and initialized to the number of parking tickets given out by the city police each day since the beginning of the current year. (Thus, the first element of the array contains the number of tickets given on January 1; the last element contains the number of tickets given today.) A variable named mostTickets has been declared, along with a variable k. Without using any additional variables, write some code that results in mostTickets containing the largest value found in parkingTickets.

User Dimassony
by
5.6k points

2 Answers

3 votes

Final answer:

To find the largest number of parking tickets in the array parkingTickets, initialize mostTickets with the first element, then iterate through the array with variable k, updating mostTickets if a larger value is encountered.

Step-by-step explanation:

The code to find the largest value in the parkingTickets array and store it in mostTickets using only the variable k as an iterator is as follows:

mostTickets = parkingTickets[0]; // Start by assuming the first element is the largest
for (k = 1; k < parkingTickets.length; k++) {
if (parkingTickets[k] > mostTickets) {
mostTickets = parkingTickets[k]; // Update mostTickets if a larger value is found
}
}

This loop iterates through each element of the array starting from the second element (since we already considered the first element by initializing mostTickets with it). During each iteration, it checks if the current element is larger than the value stored in mostTickets. If it is, mostTickets is updated with this larger value. The process continues until the end of the array is reached, leaving the largest number of parking tickets found in the array assigned to mostTickets.

User Morteza Tourani
by
5.5k points
6 votes

Answer:

Following code will store the largest value in array parkingTickets in the variable mostTickets

mostTickets = parkingTickets[0];

for(int k = 0; k<parkingTickets.length; k++)

{

if(parkingTickets[i]>mostTickets)

{

mostTickets = parkingTickets[i];

}

}

Step-by-step explanation:

In the above code segment, initially the number of tickets at first index is assumed as largest value of tickets in array.

Then using a for loop each value in the array parkingTickets is compared with the current mostTickets value.

If the compared value in parkingTickets array is larger than the current mostTickets value. Then that value is assigned to mostTickets.

This process is repeated for all elements in array.

Thus after looping through each element of array the largest value in array will get stored in mostTickets variable.

User IBabur
by
6.0k points