How to subtract 3 from each number in an array and save it in the next array

Viewed 53

Hi Guys I'm trying to subtract 3 from each entry in an array and save it in another array.

int[] messageA = {68, 70, 87, 68, 35, 72, 86, 87};
int[] messageB = {0, 0, 0, 0, 0, 0, 0, 0};

(what should Read messageB)

int[] messageB = {65,67,84,65,32,69,83,84};

I did this but of course is not working but not sure how to continue

void setup() {
  for (int i = 0 ; i=messageA.length; i++){
    messageB[]=messageA -3;
  }
}

thanks in advance

2 Answers

Your code is probably not the most efficient way to get it done, but it should work, provided you fix the errors:

void setup() {
    for (int i = 0 ; i < messageA.length; i++){
        messageB[i] = messageA[i] - 3;
    }
}

You forgot to index each array with the number i, and also used a = instead of a < in your for loop condition.

I'm assuming that you mean that you want to take an array and subtract 3 from each element and save it in a new array. Here's one way to do that:

int[] missatge_xifrat = {68, 70, 87, 68, 35, 72, 86, 87};

void setup() {
  int[] messageB = new int[missatge_xifrat.length];
  for (int i = 0; i < missatge_xifrat.length; i++) {
    messageB[i] = missatge_xifrat[i] - 3;
  }
}
Related