The following code example shows how to Find the Sum of Array Elements in JSP. So, we need to define a function that computes the sum of array elements. Therefore, we use the declaration block to define the function. Further, we need to use the scriptlet that contains the function call.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sum of Array Elements...</title>
</head>
<body>
<H1>Summation of Array Elements</H1>
<%! int findsum(int myarray[])
{
int sum=0;
for(int i=0; i<myarray.length; i++)
{
sum+=myarray[i];
}
return sum;
}
%>
<%
int arr1[]={12,-2,38,74,15,96,-97,28,-129,1350}, j;
out.print("<b>Array Elements are </b><br>");
for(j=0; j<arr1.length; j++)
out.print(arr1[j]+ " ");
out.print("<br><br><b>Sum of Array elements : </b>" +findsum(arr1));
%>
</body>
</html>
Output
Sum of Array Elements…
Summation of Array Elements
Array Elements are
12 -2 38 74 15 96 -97 28 -129 1350
Sum of Array elements : 1385