user4183195
user4183195

Reputation:

Arithmetic operations on arrays in C

I am trying to apply arithmetic operations on the values of an array in C. For example, if I want to add a number x to each value of an array, should I add it separately to each value, or instead can I add x to the whole array (so would it automaticaly add it to each value of the array).

Upvotes: 3

Views: 10666

Answers (5)

Orlandriguez
Orlandriguez

Reputation: 1

Here there is a simple example that can help to understand the concept of operations over arrays /* Basic Maths on arrays */

void setup()
{
  Serial.begin(9600);
  int vector[] = {2, 4, 8, 3, 6};
  int i;
  for (i = 0; i < 5; i = i + 1) 
    {
    vector[i] = vector[i]*3;
    Serial.println(vector[i]);
    }
  }
void loop()
{  
}

Upvotes: 0

Jonathan Mee
Jonathan Mee

Reputation: 38919

Here is a simple function that would handle that:

void Add(int* toIncrement, int size, int increaseBy){
    for(int i = 0; i < size; ++i){
        toIncrement[i] += increasedBy;
    }
}

You can use it like this:

int thirteens[10] = {0};

Add(thirteens, 10, 13);

Note that if you wanted to write Add locally you could do that and avoid throwing a bunch of variables around.

Also if you wanted multiplication or something, just copy the function, change the function name and use *= in the place of +=.

Any modification of every element in an array is done this way in C.

Upvotes: 0

Xarouma
Xarouma

Reputation: 171

make a function that loops through your array and apply manualy your operation to each value contained in the array. There is no "buildin" function that will do that for you in C

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

if I want to add a number x to each value of an array, should I add it separately to each value

Yes, you need to do it in a loop. C does not provide operators for manipulating the entire array at once.

can I add x to the whole array

An expression that looks like adding an int to an array, e.g. array+x, will compile, but it is a different operation altogether: when an array name is used in an arithmetic operation, it is treated like a pointer to the initial element of the array, so the result of the array+x expression is the same as &array[x] (a pointer to element of array at index x).

Applying += to an array would not compile.

Upvotes: 3

Swann
Swann

Reputation: 2473

You have to run through the whole array like you would do in every language.

Upvotes: 0

Related Questions