比较迭代中的当前元素与数组中的以下所有元素-循环

时间:2019-02-16 13:00:00

标签: c# arrays loops console-application nested-loops

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

对于上述数组中的示例,我需要进行比较:

  • 具有元素19、8、9、12的元素20
  • 具有8、9、12的元素19
  • 具有9、12的元素8
  • 元素9与12

1 个答案:

答案 0 :(得分:2)

两个循环:

// 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
    }
}