Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
I am having trouble getting a JavaScript while loop to run with a prompt and a counter

In my program I have a prompt first that asks for the user to enter a grade and then a while loop which says while the grade does not equal -1 and an if to check if the grade is between 0 to 100. I have an else statement with a counter called "count" incrementing by one afterwards and then printing the grade within a table. The program then asks for the grade again until a -1 is pressed.

Here is my code.

 var count = 0;
 var total = 0;
 var grade;
 var avg = 0;
 grade = prompt('Enter grade(-1 to stop)');   
 while (grade != -1) {
 if (grade < -1 || > 100) {
 grade = prompt('Enter grade again');
 }
 else
 count++;  
 document.write('<tr>');
 document.write('<td>Grade ' + count  '</td>');
 document.write('<td width="50">' + grade '</td>');
 document.write('</tr>');
   
 grade = prompt('Enter grade(-1 to stop)');
 total = total + grade;    
 document.write('</table>');
 avg = total / count;
 document.write('Semester Average: ' + avg); 

}

When a negative 1 is entered it should add of the total number of all grades, and then calculate an average by dividing the count by the total. This will not run. Any tips would be appreciated.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

for your problem you need to use Do While instead of While else...

Do { This } while {grade = -1}

didn't understand your semester average calculating techniques. Hopefully below code will solve your problem. thanks

var count = 0;
var total = 0;
var grade;
var avg = 0;


do { 
grade = prompt('Enter grade(-1 to stop)');
count++;  
document.write('<table><tr>');
document.write('<td>Grade ' + count  + ': </td>');
document.write('<td width="50"> ' + grade + ' </td>');
document.write('</tr>');


total = total + grade;    
document.write('</table>');
avg = total / count;
document.write('Semester Average: ' + avg +'<br /><br />');
}
while (grade != -1) {
    --total;
    alert("You have input -1 to stop");
 }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!