0

Is there a way which i can multiply each number that is stored within an array by n.

For example,

public static int [] intArray = new int [] {1,2,3,4,5,6,7};

n = 3

it should output: 3, 6, 9, 12,15,18, 21.

I'm not sure how to do this, help would be appreciated!

1
  • Probably some kind of array map function. Most languages have a built-in version. Commented Feb 11, 2015 at 18:59

4 Answers 4

5

The Java 8 way, for a given n:

Arrays.stream(intArray).map(i -> i * n).forEach(System.out::println);
Sign up to request clarification or add additional context in comments.

Comments

3

This would be the simplest solution.

public class Test{
    public static void main(String[] args) {
        int n=3;
        int [] intArray = new int [] {1,2,3,4,5,6,7};
       for(int i=0; i<intArray.length; i++) {
           System.out.println(intArray[i]*n);
       }
    }
}

Comments

1

The functional approach would be to use Stream.map:

    int [] intArray = new int [] {1,2,3,4,5,6,7};
    int n = 3;
    System.out.println(Arrays.stream(intArray).map(i -> i * n).boxed().collect(Collectors.toList()));

Comments

0

If you want it to be super small,

int n = 3;
int[] intArray = blah;

for (int i : intArray) {
    System.out.println(""+i*n); //The "" is to make the number i*n a string
}

2 Comments

The ""+ is not needed. println can also output numbers.
Also, use methods like Integer.toString() instead of empty concatenation when you want to do such conversions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.