0

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--;
    }
}
6
  • Make direction 1 or -1. Then add it to i. But you need stop condition too. Commented May 4, 2020 at 19:18
  • Stop condition can be >= 0 Commented May 4, 2020 at 19:21
  • 1
    @LuQ232 Without a context the provided code snippet does not make a sense. Commented May 4, 2020 at 19:22
  • @VladfromMoscow I would guess it is making an LED to run left and right on 8-LED array. Not clear what array is for though Commented May 4, 2020 at 19:23
  • @EugeneSh. Yeah. You're right. In array im holding number of LED which will be turned on. like int array [] = {0b00000001,0b00000010,0b00000100,0b00001000,0b00010000,0b00100000,0b01000000,0b10000000}; Commented May 4, 2020 at 19:27

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

if ( i == 0 || i == 7 ) { direction *= -1; } would be even less typing, as long as the initial sign of direction is correct.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.