Find the sum of a Javascript array and divide by its length - javascript

I'm almost embarrassed to ask this.
I'm a beginner programmer, and Javascript is very confusing to me. I managed to put together this much with the help of my instructor, but there are some simple things I can't get right.
I tried search Stack Overflow for a thread that would answer my question, but all of them I've seen contain code that I haven't learned about yet, so they're all just gibberish to me.
What I'm trying to do is add all the values of an Array and divide the sum by the array's length, ergo, find the average. The description of the assignment is find the average of any number of students' grades.
My two problems are
I can't figure out how to get the sum of all numeric values in the Array and,
For some reason, array.length returns one more than the actual length of the Array, even if I add a -1. (ex. if I enter 6 values, the array.length would return 7.)
I know where the problem is but I can't figure out what I need to enter. This assignment is due tomorrow, so anyone's time and effort is appreciated.
Here is my script:
<script type="text/javascript">
var allGrades = new Array();
var g = 0;
var l = 0;
var s = 0;
var t = 0;
do {
allGrades[g] = window.prompt("Please enter one grade for each window. After you enter a grade, enter an 'x' to see the average of the grades you entered.", "")
g++;
}
while (allGrades[g - 1] != "x")
for (l = 0; l < allGrades.length - 1; l++) {
s += allGrades[l] // Where I think the problem is
}
t == s / g - 1;
g == allGrades.length - 1; //
window.alert(g)
switch (t) {
case (t >= 90):
window.alert("Your average grade is " + (t) + ". " + "This is an A.")
break;
case (t >= 80 && t < 90):
window.alert("Your average grade is " + (t) + ". " + "This is a B.")
break;
case (t >= 70 && t < 80):
window.alert("Your average grade is " + (t) + ". " + "This is a C.")
break;
case (t >= 60 && t < 70):
window.alert("Your average grade is " + (t) + ". " + "This is a D.")
break;
case (t <= 60):
window.alert("Your average grade is " + (t) + ". " + "This is a failing grade.")
break;
}
</script>
I'm sorry if what I'm asking seems dumb. I've only been taking web programming for about two months, so I could really use some help!
Kyle

== is the comparison operator. You need to use the assignment operator (=) here:
t==s/g-1;
And the lines near it.
Also, for your own sake, do not use single-letter variable names unless you have a good reason for doing so.
Here's a cleaner way of writing the script:
var grades = [];
do {
var input = window.prompt("Please enter one grade for each window. After you enter a grade, enter an 'x' to see the average of the grades you entered.", "");
grades.push(parseFloat(input));
} while (input != 'x');
var sum = 0;
for (int i = 0; i < grades.length; i++) {
sum += grades[l];
}
var average = (sum / grades.length) * 100;
var grade;
if (average >= 90) {
grade = 'A';
} else if (average >= 80) {
grade = 'B';
} else if (average >= 70) {
grade = 'C';
} else if (average >= 60) {
grade = 'D';
} else {
grade = 'failing grade';
}
alert('Your average grade is ' + average + '. ' + 'This is a ' + grade);

t==s/g-1;
g==allGrades.length-1; //
Are both Comparisons, for assignment they should be
t=s/g-1;
g=allGrades.length-1;

Related

Multiplying Combinations Array

So I need a tiny bit of help with this code, Some background information: The user inputs a number, the code takes the number and outputs various combinations of numbers that multiply to it.
For example:
Input: 7
Output: (1,7)(7,1).
*But what really happens:
*
Input: 7
Output: (7,1)
I want my code to reverse the numbers as well, so it makes can look like it has two combinations
var input= parseInt(prompt("Please enter a number larger than 1"));
var arr = [];
if(input <= 1) {
console.log("Goodbye!")
}
while(input > 0) {
var arr = [];
var input = parseInt(prompt("Please enter a number larger than 1"));
for (var i = 0; i < input; ++input) {
var r = ((input / i) % 1 === 0) ? (input / i) : Infinity
if(isFinite(r)) {
arr.unshift(r + ", " + i)
}
}
console.log("The multiplicative combination(s) are: " + "(" + arr.join("), (") + "). ");
}
My code just need this tiny bit of problem fixed and the rest will be fine!
Your code has 2 infinite loop because you never change i and always increase input.
also in this line for (var i = 0; i < input; ++input) you never let i to be equal to the input so in your example (input=7) you can not have (7,1) as one of your answers. I think this is what you looking for:
var input = 1;
while(input > 0) {
input = parseInt(prompt("Please enter a number larger than 1"));
if(input > 1) {
var arr = [];
for (var i = 0; i <= input; ++i) {
var r = ((input / i) % 1 === 0) ? (input / i) : Infinity
if(isFinite(r)) {
arr.unshift(r + ", " + i)
}
}
console.log("The multiplicative combination(s) are: " + "(" + arr.join("), (") + "). ");
continue;
}
else{
console.log("Goodbye!");
break;
}
}

