How can we utilize for loops to showcase the quotients and products of array elements?

Hi there! I'm struggling with an assignment that requires me to create some buttons using loops in JavaScript. The first button should multiply each number in an array by the number after it and display the result in a new array. The second button should divide each number in the array by the number after it and display the quotient. I've managed to input numbers into an array and display them, but I can't figure out how to use loops for the multiplication and division operations. Any help would be greatly appreciated!

  <!DOCTYPE html>
<html>
<head>
</head>
<body>

<input type="number" id="num" min="0" max="100">
<button onclick="myFunction()">Try it</button>
<button onclick="SortFunction()">Sort it</button>
<button onclick="AddFunction()">Add it</button>

<p id="demo"></p>

<script>
var myarray =[] ;
var text ;

function myFunction()
{
var fLen ;
var x = document.getElementById("num").value;
var i ;
myarray.push(Number(x));
fLen = myarray.length ;
text = "<ul>";
for (i = 0; i < fLen; i++)
 {
  text += "<li>" + myarray[i] + "</li>";
}
text += "</ul>";

document.getElementById("demo").innerHTML = text;
}

function SortFunction()
{
myarray.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = myarray;
}

function AddFunction()
 {
var sum = 0 ;
var fLen ;
var i ;
fLen = myarray.length ;

for (i = 0; i < fLen; i++)
 {
 sum = sum + Number(myarray[i]);
  }
document.getElementById("demo").innerHTML = sum;
 }
 </script>

Answer №1

To enhance your code functionality, you can include specific buttons and implement unique logic for each button within corresponding functions such as MultiplyNumbers() and DivideNumbers():

<button onclick="MultiplyNumbers()">Multiply pairs</button>
<button onclick="DivideNumbers()">Divide pairs</button>

Within these functions, it is crucial to validate the array values by checking if they are paired correctly using the length property and also verify if they are valid numbers using the isNaN() function. In case of any invalid value in a pair, you can set the result of the operation to 0 or any custom value. Furthermore, the Division function should ensure that the second number in each pair is not zero.

The first function utilizes a for loop while the second one operates with a while loop.

The provided snippet depicts these two functions working effectively based on the defined rules. If there are any oversights, feel free to point them out.

Answer №2

var myarray =[] ;
var text ;

function myFunction()
{
var fLen ;
var x = document.getElementById("num").value;
var i ;
myarray.push(Number(x));
fLen = myarray.length ;
text = "<ul>";
for (i = 0; i < fLen; i++)
 {
  text += "<li>" + myarray[i] + "</li>";
}
text += "</ul>";

document.getElementById("demo").innerHTML = text;
}

function SortFunction()
{
myarray.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = myarray;
}

function AddFunction()
 {
var sum = 0 ;
var fLen ;
var i ;
fLen = myarray.length ;

for (i = 0; i < fLen; i++)
 {
 sum = sum + Number(myarray[i]);
  }
document.getElementById("demo").innerHTML = sum;
 }
 
 
 // updated code
 var secondArray=[];
 function multiplyFunction(){
   var temp =  document.getElementById("num").value;
   for(i=0;i<myarray.length;i++){
      secondArray.push(Number(temp) * myarray[i]);
   }
   // show new array ..
     text = "<ul>";
     for (i = 0; i < myarray.length; i++){
       text += "<li>" + secondArray[i] + "</li>";
     }
     text += "</ul>";
     document.getElementById("demo").innerHTML = text;
   //
 }
 
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<input type="number" id="num" min="0" max="100">
<button onclick="myFunction()">Try it</button>
<button onclick="SortFunction()">Sort it</button>
<button onclick="AddFunction()">Add it</button>
<button onclick="multiplyFunction()">Multiply</button>
<button onclick="divideFunction()">Divide</button>

<p id="demo"></p>

</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process to alter a DIV's background color when hovering over a hyperlink?

Is it possible to change the background image of a div when hovering over different links? For example, hovering over link1 displays one background, link2 shows another, and so on. <div style="background: url(image1.jpg) no-repeat right; "> <a ...

What is the process of encapsulating elements within a container?

Recently I came across an interesting HTML string: var form = '<form data-hint="blah">' + '<label for=\"password0\">Password0</label>' + '<input type=\"pa ...

The method .replace() is used to substitute instances within a string

I have set up input fields for users to enter tags. For example, if a user enters "xyz_DTL_D, John_D" it will be stored in the tagArr[] array. My goal is to replace the input "_D" with an empty string. So I created the following code: var dailycheck = ...

