"Repetitive cycling, showcasing, and organizing elements in

I have two arrays displayed below and I am trying to calculate the sum, average, and create a summary showing the course along with the grade.

grades = new Array();
courses = new Array("Mathematics", "Statistics", "Algorithm");

However, my summary is not working as expected, even after adding an extra loop...


	grades = new Array();
    courses = new Array("Mathematics", "Statistics", "Algorithm");

    function main(){

        var sum = 0;
        var average = 0;

        for(var i = 0; i<courses.length; i++){
            var note = parseInt(prompt("Enter the grade for " + courses[i] + ": "));
            grades.push(note);
            sum += note;
        }

        average = sum / 3;

        document.write("Sum of grades: " + sum + "<br>");
        document.write("Average grade:  " + average + "<br>");

        document.write("Summary : " + "<br>");
        for(var i = 0; i<courses.length; i++){
            document.write("Course: " + courses[i] + " - Grade: " + note[i] + "<br>");
        }
    }

Any suggestions on how to fix this issue?

<body onload="main()">
    <center><h2>Exercise 4.8</h2></center>
</body>

Answer №1

Everything looks great, just a small error in the code - the course variable should be replaced with tab_course in the last loop. Once you make this change, your code will be good to go!

document.write("Course " + tab_course[i] + "<br>");
// updated from course to tab_course

tab_notes = new Array();
tab_course = new Array("Mathematics", "Statistics", "Algorithm");

function main() {

  var sum = 0;
  var average = 0;

  for (var i = 0; i < tab_course.length; i++) {
    var notes = parseInt(prompt("Course " + tab_course[i] + " : "));
    tab_notes.push(notes);
    sum += notes;

  }

  average = sum / 3;

  document.write("Sum is " + sum + "<br>");
  document.write("Average is  " + average + "<br>");

  document.write("Summary : " + "<br>");
  console.log(tab_course)
  for (var i = 0; i < tab_course.length; i++) {
    document.write("Course:" + tab_course[i] + ", Marks:" +tab_notes[i]+ "<br>");
  }
}
<body onload="main()">
  <center>
    <h2>Exercise 4.8</h2>
  </center>

</body>

Answer №2

subject seems to be missing from the code. Perhaps you intended to use tab_subject[i] instead.

(Make sure to check the console for any errors related to accessing undefined variables in your JavaScript code. Error messages there can help pinpoint the issue quickly.)

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 the ways to prolong or pause the JSON transformation process in NodeJS?

I'm currently extracting keywords using ExpressJS: /* * GET keywords. */ router.get('/keywords', function(req, res) { // Ensure user is logged in if (req.user) { var db = req.db; var user = req.user; db.col ...

Leverage access tokens in React.js frontend application

After successfully creating an authentication API using Nodejs, Expressjs, MongoDB, and JWT, I am now working on a small frontend application with React-js specifically for Sign-up and Sign-in functionalities. While I have managed to integrate the Sign-up ...

Bring your Electronic Catalogue to life with the addition of dynamic HTML content showcasing the latest

I am creating a digital magazine but I am facing the challenge of having to deal with 200 pages in jpg format. To streamline the process, I am looking for a way to use a combination of JavaScript and PHP to avoid manually coding for each of the 200 pages. ...

Tips for updating data within an array using a copied object

Just starting out with JavaScript Could you assist me with a basic inquiry, please? For instance, I have an array like this: const array = [{ id: 1, name: 'Ferrari', type: 'F40', price: '350 000$', countr ...

How can one access a specific element by its id that is located within an ng-template in Angular 6?

I have a question regarding accessing a button element inside an ng-template tag using its id in the TypeScript file. How can I accomplish that without encountering undefined errors? This is what I have tried so far: HTML <ng-template #popup > ...

Converting a multi-dimensional array to a one-dimensional array in C++ using memory addresses

While studying C++, I came across a fascinating concept about multidimensional arrays. The book explained that even though we can model multidimensional arrays in C++, the actual memory where the array is stored is one-dimensional. The compiler simply maps ...

Vue.js - v-for not automatically updating when assigning a new array is not functioning

I've been going through a Vue.js tutorial on YouTube: Vue.js Tutorial: Beginner to Front-End Developer https://www.youtube.com/watch?v=1GNsWa_EZdw&t=48s Most of the tutorial has been working fine for me, except for the issue with updating the nav ...

Sort Through Hexadecimal Color Codes

I am faced with a challenge of sorting through a vast array of hex colors (over 6500) and I need to eliminate the ones that are excessively dark or overly bright. Is there a distinguishing feature in the hex codes of dark and bright colors that can help m ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

How to Determine If a String Represents an HTML Tag Using jQuery

Checking if a string is an HTML tag can be tricky. I've tried various methods found on Google, but none have been successful so far: var v = $(string).html() ? 1 : 0; --or---------------------------------------------- var htmlExpr = new RegExp("/^( ...

What is the best way to retrieve past data using RTK Query?

When working with data retrieval using a hook, my approach is as follows: const { data, isLoading } = useGetSomeDataQuery() The retrieved data is an array of items that each have their own unique id. To ensure the most up-to-date information, I implement ...

Execute Mocha programmatically and transfer the output to a designated variable or function

I have configured a series of tests in mocha using ZombieJS and Chai. These tests are designed to load a website, verify if various services are booked correctly, and ensure they appear correctly to visitors on the site. My goal is for these tests to run ...

Incorporating Javascript into a .Net MVC 3 Project

It seems like there should be a straightforward solution to my question, but I'm struggling with it. I have an animation.js file that includes dependency_1.js and dependency_2.js in an include folder. Within my animation.js file, I load these dependen ...

Tips for storing STL geometry in a cache outside of the STLLoader event listener

I am attempting to read and cache a geometry from an STL file using Three.js STLLoader. I am utilizing an event loop callback to retrieve the data (similar to the STLLoader example). My intention is to store it in an external variable called "cgeom". Howev ...

Using AngularJS to implement a clickable functionality within a directive

Currently, I am in the process of implementing a drag-and-drop directive. When an element is dropped, I am adding a copy of that element to my div and appending the ng-click attribute to it in this manner: copy.append('<button class="close" ng-cli ...

Display a random div element in jQuery without specifying a specific class

I have a dynamic list that I am displaying in a div as shown below <div class="cards card1"> <div class="front"> <p>Front 1</p> </div> <div class="back1" style="display: none"> <p>Back 1</p> ...

Are we retrieving multiple APIs the right way?

Looking for some guidance on fetching two APIs in React. I have created two functions to handle this task and called them simultaneously within another function. Should I stick with this approach or move the API calls to componentDidMount? Additionally, I& ...

Regular expression for finding CSS key-value pairs

Currently, I am utilizing regular expressions to identify CSS values. The input string that needs to be matched is: font-size:25px;font-family:georgian;content:"' unicode given in pseudo &#169; '"; The specific regex pattern I am using fo ...

The Vue3 property 'x' is not recognized on type 'Function' as a global property

I have encountered a strange issue with my Quasar app. I am attempting to define a global variable that consists of metadata about the application in an object format. Despite successfully compiling the app and displaying the correct information on the HTM ...

Guide on incorporating an HTML element within a binding in Nuxt or Vue

I'm struggling with adding an HTML element <br /> inside a data bind. I want to modify the text "I like playing games" to include a line break, making it read as "I like playing <br /> games", but I can't seem to get it right within t ...