I have a question, how do we wand to codes if I want to interchange the index elements in an array. Let say I have array of 8 elements,
int arr [8] = {0,3,5,7,9,12,17,19};
but i want to change so the:-
elements 0 interchange to elements 7,
elements 1 interchange to elements 6,
elements 2 interchange to elements 5,
elements 3 interchange to elements 4,
elements 4 interchange to elements 3,
elements 5 interchange to elements 2,
elements 6 interchange to elements 1, and
elements 7 interchange to elements 0.
Lets say you have 8 index cards with some numbers on them, and 8 outlines drawn on the table, with each card placed in an outline. There is one extra outline, off to the side, with no card in it.
How would YOU move the card with the value 19 on it to the spot where the card with 0 on it is? Only one card can be picked up at a time, so once you pick up a card, that card must be put down, in an outline somewhere before you can pick up another one.
wirered:
if I want to interchange the index elements in an array.
Rather than move the elements within the array - which is a slow process - just create another array to hold a sequence of the elements in the new order.
Suppose the data in the main array is 12,17,23,19,5 and you want to be able to access it as 5,12,17,19,23 then all you need is another array holding the values 4,0,1,3,2 and use that to index the elements in the main array.
There are ways of doing the swap without an intermediate variable but they could make the code more obscure so whether it is worth it and is applicable to the code in question is a matter for debate.
int arr[8] = {0, 3, 5, 7, 9, 12, 17, 19};
// so, that the output I expected will now become:
// {19, 17, 12, 9, 7, 5, 3, 0}
void setup() {
Serial.begin(19200);
Serial.print("{");
for (int i = 0; i < 8; i++) {
Serial.print(arr[7 - i]);
if (i < 7)
Serial.print(",");
}
Serial.println("}");
}
void loop() {}
Oh - hang on: you just want to reverse an array? Even easier:
// see http://forum.arduino.cc/index.php?topic=440473
int arr [8] = {0,3,5,7,9,12,17,19};
#define NELEMENTS (sizeof(arr)/sizeof(*arr))
for(int i = 0; i < NELEMENTS/2; i++) {
int foo = arr[i];
arr[i] = arr[NELEMENTS-i-1];
arr[NELEMENTS-i-1] = foo;
}
Is this a homework question? I love doing people's homework for them! It helps to dilute the value of holding a degree when half the people with degrees are academic frauds. You hire a guy with a BA in computing from Foo U, and it turns out he can't work out for himself how to use subtraction to reverse an array. Employers pretty quickly learn that degrees from Foo U are worthless.
Don't forget to include that comment - your lecturer will need to see it.
But why spend time reversing the array? That is just nonsens. The micro doesn't care if it's counting up or down... Just go through it in the reverse order