LuQ232
LuQ232

Reputation: 35

Loop over array and then loop backwards. [C]

I want to make a program looping over array and then looping backwards. How can I make it better with less code in C? Array has 8 elements!

while (1) {
    if (i == 0) {
        direction = 0; // RIGHT DIRECTION
    }
    if (i == 7) {
        direction = 1; // LEFT DIRECTION
    }
    PORTD = array[i]; // NEEDED ARRAY ELEMENT

    if (direction == 0) {
        i++;
    } else {
        i--;
    }
}

Upvotes: 0

Views: 86

Answers (2)

As others have noted, you need to reverse the sign of the increment variable, and you then need to use a proper condition to terminate the loop:

#include <stdio.h>

int main()
  {
  int i = 0, direction = 1;
  int PORTD, array[8] = {10, 11, 12, 13, 14, 15, 16, 17};

  for (i = 0 ; i >= 0 ; i += direction)
    {
    PORTD = array[i];

    printf("i=%d array[%d]=%d\n", i, i, array[i]);

    if(i == (sizeof(array)/sizeof(array[0]))-1 )
      direction = -1;
    }
  }

Upvotes: 0

chqrlie
chqrlie

Reputation: 144695

You can simplify your code by making direction the increment for the next index, 1 or -1.

Here is a modified version:

int i = 0, direction = 1;
for (i = 0;; i += direction) {
    if (i == 0) {
        direction = 1; // RIGHT DIRECTION
    } else
    if (i == 7) {
        direction = -1; // LEFT DIRECTION
    }
    PORTD = array[i]; // NEEDED ARRAY ELEMENT
}

Upvotes: 2

Related Questions