-2

I have this situation:

int[] array = new int[] {7, 5, 6}

The value of my index i is 1 and it is pointing at the head of my hypothetical circular list. The value "7" at the zero position is the tail.

My aim is to print:

5,6,7

Do I need a specific structure or can I do it with a simple array?

Pickeroll
  • 908
  • 2
  • 10
  • 25
  • 1
    Sort the array, and then print each index sequentially. –  Sep 02 '16 at 13:33
  • 2
    Possible duplicate of [Easiest way to Rotate a List in c#](http://stackoverflow.com/questions/9948202/easiest-way-to-rotate-a-list-in-c-sharp) – Liam Sep 02 '16 at 13:34
  • `index = (index + 1) % array.Length;` Something like that. – Dennis_E Sep 02 '16 at 13:38

3 Answers3

4

With a single "for" loop and the modulo operator:

int[] array = new int[] {7, 5, 6};

int start = 1;

for (int idx=0; idx<array.Length; idx++)
  Console.Write(array[(idx+start) % array.Length]);
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
1

There is nothing out of the box, but the following will wrap around the array.

        int[] array = new int[] { 7, 5, 6 };
        int startPosition = 1;
        string result = "";

        // Run from the start position to the end of the array
        for (int i = startPosition;  i < array.Length; i++)
        {
            result += array[i] + ",";
        }

        // Wrapping around, run from the beginning to the start position
        for (int i = 0; i < startPosition; i++)
        {
            result += array[i] + ",";
        }

        // Output the results
        result = result.TrimEnd(',');
        Console.WriteLine(result);       
        Console.Read();
Murray Foxcroft
  • 12,785
  • 7
  • 58
  • 86
1

If you want to print 5,6,7 you could use:

int printIndex = 1;
for(int i = 0; i < array.Length; i++)
{
     print(print(array[printIndex].ToString());
     printIndex++;
     if(printindex >= array.Length)
          printindex = 0;
}