Table of Contents
show
Example: 3A
Write a JavaScript to find sum of elements in array using function (prompt the inputs from user)
Script
const prompt = require("prompt-sync")(); // required to get input from user
function SumArrayElements(num) {
let sum = 0;
for (let j = 0; j < num.length; j++) {
sum += num[j];
}
return sum;
}
const input = prompt("Enter the number of elements");
let a = [];
for (let i = 0; i < input; i++) {
let t = prompt("enter the number for \t" + i + " \t location \t");
a[i] = parseInt(t); // convert string to integer
}
console.log("Elements are:");
for (let i = 0; i < input; i++) {
console.log("a[" + i + "]:" + a[i]);
}
const result = SumArrayElements(a);
console.log("sum of array elements:" + result);
Output
Views: 9