Question #289023

Task #7: Arrays and Methods


In this task, you are being asked to write methods that manipulate arrays in Java.


Write a method called sumOfArrays which will take two integer arrays as argument and


return an integer array having the sum of these two arrays.


You may use the following header for this method:


public static int[] sumOfArrays(int[] arrayA, int[] arrayB)


For example, if we pass {2, 4, 9, 12, 15, 5} and {7, 4, 3, 6, 2, 9} to this


method, then the method should return {9, 8, 12, 18, 17, 14} as an integer array.


NOTE: Declare and initialize the array without taking input from user.


1. Create a program called SumArraysLab2.java.


2. Correctly display appropriate messages.

Expert's answer

import java.util.*;


public class SumArraysLab2 {


	/**
	 * The start point of the program
	 * 
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		Scanner keyBoard = new Scanner(System.in);
		
		int arrayA[] ={2, 4, 9, 12, 15, 5};
		int arrayB[] ={7, 4, 3, 6, 2, 9};
		
		int sum[]=sumOfArrays(arrayA,arrayB);
		for (int i = 0; i < sum.length; i++) {
			System.out.print(sum[i]+" ");
		}
		
		keyBoard.close();
	}
	
	public static int[] sumOfArrays(int[] arrayA, int[] arrayB) {
		int sum[]=new int[arrayA.length];
		for (int i = 0; i < arrayA.length; i++) {
			sum[i]=arrayA[i]+arrayB[i];
		}
		return sum;
	}


}

LATEST TUTORIALS
APPROVED BY CLIENTS