Finding the grade based on the best score

So my program wants the user to input the number of students and their scores. Based on the best score it will follow this grading scheme:
The score is > or = the best - 10 then the grade is A.
The score is > or = the best - 20 then the grade is B.
The score is > or = the best - 30 then the grade is C.
The score is > or = the best - 40 then the grade is D.
Anything else is an F
This is my code so far:
var readlineSync = require('readline-sync')
let scoreArray = []
let best = 0
students = readlineSync.question('Enter the number of students: ');
for (var x = 0; x < students; x++){
score = readlineSync.question('Enter Score: ')
scoreArray.push(score);
}
for (var i = 0; i < scoreArray.length; i++){
var data = scoreArray[i];
if(best < scoreArray[i]){
best = scoreArray[i];
}
if(scoreArray[i] >= (best-10)){
grade = 'A';
}else if(scoreArray[i] >= (best-20)){
grade = 'B';
}else if(scoreArray[i] >= (best-30)){
grade = 'C';
}else if(scoreArray[i] >= (best-40)){
grade = 'D';
}else {
grade = 'F';
}
console.log('Student ' + i + ' score is ' + scoreArray[i] +' and grade is ' + grade);
}
When I run the code it sometimes displays the correct grade and sometimes it doesn't. It should display this:
Enter the number of students: 4
Enter Score: 40
Enter Score: 55
Enter Score: 70
Enter Score: 58
Student 0 score is 40 and grade is C. Student 1 score is 55 and grade
is B. Student 2 score is 70 and grade is A. Student 3 score is 58 and
grade is B.
Instead it displays the grades A,A,A,B.
It looks like you're iterating over scoreArray and updating best along the way. You should first get the max score from scoreArray so you know the best to start with, and then iterate over scoreArray. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max for more info, but put var best = Math.max(...scoreArray); before your for loop, and then your conditional logic should work.
scoreArray = [49, 81, 72, 80, 81, 36, 58];
var best = Math.max(...scoreArray);
for (var i = 0; i < scoreArray.length; i++) {
var data = scoreArray[i];
if (scoreArray[i] >= (best - 10)) {
grade = 'A';
} else if (scoreArray[i] >= (best - 20)) {
grade = 'B';
} else if (scoreArray[i] >= (best - 30)) {
grade = 'C';
} else if (scoreArray[i] >= (best - 40)) {
grade = 'D';
} else {
grade = 'F';
}
console.log('Student ' + i + ' score is ' + scoreArray[i] + ' and grade is ' + grade);
}

Check for perfect number and print out divisors?

My goal is to create a program that checks whether the user input is a perfect number or not. It has validation for the numbers entered. If the input IS a perfect number, I'd like to print out each of the divisors. I tried using this method:
{
for(int number=2; number <= 10000 ; number++)
perfect(number);
return 0;
}
void perfect(int number)
{
int total = 0;
for (int i = 1; i < number; i++)
{
if (number % i == 0)
total += i;
}
if (number == total)
{
for (int x = 1; x < number; x++)
{
if (number % x == 0)
cout << x << " + ";
}
cout << " = " << number << endl;
}
}
However, I was unable to get the desired effect. I am very new to javascript and am struggling with inserting code in the correct way. Does anyone have a suggestion for how I can get the desired effect? Here is the code I have already written:
function check_prime() {
var input = document.getElementById("enteredNumber").value;
var number = parseInt(input);
if (isNaN(number)) {
alert("Oops! Please enter a valid number.");
document.getElementById("enteredNumber").value="";
document.getElementById("result").innerHTML = "";
document.getElementById("enteredNumber").focus();
}
else if (input.length === 0) {
alert("Please enter a number.");
document.getElementById("enteredNumber").focus();
}
else if (!isNaN(number)) {
if (is_perfect(number)) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number." ;
}
else {
document.getElementById("answer").innerHTML = "I'm sorry. " + number + " is not a perfect number. Try Again.";
}
}
else {
document.getElementById("answer").innerHTML = "Please enter a number.";
}
}
function is_perfect(number)
{
var temp = 0;
for(var i=1;i<=number/2;i++)
{
if(number%i === 0)
{
temp += i;
}
}
if(temp === number)
{
return true;
}
else
{
return false;
}
}
function clear_textbox(){
document.getElementById("answer").innerHTML = "";
document.getElementById("enteredNumber").value="";
document.getElementById("enteredNumber").focus();
}
I'd suggest revising your is_perfect() function to return an array of divisors if the number is perfect and null if the number is not perfect. Then the calling code has the divisors available for display when the input is a perfect number.
function is_perfect(number) {
var temp = 0;
var divisors = [];
for(var i=1;i<=number/2;i++) {
if (number%i === 0) {
divisors.push(i);
temp += i;
}
}
return temp === number ? divisors : null;
}
Then:
var divisors = is_perfect(number);
if (divisors) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number.";
// display the divisors somewhere; the alert is just for show
alert("Divisors: " + divisors.toString());
} else {
...
}
[Note: In an earlier version of this answer, I had initialized temp to 1 and divisors to [1] and had started the loop at 2, on the theory that 1 is always a divisor. Unfortunately, that's wrong, since 1 is not a proper divisor of 1. The revised version of is_perfect() now returns null for an argument of 1 instead of [1]. An alternative fix would have been to test explicitly for the case number === 1, but that's uglier (if perhaps a tiny bit more efficient, since it avoids one % evaluation).]
so I use 2^(n-1)*(2^n -1) formula (to generate a perfect number) and checking if last digit is 6 or 8 to check if x is perfect number.
Note: It's not perfect 100%
function pn(x) {
x = '' + x
for (var i = 0; i < Infinity; i++) {
perfnumgen = Math.pow(2, i - 1) * (Math.pow(2, i) - 1)
if (x === "" + perfnumgen && (perfnumgen % 10 === 8 || perfnumgen % 10 === 6))
return true
else if (perfnumgen > x)
return false
console.log("" + perfnumgen)
}
}

