What is the process for implementing a loop within a function using a separate function?

As a Java newbie enrolled in a university course, I have been tasked with designing three functions. The first function is to find the difference between each adjacent pair of numbers in an array, the second function is to calculate the total sum of all numbers in the array, and the third function involves using the previous two functions to write a program. However, I am struggling with implementing the final function as my tutor is currently on holiday. Below is the code that I have managed to write so far. While I don't want someone to do the coding for me, any advice on how to proceed would be greatly appreciated. Specifically, I need help on looping the difference function through the array and storing the results in a new array. If anyone could point out where I might be going wrong, I would be very grateful!


var numberArray = [10, 9, 3, 12];

function difference(firstNumber, secondNumber) {
    if (firstNumber > secondNumber) {
        return (firstNumber - secondNumber);
    } else {   
        return (secondNumber - firstNumber);
    }
}

function sum(numberArray) {
    var numberTotal = 0;
    for (var i = 0; i < numberArray.length; i++) {
        numberTotal += numberArray[i];
    }
    return numberTotal;
}

function calculateDifferences() {
    var differencesArray = new Array(numberArray.length);
    
    for (var j = 0; j < numberArray.length; j++) {
        if (j === numberArray.length - 1) {
            differencesArray[j] = difference(numberArray[j], numberArray[0]);
        } else {
            differencesArray[j] = difference(numberArray[j], numberArray[j + 1]);
        }
    }
    
    return differencesArray;
}

Answer №1

It appears that there is an issue with your implementation of the "calculateDifferences" function.
The correct version should look like this:

function calculateDifferences()
{
var newArray = new Array (numberArray.length);
for (var i = 0; i < numberArray.length - 1 ; i = i + 1) {
/*
The function "difference" requires two parameters (firstNumber, secondNumber) in its declaration, so make sure to provide two arguments that are adjacent elements in the array.
*/
newArray[i] = difference(numberArray[i],numberArray[i+1]); }
/ *
Calculate the difference between the first and last element of the array and assign it to the last element of the new array.
*/
newArray[numberArray.length - 1] = difference(numberArray[0],numberArray[numberArray.length - 1]);
return newArray;
}

Answer №2

Ensure to properly index the function createArray, just like how you are currently doing with numberArray[c].

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 are some ways I can safeguard my CSS from injected elements?

I have created an HTML widget that is inserted into various websites without the use of iframes. However, I am encountering issues where the CSS of some sites is affecting the appearance of my elements, such as text alignment, underlining, and spacing. Is ...

Here is how you can make a time-keeping device without relying on the pre-existing clock class

Exploring my programming skills, I decided to create a practice program where a clock ticks every second. Researching on this topic led me to either overly complex solutions or information that wasn't relevant to what I've learned so far. My aim ...

Storing array elements in a MySQL database through PHP and jQuery

Hello, I am in the process of populating a table by inserting multiple rows individually for each query. Here is the code snippet that shows how I am sending an array elements: The HTML markup: <form action="post.php" method="POST"> <h1>U ...

What is the process for accessing a URL using a web browser and receiving a plain text file instead of HTML code?

Hello there! I've created a simple HTML file located at that can display your public IP address. If you take a look at the code of the page, you'll notice that it's just plain HTML - nothing fancy! However, I'm aiming for something mo ...

Ways to condense list chart into a single item and utilize a select dropdown to display choices without the need to refresh the

As a novice in the realm of creating charts using pandas and converting them into JSON format, I am faced with the challenge of displaying numerous graphs while conserving space. I am seeking guidance on how to implement a filtering system to only show the ...

I'm having trouble with my Discord app command. Every time I try to use it, I keep getting the error messages "The application did not respond" and "Dispatching MESSAGE_SEND_FAILED." How

Having a good amount of experience in JavaScript, I was optimistic about developing a Discord application as it seemed quite manageable. Eventually, I successfully integrated the bot into a server and implemented a command that is now listed in Discord&apo ...

Generating a single string from an array of strings by utilizing loops

Is there a way to combine all the Strings in an array into a single String using loops? I need help with this process. public class HelloWorld { public static void main(String[] args) { String [] x = {"ab", "bc", "cd& ...

Encountering an error stating "cloudinary.uploader is undefined" while attempting to delete media files from Cloudinary

I'm currently developing a web application using express and node.js. In my project, I'm utilizing cloudinary for uploading media files. While uploading and accessing media works smoothly, I'm encountering an issue with deleting images from ...

Connect or disconnect an element to a JavaScript event handler using an anonymous function

I'm stuck on a basic issue... I have a custom metabox in my WordPress blog, and here's my event handler: jQuery('tr input.test').on('click', function( event ){ event.preventDefault(); var index = jQuery(this).close ...

Seeking assistance with reading individual characters from a file using C programming

I have a query regarding reading a file character by character and counting it using C programming language Below is the code snippet I am referring to: void read_characters(char** file_contents){ FILE *file_ptr = fopen(INPUT_FILE, "r"); char ...

Having difficulties creating an array due to identical id tags causing HTML to break in JavaScript

I've been grappling with this issue all day. Before delving into dynamic solutions, I'd like to create multiple divs with unique id tags or classnames rather than repeating ids. Whichever option proves simpler would be greatly appreciated. Curren ...

Utilizing this method for declaring functions in Angular

I'm currently learning about Angular and attempting to implement a controller. However, I've run into an issue where the ng-click is not working (the function is not being called). According to the Chrome extension Batarang, the function is defin ...

Transform the CSS animation to include a sliding down motion combined with a blur effect

Can the CSS transition be changed to allow for a sliding down effect with a blur effect? I am looking to change this CSS animation effect to match the gif image shown below. Is it achievable using JavaScript, CSS, or a combination of both? Any help in solv ...

Unexpected Outcome Arises When Applying Lodash's Debounce Function to Axios API Call

I keep encountering an issue with my app where it updates every time text is typed. I've implemented debounce on an axios request to queue them up until the timer runs out, then they all go at once. But I want to limit the requests to one per 10-secon ...

Creating a CSS animation that smoothly slides across the screen and unveils a hidden text/div once the animation is complete

I have been attempting to replicate the captivating CSS animations seen on a particular website: My goal is to imitate how the site: initially reveals a full-screen black div sliding away to the right progressively loads the black background (div ta ...

Choosing a portion of a polyline - Google Maps Application Programming Interface

Is it possible to select only a section of a polyline in a Google Map? I have markers that are added by the user and a polyline is drawn between the markers. The polyline between two markers represents the route between the two places. I want the user to b ...

Adjust the CSS of a nested div within the currently selected div upon page load

I am facing an issue with a page that users access by clicking through an ebook. Upon clicking a link, they are directed to a specific product on the page, and the URLs look like example.com/#product1 example.com/#product6 example.com/#product15, etc... ...

Problem Installing Express Sharp using Docker

When deploying via Docker, I encountered an error with sharp, even though it works fine on my workspace. I followed all the steps but still faced issues. Error: 'linux-x64' binaries cannot be used on the 'linuxmusl-x64' platform. P ...

Inquiring about the specifics of pointer behavior

Consider having an array int b[] = {2, 3, 4}; What allows a pointer to the first element &b[0] to point to elements of the array or values in general, while the pointer &b itself cannot? cout << (&b[0])[1]; // 3 cout << (&b)[0 ...

Component in Next Js fails to pass props when using getInitialProps

I am facing some challenges with Next Js and could really use some assistance. We have a component where I am utilizing "getInitialProps" to pass props to it during the server-side rendering process. However, no matter what I try, the props do not seem to ...