Multplying each element in an array

Hi, I wanted to make an array where each element is simply being multiplied by 2. Here is what I have so far. Help would be greatly appreciated

int expo(int[] array[]){
  int mult = 2;
  for (int i=0;i<array.length;i++){ //goes through each element of the array and multiplies by 2 
     int [] a1 = mult *array[i];
    
  }
  return mult;
}

Hello and welcome to the processing forum!

Great to have here with us!

can you show us a code that printlns an array?

That would be a good starting point

do you want one from this example? I have more code that is on a separate tab.

1 Like

Yeah, that would be awesome

void test_expo(int[] a, int[] expected){
  int[] test =  expo(a);
  if(compare_Arrays(test,expected)){
     println("Exp given (" + Arrays.toString(a) + ") outputs " + Arrays.toString(test) + "when expecting" + Arrays.toString(expected) + "PASS");
  } else{
      println("Exp given (" + Arrays.toString(a) + ") outputs " + Arrays.toString(test) + "when expecting" + Arrays.toString(expected) + "FAIL");
  }
}

I meant this:

println an array using a for-loop and println :

int[] array = { 
  7, 12, 14, 18, 22
};

for (int i=0; i<array.length; i++) { 
  println( array [i] );
}

Warm regards,

Chrisir

for more information read https://www.processing.org/tutorials/arrays/

Local variable mult isn’t declared as an array but as a single int.

In order to multiply each element in parameter array[] by 2, mults[] needs to be as big as array[].

We have to read array[]'s length field in order to know its size:
final int len = array.length;

And use it to declare mults[]:
final int[] mults = new int[len];

Alternatively we can invoke method clone() in order to get a shallow copy out of array[]:
final int[] mults = array.clone();

Last detail, you’re gonna need to return an int[] instead of just int:
int[] expo(int[] array[]) {

The example sketch below demos both approaches:

// https://Discourse.Processing.org/t/multplying-each-element-in-an-array/24827/8
// GoToLoop (2020/Oct/22)

static final int[] VALS = { 15, -3, 100, 0, };

void setup() {
  println(str(VALS));                // 15 -3 100 0
  println(str(expoNewArr(VALS)));    // 30 -6 200 0
  println(str(expoClonedArr(VALS))); // 30 -6 200 0
  exit();
}

static final int[] expoNewArr(final int... vals) {
  if (vals == null)  return new int[0];

  final int len = vals.length;
  final int[] mults = new int[len];

  for (int i = 0; i < len; mults[i] = vals[i++] << 1);

  return mults;
}

static final int[] expoClonedArr(final int... vals) {
  if (vals == null)  return new int[0];

  final int[] mults = vals.clone();

  for (int len = mults.length, i = 0; i < len; mults[i++] <<= 1);

  return mults;
}