Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Since this is a learning exercise, I wouldn't write code, just the explanation:</p> <ul> <li>In general, the array is not guaranteed to have negative elements. Therefore, the program should be ready to see two outcomes - (a) when there is at least one negative element, so you can produce the desired output, and (b) when there are no negative elements in the array.</li> <li>Keeping the above in mind, your second loop needs to keep two parts of the current state: the <code>nmaxelement</code> that you already have, and <code>bool haveNegatives</code> which you need to introduce.</li> <li>Set <code>haveNegatives</code> to `false before the second loop</li> <li>Inside the loop, first check if the number <code>c[i]</code> is negative. If it is non-negative, move on to the next element (e.g. using the <code>continue</code> statement).</li> <li>If the number <code>c[i]</code> is negative, look at the current value of <code>haveNegatives</code>: if it is set to <code>true</code>, compare <code>c[i]</code> to <code>nmaxelement</code>, and change the current value of <code>nmaxelement</code> if <code>c[i]</code> is greater.</li> <li>If <code>haveNegatives</code> is <code>false</code>, set it to <code>true</code>, and also set <code>haveNegatives</code> to <code>c[i]</code></li> </ul> <p>When the loop ends, <code>haveNegatives</code> will be set to <code>true</code> if <code>nmaxelement</code> contains the highest negative element of the array; if there are no negative numbers in the array, <code>nmaxelement</code> will remain <code>false</code>.</p> <p>Alternatively, you could store the index of the current max negative in a single variable, rather than keeping both the value and the index. In this case, you could set that index to <code>-1</code> before the loop, and make a conditional on that index, like this:</p> <pre><code>// Come to this point only when c[i] is negative if (maxNegativeIndex == -1 || c[i] &gt; c[maxNegativeIndex]) { maxNegativeIndex = i; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload