Write a Java Code for the following. Please also note that in the main function,
ID: 3628932 • Letter: W
Question
Write a Java Code for the following. Please also note that in the main function, u can only call question 11 and no coding should be there.
11. Write a function that finds the sum of all the numbers in an array of integers. Test your
function with two arrays and print the resulting sums.
// example output
The sum of {2, 6, 4} is 12
The sum of {11, 2, 4, 1} is 18
Please do not input any values from the user.
Note: printing should only be done in question11 function
Example template:
public class One
{
public static void question11()
{
int sum = calcSum(5);
System.out.println("The sum of 1 to 5 is " + sum);
}
public static int calcSum(int y)
{
...
return sum;
}
...
}
Explanation / Answer
please rate - thanks
import java.util.*;
public class Main
{public static void main(String[] args)
{int a[]={2, 6, 4};
int b[]={11, 2, 4, 1};
sum(a);
sum(b);
}
public static void sum(int a[])
{int i,sum=0;
for(i=0;i<a.length;i++)
sum+=a[i];
System.out.print("The sum of {");
for(i=0;i<a.length-1;i++)
System.out.print(a[i]+", ");
System.out.println(a[a.length-1]+"} is "+sum);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.