Dealt with and dismissed commitments in a personalized Jasmine Matcher

The Tale: A unique jasmine matcher has been crafted by us, with the ability to perform 2 key tasks: hover over a specified element verify the presence of a tooltip displaying the expected text Execution: toHaveTooltip: function() { return { ...

Submitting a Django form seamlessly without reloading the page

Currently using Django-Angular, I am attempting to submit a form and access the data on the backend. Despite achieving this, I have noticed that the page reloads when saving the form. Is there a way to achieve this without having the page render? forms.py ...

Create a new `div` component for a child element when the button is clicked in ReactJS

I am attempting to incorporate a child div component (div-col inside of div-row) when the button is clicked. In this case, I am changing the card layout from grid to list view using Bootstrap classes. If the current view is set to grid view: <div class ...

Trouble aligning dynamic inline-block <h1> tag with text-align: center

One of my Angular directives has a feature that scrolls through words in an array and presents them as if they are being typed out in real-time. I'm facing an issue with aligning the h1 tag that displays these dynamically changing words to be centered ...

Interactive Checkbox Generated in Jquery UI Accordion Header

I need help creating an accordion with checkboxes in the headers dynamically populated from a database. I have tried using the click() function to prevent the accordion from activating when checking the checkbox, but since the accordion is generated dynami ...

Ways to distinguish XmlHttpRequest Access-Control-Allow-Origin issues from regular network errors

When making an ajax request, there is a possibility of encountering an error, indicating a failure to establish communication with the intended target (no status code returned). To handle these errors, you can use the following code: var oXhr = new XMLHt ...

Run parser functions without the need for a main method

When attempting to call the parserAction() method within another servlet class, I am receiving an empty array. I am unable to output the nouns within my servlet. However, when running this code with the MAIN METHOD, the noun array is printed correctly. Wha ...

What could be causing the malfunction in the cloning of the carousel item?

My goal was to create a carousel that displays multiple images in one slide. However, I encountered an issue where once the fourth image is reached, the other three images are forcibly hidden. I want to give credit to the original creator of this code snip ...

Add an image tag to the Canvas element

I'm attempting to add an image to a canvas element. Consider this code snippet (http://jsfiddle.net/n3L6e1wp/). I am aiming to replace the text shown in the canvas with an img tag. I have attempted to substitute the content of the div with: <img s ...

What is the correct way to create a constant array containing multiple structures with fixed values?

When working in the 'C' programming language, I encountered the following scenario: typedef struct { int aaa; int bbb; } My_Struct; I needed to create a constant script for a regression test containing multiple instances of My_Struct, eac ...

The issue persists with UIkit modal element remaining in the DOM even after the parent component in Vue.js is destroyed

In my Vue app, I am utilizing the UIKit modal. UIkit.modal(element).show(); // This adds the class uk-open and sets style to display:block UIkit.modal(element).hide(); When I hide the modal, it simply removes the class uk-open and the inline style of dis ...

When using html-webpack-plugin with webpack 2, there is no need for a starting slash '/'

I am in the process of migrating my webpack 1 project to webpack 2. Most of it is working smoothly, except for the issue I am facing with html-webpack-plugin: When using it in webpack 2, the script tag that gets generated looks like this: <script typ ...

How to send a form data through a POST request in Vue.js

There is an endpoint available for submitting data using a POST request, http://localhost:3000/entry The required keys are fname, lname, age By sending a POST request to the specified endpoint, a new entry will be created. Currently, I am attempting to ...

Looking to create a clone of an HTML element, make some modifications, and extract the HTML string without impacting the DOM?

After working with some HTML code, I encountered the following: <div style="background:red;width:900px;height:200px" id="wrap"> <div id="inner" style="width:300px;float:left"> ... </div> </div> The tasks at hand are ...

The session disappears after redirecting using AJAX

I am currently working with an index.html login page on my local machine, which includes a JavaScript file called index.js. This file is responsible for making an ajax call to authenticate usernames and passwords against an index.php page hosted on a remot ...

What is the process of passing a JavaScript variable to PHP with AJAX?

In the given scenario, I have an HTML file that is intended to display the content of a text file at div id="myDiv". The text file content will be read by PHP. However, there seems to be an issue in retrieving the content from the text file. I need assis ...

Troubleshooting an Ajax Error

Encountering an issue when trying to bind two components (checkbox and label) by using the "for" tag attribute for the label and the "id" tag attribute for the checkbox. An ajax debug error is thrown: "Cannot bind a listener for event "click" on element "v ...