Programming with JavaScript

⌘K
  1. Home
  2. Docs
  3. Programming with JavaScri...
  4. Practice Programs
  5. Sum of elements in array using function

Sum of elements in array using function

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

Loading

Views: 9

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments