I found this somewhere on some website. Would you care to decode it, like explain why, when, and how they used the codes? The only part I didn't get is how did they get "largest_1" and "largest_2" by doing this. I see that it loops to find it but does the program overrides the "largest" numbers? This would help me understand more about finding the max/min of an assignment.

do                           
    {
    restart = false;
    
    for ( i = 1; i < 4; i++ )
    {
    
    if ( input[i] < input[i+1] ) 
    {
    temp = input[i];           //=======================================//
    input[i] = input[i+1];     //set up to do loop again until it's true//
    input[i+1] = temp;         //=======================================//
    
    restart = true;            // if it is true then it will go to while loop
    }                          // end of If loop
    }                          // end of For loop                   
    }                          // end of Do loop
    
    while ( restart == true ); // start of while loop
    largest_1 = input[1];      // records first largest
    largest_2 = input[2];      // records second largest
       
                               // desplays the answers 
    cout << "The largest two of the numbers you entered are " << largest_1
         << " and " << largest_2 << endl << endl;
  
    return largest_1, largest_2;
    }

Thank you.

They're sorting the list from high to low, then picking the first two elements, which are, since it's a sorted list, the largest two elements.

Note that they don't use the 0 array index. Arrays start with element index 0 in C++, not 1.

what the program does is, instead of overriding, replace the numbers to order them from largest to smallest... Let me explain:

Suppose the original input is | 5 | 7 | 1 | 3 | Enter the loop: is 5 < 7 ? Yes
Since it is, it assigns 5 to a temp variable, assign 7 to the position where 5 was originally located and assign 5 to where 7 was originally located.

So, now we have: | 7 | 5 | 1 | 3 | Move forward. Is 5 < 1 ? No
Move forward. Is 1 < 3 ? Yes
Since it is, repeat the same process as before (switch the numbers)

Now, we have | 7 | 5 | 3 | 1 | KEEP ALWAYS IN MIND: To better understand an excercise, do a desktop test, by running the process with paper and pencil, so you can visually track the program's data flow

Edited 5 Years Ago by Nichito: n/a

Thank you guys. Your explanation really helped me to understand this codes. Now I know what to do on my other project.

This article has been dead for over six months. Start a new discussion instead.