Function sum of array Learn programming Java

Lesson:

Functions


Exercise:

Function sum of array 14


Objetive:

Create a java program to calculate the sum of the elements in an array. "Main" should be like this:

public static void Main()
{ int[] example = {20, 10, 5, 2 };
Console.WriteLine(
__"The sum of the example array is {0}", __Sum(example));
}
}


Code:

public class Main
{
	public static int Sum(int[] example)
	{
		int total = 0;
		for (int i = 0; i < example.length; i++)
		{
			total += example[i];
		}
		return total;
	}

	public static void main(String[] args)
	{
		int[] example = {20, 10, 5, 2};
		System.out.printf("The sum of the example array is %1$s" + "\r\n", Sum(example));
	}
}