Discovering the minimum/maximum value within an array by iterating through each element

One of the tasks for my web development course is as follows:

In order to convince your boss to allow adjustable thermostats in the office suite, you need to demonstrate that significant temperature variations occur in different offices and within each office on different days. Your assignment is to create a program that lets employees enter the noon temperature for five days and then displays the highest, lowest, and average temperatures. You should use a For loop to record the temperatures (Tip: Start by initializing variables for the highest and lowest temperatures with the first reading, then compare subsequent readings to determine if they are higher or lower.) Remember to use the parseFloat() method to convert temperature inputs into decimal numbers and display the average to one decimal place.

How can I calculate the average temperature?

<!DOCTYPE HTML>
<html>
<body>
    <script type="text/javascript">
    var high; // variable for highest temperature
    var low; // variable for lowest temperature
    var avg; // variable for average temperature

    var temperatures = [];

    for (var i = 0; i < 5; i++) {
        high = temperatures[0];
        low = temperatures[0];

        temperatures.push(parseFloat(prompt("Enter the temperature for day " + (i+1))));

        if (high < temperatures[i]) {
            high = temperatures[i]; }
        if (low > temperatures[i]) {
            low = temperatures[i]; }

    }

    document.write("The highest temperature is " + high + ".<br>");
    document.write("The lowest temperature was " + low + ".<br>");
    document.write("The average temperature was " + avg + ".");
    </script>
</body>
</html>

Answer №1

Starting Point:

@Emily, I've provided a snippet below to help you begin using a for loop for gathering user input.

var temperatures = [];

for (var i = 1; i <= 5; i++) {
    var temperature = prompt('Enter temperature for day ' + i);
    // Process input and add it to the temperatures array
}

Moving Forward:

Great job! You now have an array called temperatures containing 5 temperature values. In the revised example below, I've split the line for capturing and pushing the value into separate statements for clarity. See below:

var temperature = prompt('Enter the temperature for day ' + (i + 1));
temperatures.push(parseFloat(temperature));

One small adjustment that needs to be made is setting the high and low values inside the loop before any inputs have been added to the temperatures array. This aspect will need to be revisited.

Prior to tackling the average temperature calculation, let's address finding the sum of all values. The iterative nature of our loop allows us to accumulate these values as we progress through each input. Here's how:

var temperatures = [];
var total = 0;
var high;
var low;
var avg;

for (var i = 0; i < 5; i++) {
    // Capture, parse, and append temperature to temperatures array
    var temperature = prompt('Enter the temperature for day ' + (i + 1));
    temperatures.push(parseFloat(temperature));

    // Add current temperature to total sum
    total += temperature;
}

As for determining the highest and lowest temperatures, your recent question update code would cause the high and low values to reset with every iteration of the loop, resulting in inaccurate comparisons. To rectify this, consider initializing high and low to extreme values, guaranteeing user-entered temperatures will always surpass or fall beneath them. For instance:

var high = Number.NEGATIVE_INFINITY;
var low = Number.POSITIVE_INFINITY;

During each loop iteration, utilize your existing logic to compare the present temperature against the previous high and low values. Here's how:

var temperatures = [];
var total = 0;
var high = Number.NEGATIVE_INFINITY;
var low = Number.POSITIVE_INFINITY;
var avg;

for (var i = 0; i < 5; i++) {
    // Capture, parse, and append temperature to temperatures array
    var temperature = prompt('Enter the temperature for day ' + (i + 1));
    temperatures.push(parseFloat(temperature));

    // Add current temperature to total sum
    total += temperature;

    // Compare high and low temperatures
    if (high < temperature) high = temperature;
    if (low > temperature) low = temperature;
}

Concluding Step:

If desired, there's room for further enhancements in this code. However, such improvements may extend beyond the initial question scope.

To explore potential enhancements, consider utilizing functions like Math.min(), Math.max(), and apply(). If interested, I can furnish additional code snippets demonstrating how these functions can aid in determining high and low temperatures, along with employing Array.prototype.reduce for calculating averages.

Answer №2

In order to properly set values in alltemp, you must ensure that they are assigned based on certain conditions. Here is a demonstration of how this can be achieved (using a for loop, although there are more efficient methods available): https://jsfiddle.net/wvajgtdx/

var numbers = [5, 23, 11, 65, 9, 32],
    highest = lowest = nums[0];

for(var j = 0; j < numbers.length; j++) {
    highest = Math.max(highest, numbers[j]);
    lowest = Math.min(lowest, numbers[j]);
}

alert("The highest number is " + highest);
alert("The lowest number is " + lowest);

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

Creating data structures for visualizing in vis.js (Converting PHP to JavaScript)

Attempting to transfer information from a GraphDB (Neo4J) using PHP to interact with JavaScript and display the data with vis.js. Here's my progress so far: Retrieving data from Neo4J and storing it in a PHP array: Array ( [0] => Arra ...

Troubleshoot remote debugging in WebStorm when using Nodemon

Utilizing Nodemon has significantly increased my development speed by automatically restarting my app whenever I make changes. Due to the inability of WebStorm debug to work seamlessly with Nodemon using standard methods (%NODE_DEBUG% or --debug-brk), I h ...

Combining results from two streams in RXJS to create a sorted array

I currently have two different streams which I will name as follows: const firstStream = Rx.of([ { first: 'first', }, { third: 'third', } ]); const secondStream = Rx.of([ { second: 'second' }, { four ...

Differentiating programmatic from operational errors with the use of promise-based node.js programming: A comprehensive guide

Node.js is a new adventure for me and I'm really enjoying it. However, I'm struggling to grasp proper error handling techniques. While the internet offers plenty of resources on this topic, most of them focus on callback-based programming which ...

Encountered an issue while trying to set up mocks with $route in vue-test-utils

I am currently practicing test referencing by using a mock router. Here is the code I am working with: NestedRoute.vue <template> <div> <div>Nested Route</div> <div class="username"> {{ $route.params.username ...

Protractor struggles to locate Angular framework

I am experiencing issues with Protractor recognizing that Angular is loaded and operational. Upon opening Chrome, my application fully loads in the browser, confirming that Angular is indeed loaded and running correctly. Here is the configuration file: e ...

What is causing my sorting algorithm to produce inaccurate results?

After finding this sorting function as the best answer to my question, I tested it with example data and it worked perfectly. However, when I tried it with my actual data, it didn't work as expected and I'm not sure why. You can view my data her ...

Guide on retrieving POST data in sveltekit

Hello, I'm new to sveltekit and I am trying to fetch post data in sveltekit using a POST request. Currently, I am utilizing axios to send the post data. const request = await axios .post("/api/user", { username, email, ...

Creating clickable phone numbers in JSON elements for browser display to enable direct calling action

There is a Phone.json file with the following contents: { "Call": "Hi, Please contact the custom care at (119)239-9999 for further discussions" }, { "Call": " For emergency dial 911 as soon as possible" } The goal is to dis ...

Executing statements within a loop sequentially in jQuery: Best practices

I'm working on developing a program that will display different images in a loop when clicked. To achieve this functionality, I implemented jQuery to trigger a function upon clicking an image, which then cycles through all the images by updating the " ...

Collaborating with multiple forms and files in PHP using jQuery and AJAX operations

Need help with the title for this question. There are two input fields and buttons in index.php <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST"> <input type="text" class="for ...

How to dynamically adjust the height of a content div in CSS while maintaining fixed headers and foot

Seeking assistance with CSS layout from this amazing community. Desired layout includes a header, footer, left pane, and content area. Current CSS code provided but looking for better solutions. Image of desired layout included along with existing CSS a ...

Parse the file and save each word individually into a two-dimensional array

I've been attempting to read from a text file word by word and then store the words in a 2D array so that I can access and use them individually. I have experimented with using fscanf and malloc, but I am uncertain about how to properly implement them ...

The global JavaScript variable is refusing to be posted during the DataTable Ajax request

I've been struggling to send an additional custom value to my MVC controller for a server-side data table. Despite trying various approaches, the value I want always ends up being null in my view model. Here is my code snippet: $(document).ready(func ...

Guide on implementing automatic callbacks with AJAX

I am facing an issue with my index page that has one input tag and one division. There is an ajax function that retrieves data from the server, but I am encountering a problem. When I enter a single letter, it returns 3 records. Then, if I add another lett ...

Angular retrieves elements between indexes following ordering

After applying the orderBy on a table, the ordering is lost and the values of $index are from the sorted array rather than the original one. For example, if you have an items array with values ['orange', 'banana','potato',&apo ...

What is the reason for the presence of HTML tags in the response from PHP when using AJAX

My code is causing an ERROR instead of SUCCESS due to the presence of HTML tags. What mistake am I making? Below is the snippet of my HTML code: <head> <title>HTML Window</title> <meta charset="UTF-8"> <script src=" ...

Invalid hook usage detected. Hooks are only allowed to be called within the body of a function component

I encountered an error while trying to display records in a table using React. The error message reads as follows: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reason ...

JavaScript: Remove duplicate values from one array by comparing and utilizing a search filter against another array

There are two arrays available: public favoriteTeams: any[] = [ { name: 'Team Batman' }, { name: 'Team Superman' }, { name: 'Team Darkseid' }, { name: 'Team Wonder Woman' } ]; public searchTeams: any[] = [ ...