2

I have 2 arrays below and I must to display the sum, the average and to do a summary namely to display the course with the note.

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

My problem is my summary doesn't work, despite a supplementary loop...

        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>");
            for(var i = 0; i<tab_course.length; i++){
                document.write("Course " + course[i] + "<br>");
            }
        }

Do you have an idea please ?

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

</body>
anais_stem
  • 73
  • 1
  • 10
  • [why document.write is considered bad practice](https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) – Barmar Oct 04 '18 at 16:12

2 Answers2

1

course doesn't appear to be defined anywhere. I think you meant tab_course[i] instead.

(The console should be throwing an error over trying to access an index of an undefined variable. You should always check the console first when your JS code doesn't work as expected - error messages there can point you straight to the source of the problem.)

Robin Zigmond
  • 14,041
  • 2
  • 16
  • 29
1

Everything seems Ok to me except the course variable is missing on last loop It should be tab_course instead of course. Just fix this line and you're good to go.

document.write("Course " + tab_course[i] + "<br>"); // changed 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>Exercice 4.8</h2>
  </center>

</body>
Always Sunny
  • 29,081
  • 6
  • 43
  • 74