简体   繁体   中英

Compare the current element in iteration with all the following elements in an array - for loop

int[] num = new int[] { 20, 19, 8, 9, 12 };

For Example in the above array, I need to compare:

  • Element 20 with the elements 19, 8, 9, 12
  • Element 19 with 8, 9, 12
  • Element 8 with 9, 12
  • Element 9 with 12

Two loops:

// Go through each element in turn (except the last one)
for (int i = 0; i < num.Length - 1; i++)
{
    // Start at the element after the one we're on, and keep going to the
    // end of the array
    for (int j = i + 1; j < num.Length; j++)
    {
        // num[i] is the current number you are on.
        // num[j] is the following number you are comparing it to
        // Compare num[i] and num[j] as you want
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM