Looking to identify the maximum and minimum values within an array using user prompts

For our latest assignment, my teacher tasked us with creating a program to determine the highest and lowest marks among a group of up to 15 students. This means that we can input fewer than 15 students if needed. The user has to enter each student's name followed by their mark. Once all the names and marks are entered, the program should compare the marks to identify the highest and lowest ones.

CODE:

var Students = ["sn1", "sn2", "sn3", "sn4", "sn5", "sn6", "sn7", "sn8", "sn9", "sn10", "sn11", "sn12", "sn13", "sn14", "sn15"]; //array for student names
var Marks = ["sm1", "sm2", "sm3", "sm4", "sm5", "sm6", "sm7", "sm8", "sm9", "sm10", "sm11", "sm12", "sm13", "sm14", "sm15"]; //array for student marks

Students[0] = prompt("Enter Student 1's name.");
    if(Students[0].length == 0) { 
        Marks[0] = null
    } else {
        Marks[0] = prompt("Enter Student 1's mark.");

       //Code iteration repeated here multiple times for each student

}
console.log(Students[0] + " " + Marks[0]); //display the mark in console

//Further code for finding greatest and least marks is provided here.

PROBLEMS: 1. Currently, the program mistakenly identifies the first number as both the highest and lowest marks. For instance, entering 99 and then 100 will show 99 as the highest mark instead of 100. 2. Comparing numbers like 29 or 99 against 100 results in incorrect ranking due to how the comparison logic functions. 3. Negative numbers pose another challenge where -13 may incorrectly be labeled as the lowest when compared to -99. 4. Even when comparing 10 and 100 (including negative values), the program might wrongly prioritize 10 over the much larger value of 100.

It seems like you've put in considerable effort on troubleshooting these issues, especially considering this is your first experience with JavaScript. Should any further help be required before the Monday deadline, feel free to ask. Good luck!

Answer №1

Here is an illustration of how it can be achieved. Notice the process of validation and conversion of user input into a numerical value for comparison purposes. Only one primary loop is required; the while loops are utilized to ensure that the user inputs valid data.

It is not compulsory to store all the students' information in an array in order to showcase the highest and lowest scores.

var students = [];
var numOfStudents, highest = { mark:-1 }, lowest = { mark:101 };

// Obtain the number of students (ranging from 1 to 15)
while (isNaN(numOfStudents) || numOfStudents <= 0 || numOfStudents > 15)
    numOfStudents = parseInt(prompt('How many students? (1-15)', '1'), 10);

// For each student, collect their name and score
for (i = 1; i <= numOfStudents; i++) {

    var student = {};
    while (typeof student.name === 'undefined' || student.name == '')
        student.name = prompt('Enter Student '+i+' name:', '');
    
    while (typeof student.mark === 'undefined' || isNaN(student.mark) || student.mark < 0 || student.mark > 100)
        student.mark = parseFloat(prompt('Enter Student '+i+' score (0-100):', ''));
    
    // Determine if it's the highest or lowest score
    if(student.mark > highest.mark) highest = student;
    if(student.mark < lowest.mark) lowest = student;
    
    // Add the current student to the list (if desired)
    students.push(student);
}

// Output the results
document.body.innerHTML = highest.name + " attained the highest score of " + highest.mark + ". " + lowest.name + " received the lowest score of " + lowest.mark + ".";

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 simplest method for transferring data to and from a JavaScript server?

I am looking for the most efficient way to exchange small amounts of data (specifically just 1 variable) between an HTML client page and a JavaScript server. Can you suggest a script that I can integrate into my client to facilitate sending and receiving d ...

Re-rendering an array in Vue.js with sorted elements

I am working on a basic sorting user interface to sort comments based on certain values: Within the CommentsSection template: <div v-if="numComments" class="tabs d-flex"> <span class="text-muted">Sort by:</span> <div cl ...

The variable maintains the same value both inside and outside of the loop

I have a list of objects that provide information to a variable, which creates "markers": var markers = [ //testPOW { mesh: ["campDome","POW"], color: iconRed, location: {lat: 43.30985465943113, lng: 11.898409657895801}, visible: true, id: "TestPO ...

Navigating with buttons in the Material UI Drawer

I have implemented a Material UI drawer with some modifications. The original code used buttons, but now I want to navigate to a new page when a button is clicked. For example, clicking on the 'INBOX' button should take me to a page '/new&ap ...

Organizing content into individual Div containers with the help of AngularJS

As someone who is new to the world of AngularJS, I am currently in the process of learning the basics. My goal is to organize a JSON file into 4 or 5 separate parent divs based on a value within the JSON data, and then populate these divs with the correspo ...

Utilizing ng-model and ng-repeat in AngularJS to populate models with a list of objects

I need to call a POST function, and I have to compress the data in a web form into an object beforehand. I utilized ng-repeat to showcase all inputted data and initialized this value for input, but I am unsure how to utilize ng-model to store the data. I c ...

Converting HTML to PDF: Transform your web content into

I have a couple of tasks that need to be completed: Firstly, I need to create a functionality where clicking a button will convert an HTML5 page into a .PDF file. Secondly, I am looking to generate another page with a table (Grid) containing data. The gr ...

Angular.js can dynamically add a class to an element based on the current page being viewed

Currently, my goal is to assign the class post to my div with id #wrap when I am on the page /post. Here's what I have so far: $routeProvider when('/post', { templateUrl : 'views/post.php', controller : 'postCtrl&ap ...

An issue has occurred with NPM CI where the bindings are not available from watchpack-chokidar2:fsevents

After executing npm ci on GitHub Actions, I encountered the following error: Run npm ci npm ERR! bindings not accessible from watchpack-chokidar2:fsevents npm ERR! A complete log of this run can be found in: npm ERR! /home/runner/.npm/_logs/2021-09-17 ...

Encode a variable into base64 using the Buffer module in node.js

Attempting to convert a variable from an HTTP parameter to base64 using node.js and Buffer. Code snippet: var http = require("http"); var url = require("url"); http.createServer(function(req, res) { var parsedUrl = url.parse(req.url, true); var que ...

Verify if the radio element is marked as selected in the AJAX reply

My ajax response contains two radio elements and I need to check if they are checked in the response. I've tried using the code below to check the radio status but it's not working: $('#input[type=radio]').each(function(){ alert($( ...

Eliminate repetitive elements from an array using a specific merging algorithm

Here's a thought I have: If we have an array of objects like this: [ { "name": "Kirk", "count": 1 }, { "name": "Spock", "count": 1 }, { "name": "Kirk", "count": 1 } ] I would l ...

This particular JavaScript function is only designed to operate on the initial input box in the provided

I have a question regarding echoing rows of $data inside input boxes. I am using a JavaScript function that is supposed to copy the input value to the clipboard when the input box is clicked. However, I am encountering an issue - the function only works ...

Verifying the emptiness of a PHP array using JavaScript

Hey there, I've got a form set up for users to input one or more books into a database. If a user forgets to enter the title when adding just one book, a JavaScript alert pops up reminding them to fill it in. However, if they have two or more books an ...

Enhance the appearance of a bokeh plot with real-time updates using

My question is similar to the one found at this link. I have a website that includes various elements, such as a table and a bokeh plot. I want to update these elements based on user input. While I have figured out how to update the table, I am struggling ...

Utilizing Node.js and Mongoose, effortlessly update data in Mongo DB regardless of the existence of the collection

How can I update a field that may or may not exist? I attempted the following code: db.foo.update( { site: '"wisdom'}, { $set: {'club': 'fc barcelona'}}, (upsert=true) ) ...

Passing an object in an ajax call to a function: a comprehensive guide

@model IEnumerable<HitecPoint.BlackBox.Models.SMSReportModal> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"> </script> <script type="text/javascript"> var MyAppUrlSettin ...

Troubaling with AngularJS Routing issues

I am encountering an issue with my routing system. The "otherwise" case is functioning correctly, however, when I click on a menu item, the routing does not load the corresponding page automatically. Can someone assist me in identifying what is wrong with ...

Extracting timestamped text data from a simulated chat interface

I am looking to gather chat data from Twitch clips. These are saved moments from livestreams where viewer reactions are captured. Take a look at this example clip: While I can scrape all the data by watching the video and utilizing query selectors, my goa ...

Switching between a single checkbox and a group of checkboxes: A step-by-step guide

My goal here is to design a group of checkboxes. The "Search everywhere" option is initially checked by default. If you check any other checkbox, the "Search everywhere" box automatically unchecks. You're allowed to check multiple checkboxes, but once ...