function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Gurjit Singh 22Gurjit Singh 22 

working of a below for loop

It may sound little weird but can someone please explain how the below loop manages to get the lowest value
Decimal LowestPrice;
//for loop to find the smallest value
 for(Integer i = 0;i<leadingPrice.size();i++){
//no idea how the below line is getting the lowest value
if(LowestPrice == null || leadingPrice.get(i) < LowestPrice){
lowestprice = leadingPrice.get(i);
 }
LeadingPrice is a List of Decimals and above loop is assigning the lowest value to the variable lowestprice, can someone please explain the working of above loop Thank you in advance.
Raj VakatiRaj Vakati
Here is the code
 
List<Decimal> leadingPrice = new List<Decimal>() ; 
leadingPrice.add(12);
leadingPrice.add(190);
leadingPrice.add(1);
leadingPrice.add(17);


Decimal LowestPrice =0 ; 
for(Integer i = 0;i<leadingPrice.size();i++){
//no idea how the below line is getting the lowest value
if(LowestPrice != null && leadingPrice.get(i) < LowestPrice){
LowestPrice = leadingPrice.get(i);
 }

 
Glyn Anderson (Slalom)Glyn Anderson (Slalom)
Gurjit,

if ( LowestPrice == null || leadingPrice.get(i) < LowestPrice )

The first time through the loop, "LowestPrice" is null (uninitialized), so the if-expression is TRUE, and "LowestPrice" gets set to whatever the first price is.  This is the lowest price seen so far.

Every subsequent iteration, "LowestPrice" is not null, so the if-expression is TRUE only when the current price is lower than the lowest price seen so far.  If that's the case, "LowestPrice" gets set to this new, lower price.

At the end of the loop, "LowestPrice" has the lowest price seen.

BTW:  Raj's modification will always result in "LowestPrice" being zero -- unless the loop encounters a price that is less-than-zero (i.e. negative).  [Sorry, Raj!]