Home > OS >  Iterations Count Of Nested For Loop
Iterations Count Of Nested For Loop

Time:12-27

I was performing a practice test of my university. There was a question in which I had to calculate number of iterations of a nested for loop. I have read somewhere on internet that to find number of iterations of nested for loop,

the formula is N(N-1)/2 where N is length of array.

I also verify my answer by writing the code in c# (given below).

But it was a wrong answer according to the software.

What is the problem?

Here is the question:

enter image description here

My answer is 6.

This is my code.

public class MainClass
    {
        public static void Main()
        {
            int count = 0;
            int[] arr = { 5, 9, 16, 19 };
            for (int i = 0; i < arr.Length; i  )
            {
                int idx = i;
                for (int j = i   1; j < arr.Length; j  )
                {
                    if (arr[idx] > arr[j])
                    {
                        idx = j;
                    }
                    count  ;
                }
                (arr[i], arr[idx]) = (arr[idx], arr[i]);
            }

            Console.WriteLine(count);
        }
    }

CodePudding user response:

The outer loop performs 4 iterations (more generally L*), implying 3 2 1 0=6 iterations ((L-1)L/2) of the inner loop. The correct answer must be one of 4 6=10 (L(L 1)/2) or 6 (L(L-1)/2).

*Length of the array.

CodePudding user response:

Can you figure out the number ot iterations it will take to execute the following input?

In my view, you need to add count in the first loop too. So the code would look like this:

int count = 0;
int[] arr = { 5, 9, 16, 19 };
for (int i = 0; i < arr.Length; i  )
{
    int idx = i;
    for (int j = i   1; j < arr.Length; j  )
    {
        if (arr[idx] > arr[j])
        {
            idx = j;
        }
        count  ;
    }
    (arr[i], arr[idx]) = (arr[idx], arr[i]);
    count  ;
}

Console.WriteLine(count);

OUTPUT: 10

  • Related