Search code examples
c#for-loopmodulo

Using Modulo instead of two loops


I'm new at programming in general and learning C# right now.

I just wrote a little programm where I have to step through an int[] in a specific pattern. The pattern is as follows:

  • Start at the last entry of the array (int i)
  • form the sum of i and (if avaible) the three entrys above (e.g. i += i-1 ... i += i-3)
  • Change i to i -= 4 (if avaible)
  • Repeat from step 2 until i = 0;

Therefore i wrote the following loop:

        for (int i = intArray.Length - 1; i >= 0; i -= 4)
        {
            for (int a = 1; a <= 3; a++)
            {
                if (i - a >= 0)
                {
                    intArray[i] += intArray[i - a];
                    intArray[i - a] = 0;
                }
            }
        }

Now my new assignment is to change my code to only use 1 loop with the help of modulo-operations. I do understand what modulo does, but i can't figure out how to use it to get rid of the second loop.

Maybe somebody explain it to me? Thank you very much in advance.


Solution

  • While iterating over the array, the idea would be to use the modulo 4 operation to calculate the next index to which you will add the current value.

    This should work with any array lengths:

            for (int i = 0; i < intArray.Length; i++){
                // we check how far away we are from next index which stores the sum
                var offset = (intArray.Length - 1 - i) % 4;
                if (offset == 0) continue;
                intArray[i+offset] += intArray[i];
                intArray[i] = 0;
            }