guessing game in javascript using while loop and unlimited guesses

var x = Math.floor(Math.random() * 100) + 1;
var hint = 'Guess my number, 1-100!';
var userIsGuessing = true;
while (userIsGuessing) {
var guess = prompt(hint + ' Keep guessing!');
userIsGuessing++;
if (guess < x && (x - guess) < 15) hint += ' A little too small!';
else if (guess < x && (x - guess) >= 15) hint += ' Way too small!';
else if (guess > x && (x - guess) < 15) hint += ' A little too big!';
else if (guess > x && (x - guess) >= 15) hint += ' Way too big!';
else(guess === x); {
document.writeln("You win! It took you" + userIsGuessing + " times to
guess the number.
");
}
}
I am trying to get this code to ask the user to guess a number between 1 and 100. Each time the user guesses, they get one of four hints. Then at the end, when they guess correctly, they will be told how many guesses it took them. I'm really stuck, please help.
How to begin..
userIsGuessing is a boolean, you should never use ++ on it.
You are writing in the document that the user win, you should alert it, like the prompt but ok.
Do not increment your hint, the ergonomics is terrible.
Check the comment
var x = Math.floor(Math.random() * 100) + 1;
var hint = 'Guess my number, 1-100!';
var userIsGuessing = false; // Boolean, begin at false
var count = 0; // Will count the try of the users
while (!userIsGuessing) {
var guess = prompt(hint + ' Keep guessing!'); count++; // We increment count
if(guess == x) { // CHECK IF RIGHT FIRST. EVER FOR THIS KIND OF STUFF.
userIsGuessing = true; // If right, then the Boolean come true and our loop will end.
alert("You win! It took you" + count + " times to guess the number.");
}
if (guess < x && (x - guess) < 15) hint = ' A little too small!';
else if (guess < x && (x - guess) >= 15) hint = ' Way too small!';
else if (guess > x && (x - guess) < 15) hint = ' A little too big!';
else if (guess > x && (x - guess) >= 15) hint = ' Way too big!';
}

Trying to find the average

I need to know why when I try to divide student 1,student 2 and student 3. I think it might be a looping error since the number that it give's me is numbering in the thousands but I don't see how that could be happening.
function averageOfThreeScores() {
var student1;
var student2;
var student3;
var end;
do {
student1 = prompt("What are the scorces of students 1?");
student2 = prompt("What are the scorces of students 2?");
student3 = prompt("What are the scorces of students 3?");
end = prompt("Would you like to end, type yes to end.");
var average = (student1 + student2 + student3) / 3;
if (average <= 59) {
document.write(average + " Your score is F <br/>");
} else if (average <= 69) {
document.write(average + " Your score is D <br/>");
} else if (average <= 79) {
document.write(average + " Your score is C <br/>");
} else if (average <= 95) {
document.write(average + "That's a great score <br/>");
} else if (average <= 100) {
document.write(average + "God like </br>");
} else {
document.write(average + " End <br/>");
}
}
while (end != "yes");
}
You expect the sum of student grades to be number but in fact they are concatenated as string. So if user types following values for example:
for student1: 13
for student2: 36
for student3: 50
The average will be 44550 because the sum will be (concatenated strings): 133650
To fix this, just convert the type to number when you get it.
student1 = parseInt(prompt("What are the scorces of students 1?"));
student2 = parseInt(prompt("What are the scorces of students 2?"));
student3 = parseInt(prompt("What are the scorces of students 3?"));

Categories

Resources