hi im very new to javascript and stuck doing my homework. My question is how do I add multiple inputs together in a do while loop? I am supposed to get all the inputs added together then divided by the amount of inputs to get the average. For example if the user were to input 7, 3, 5 and 2 then the answer will be 4.25.This is what I have so far.
var prompt;
var input = prompt("Please enter a number, input a negative number to stop");
var number = input >= 0;
var alert;
var sum = 0;
var sum2 = 0;
while (input <= 0) {
input = +prompt("Error enter a positive number to start");
}
do {
input = +prompt("Enter another number, a negative to stop");
sum += number;
//inputs added together goes here
} while (input >= 0);
alert(); //inputs added together divided by sum goes here
Hi try this version;
var num = 0, sum = 0, count = 0;
do {
num = parseInt(prompt('Enter Number'));
sum = num >= 0 ? sum+=num : sum;
count = num >= 0 ? count+=1: count; }
while(num >= 0);
console.log(sum + ' count is ' + count);
console.log(sum/count);
Basically I read from prompt, convert the input to integer, I sum the numbers if they are 0 or greater. I add 1 to the count if number is 0 or greater then I divide the sum by the count
Increase the value of sum2 to count the no input. And add a condition that if the user enter a negative value then the total will be divided by the no of inputs.
I have edited your code.
var prompt;
var input = prompt("Please enter a number, input a negative number to stop");
var number;
var alert;
var sum = 0;
var sum2 = 0;
while (input <= 0) {
input = +prompt("Error enter a positive number to start");
}
do {
input = +prompt("Enter another number, a negative to stop");
number=input;
alert(number);
sum += number;
sum2++;
if(input<0){
sum +=(-number);
alert("average"+(sum/(sum2-1)));
}
//inputs added together goes here
} while (input >= 0);
alert();
Hope it will help.
'use strict';
let input, sum = [];
do {
input = prompt("Enter another number, a negative to stop");
sum.push(input);
} while (input >= 0);
alert(sum.filter((a, b) => {return a + b}) / sum.length);
Related
I have an input field where by default I will have $0.00.
when I enter a number, say 1, the input should show $0.01,
again if I enter 2, the input should show $0.12
simultaneously if I press 3, 4, 5, the final output should be $123.45.
Now, If I click delete, it should remove 5, so output will be $123.4
again if I click delete it should remove 4, so output will be $123
If I add a number 2 again here, it should show, $123.2
Is it possible? I am stuck at the last 3 steps.
I have this so far,
let previousTip = 0;
const addingFunction = (value) => {
if(Number(value) <= Number(previousTip)) return Number(value).toFixed(2);
const addNumberRightToLeft = (baseValue, updatedValue) => ((baseValue * 10) + (updatedValue / 100)).toFixed(2);
previousTip = addNumberRightToLeft((Number(previousTip) || 0), value.length > 1 ? value.slice(-1) : value);
return previousTip;
}
my onClick event has
const tipString = addingFunction(e?.target?.value?.trim()?.replace(/[^\d.]/g, '') || '');
Any help will be really appreciated
Here are two functions that should do what you need. You can call the correct one depending on which key is pressed on onKeyPressed
I'm currently not able to test this, but the logic is there.
function addValueToNumber(number,value){
count = 0;
while (number%10 != 0){
number *= 10;
count ++;
}
number += value/10;
for (i=0,i<count-1,i++){
number /= 10;
}
}
function remove(number){
count = 0;
while (number%10 != 0){
number *= 10;
count ++;
}
number = number//10;
for (i=0,i<count-1,i++){
number /= 10;
}
}
I am trying to complete the following code to achieve the sum of numbers from 1 to 100(user's entry must be 1-100), using whileloop or doloop. I am new to this so, any help is much appreciated!
In the following code, I used prompt method to get the user entry. Wrote the code, to sum numbers; from 1 through the user's entry. I displayed the result in an alert box. Now, my challenge is I want to display an error message if the user's entry outside the 1-100 range. And after that, I do not want to do any calculations if user clicks cancel and stop displaying the prompt box.
<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers!=null && (isNaN(parseInt(numbers)) || parseInt(numbers) >100 || parseInt(numbers) <1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers !=null){
alert("Finally you entered a correct number");
}
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum+=counter;
counter++;
} while (counter<=numOfLoops)
alert ("sum=" +sum);
</script>
</head>
<body>
<script>
document.write("<h1>Sum of Numbers</h1>");
document.write("The sum of numbers from 1 to = " + numbers + " is = " +
+ sum + "<br><br>");
</script>
</body>
</html>
Simply move the calculation logic inside the condition where the user enters the correct input. This will make sure that the prompt closes automatically when you click on the cancel button (Prompt returns null when the user clicks on cancel)
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers != null && (isNaN(parseInt(numbers)) || parseInt(numbers) > 100 || parseInt(numbers) < 1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers != null) {
alert("Finally you entered a correct number");
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum += counter;
counter++;
} while (counter <= numOfLoops)
alert("sum=" + sum);
}
</script>
You could simply use a do…while to solve your problem, e.g.:
let n = null;
do {
n = parseInt(prompt('Enter an int number between 1 and 100'));
} while (isNaN(n) || (n < 1 || n > 100));
let sum = n * (n + 1) / 2;
alert('The sum of all int numbers from 1 to ' + n + ' is: ' + sum);
N.B. The sum of the first n integer numbers can be computed as n * (n + 1) / 2, with O(1) complexity - reducing the O(n) complexity of your for loop.
I can't get this program to output the average of the entered prompted numbers by a user. How else should i code it? Any help will be appreciated.
var gpas = [];
var gp;
var total = 0;
let count = 0;
var max = 0;
var min = 0;
var out = "";
while (i != "XXX") {
var i = prompt("Enter a gpa or XXX to Stop");
if (i != "XXX") {
gpas.push(i);
}
}
for (var i = 0; i < gpas.length; i++) {
out += gpas[i];
out += "<br/>";
}
count++;
total += gpas[i];
var avg = total / count;
out += avg;
document.getElementById('output').innerHTML += out + "<br/>";
the output is showing "NaN" instead of a valid number.
You can only use a variable that holds the sum of the numbers entered and then just divide it by the total numbers entered.
First approach infinite loop :
The first approach acts as the one you're using. Basically, we'll ask for a new number as long as we don't get the string "XXX".
/**
* #const output the span where to print the average.
**/
const output = document.getElementById('output');
/**
* #var avg stores the sum of the entered numbers.
* #var i keeps track of the number of numbers entered.
**/
let sum = 0,
i = 0;
/** basically while true increment i **/
while (1 && ++i) {
/** ask for a number or "XXX" to exit **/
const n = prompt(`Enter a number or enter "XXX" to exit :`, 0);
/** if "XXX" is entered break the loop (the only way to break that infinite loop) **/
if(n == 'XXX') break;
/** if something else than "XXX" is entered try to cast it to a float **/
sum += parseFloat(n);
}
/** print the average **/
output.textContent = (sum / (i - 1)).toFixed(2); /** why dividing by "i - 1" and not only "i" is because "i" is incremented even when we enter "XXX" **/
<div>average: <span id="output"></span></div>
This approach is not user friendly (the loop can't be exited unless "XXX" is typed) and may consume a lot of resources.
Second approach fixed number of numbers :
This approach asks the user to enter how many number he want to type then we ask him to type as many numbers as the one he typed earlier.
const output = document.getElementById('output');
/**
* #var n the number of numbers the user is going to type.
* #var sum the sum of these numbers.
* #var i a counter used to exit the loop when we reach "n" nummbers typed.
**/
let n = prompt('How many element do you want to enter ?', 2),
sum = 0,
i = 0;
/** while i + 1 < n and no need to manually break the loop **/
while (i++ < n) sum += parseFloat(prompt(`Enter a number (${i} remaining) :`, 0));
output.textContent = (sum / n).toFixed(2); /** now we know how many numbers entered from the beging thanks to the variable "n" **/
<div>average: <span id="output"></span></div>
parseFloat used to parse the numbers (in fact they're strings) entered by the user to floats.
toFixed is used to have only two decimal numbers when calculating the average.
while (i != "XXX") {
var i = prompt("Enter a gpa or XXX to Stop");
if (i != "XXX") {
gpas.push(parseInt(i)); // we need string to number with `parseInt`
}
}
Thanks everyone that contributed. By applying some of the suggestions given, I was able to make it work. I also noticed that the code below does the work too:
var gpas = [];
var gp;
var out = "";
while (i != "XXX")
{
var i = prompt("Enter a gpa or XXX to Stop");
if(i != "XXX"){
gpas.push(parseInt(i));
}
}
let sum = gpas.reduce((a, b) => {
return a + b;
});
sum;
var avg = (sum/gpas.length);
document.getElementById('output').innerHTML += "average =" + avg + "<br/>";
</script>````
The question as per the practice course is :
Write a JavaScript program to find the maximum integer n such that (1 + 2 + ... + n <= given integer ) is true. For eg. If a given integer is 10, value of maximum integer n is 4 so that 1+2+3+4 <= 10 is true. Your output code should be in the format console.log("Value of n is ", variableName)
My code is :
var num = prompt("Enter a number");
function test(x) {
var sum = 1,
n = 1,
a = 0;
while (sum <= x) {
sum += n;
n = n + 1;
a += 1;
}
return a;
}
var output = test(num);
console.log("Result is :", output);
I'm getting the correct outputs as per the test cases I've entered(10-4,15-5,16-6,17-6) but the website says there is something wrong with the program.
What am i doing wrong?
Better answer than looping: exploit maths. Starting with Triangular number formula:
1 + 2 + ... + n = n * (n + 1) / 2
Thus, for input x, you need to find n such that
n * (n + 1) / 2 <= x
To solve this, we need to clean up the inequality, then use the quadratic equation formula:
n^2 + n <= 2x
n^2 + n - 2x <= 0
n <= (-1 + sqrt(1 + 8x)) / 2
as the final solution. e.g. for
x = 10: n <= (-1 + sqrt(81)) / 2; n <= 4
x = 16: n <= (-1 + sqrt(128)) / 2; n <= 5.156854249492381
Round the upper limit down, and you have the largest allowed integer. Translated into JavaScript:
function test(x) {
return Math.floor((Math.sqrt(8 * x + 1) - 1) / 2);
}
var num = prompt("Enter a number");
console.log("Result is :", test(num));
Consider if the passed value is 11. Then, the maximum integer n should be 4, because 1+2+3+4 < 11 is true, while 1+2+3+4+5 < 11 is false. Your current code outputs 5 for an input of 11, though, which is incorrect; your while loop is sometimes overshooting sum.
You also need to initialize sum to start at 0, not at 1.
Subtract one from a before returning it:
function test(x) {
var sum = 0,
n = 1,
a = 0;
while (sum <= x) {
sum += n;
n = n + 1;
a += 1;
console.log(a, sum);
}
return a - 1;
}
console.log(test(10));
console.log(test(11));
var num = prompt("Enter a number");
var output = test(num);
console.log("Result is :", output);
The code below should work for you. Basically, what I did was that if the input is 10, and your sum is 9, it will still go into the while loop. Then it will add n again and now your number is greater than your input (which is 10), but you still return it. Here what I did is that at the end of the while loop, if your sum is greater than your input, subtract one from a. That way it will still execute, but it will fix the problem.
Also another error I noticed was that sum started at 1, and n started at 1. You wanted 1+2+3+...+n, however using your previous method, you got 1+1+2+3+...+n.
var num = prompt("Enter a number");
function test(x) {
var sum = 0,
n = 1,
tempSum = 1,
a = 0;
while (sum <= x) {
sum += n;
n++;
a++;
if (sum > x) {
a--;
}
}
return a;
}
var output = test(num);
console.log("Result is :", output);
Your order of operation is a little funky; all you have to do is add the incrementor. The while false case will make sure the sum only passes over the number once. So when you return, reduce the number by one:
var num = prompt("Enter a number");
var output = test(num);
console.log("Result is :", output);
function test(num){
let sum = 0
let inc = 0
while(sum<=num)
sum+=++inc
return --inc;
}
This is a reduced version of your code, basically we increment first the number to add (n) in each iteration, and then we add it to the variable holding the sum. When the loop conditions evaluates to false you need to decrement one to n to get your value:
var num = prompt("Enter a number");
function test(x)
{
var sum = 0, n = 0;
while (sum <= x)
{
sum += (++n);
}
return --n;
}
var output = test(num);
console.log("Result is :", output);
I think this will work for you:
var num = prompt("Enter a number");
function test(x) {
var sum = 1,
n = 0;
while ((sum+n) <= x) {
n = n + 1;
sum += n;
}
return n;
}
var output = test(num);
console.log("Result is :", output);
Try below function to find max Number
function maxNumber(a){
var i=1,sum=0,maxNumber=0;
while(sum<=a) {
sum=sum+i;
if(sum<=a)
{
maxNumber=i;
}
i+=1;
}
return maxNumber;
}
doubled checked condition sum<=a to preserve the previous loop value and if condition not satisfied that means current loop value is not useful so returned preserved value of previous loop
Output tested :
Below will help you get the job done.
var num = prompt("Enter a number");
function findMaxNumber(num){
var sum = 0;
var counter = 0;
while(sum < num){
if(sum + counter > num){
break; // Exit loop
}
sum = sum + counter;
counter++;
}
return --counter; // Loop will cause this to be 1 higher than the max int.
}
console.log('Result is: ' + findMaxNumber(num));
I am having an issue with getting the average of the numbers that are inputted through a prompt window. I need to display the numbers like i have so far, but I can't seem to get them to add together to get the average.
here is my code so far.
<html>
<body>
<script type="text/javascript">
function show_prompt() {
i = 0;
do {
var number = prompt("Please Enter a Number");
var number = parseInt(number);
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
}
show_prompt();
var avrg = number + number + number + number + number
document.write('Average of scores : ' + avrg);
</script>
</body>
</html>
You have to move calculation inside function. Also you can do it simplier:
function show_prompt() {
var i = 0;
var sum = 0;//declare a variable to keep the sum of numbers
do {
var number = prompt("Please Enter a Number");
sum += parseInt(number); //sum the numbers here
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
document.write('Average of scores : ' + sum / i);//use the sum of the numbers divide by the the numbers the user enters
}
show_prompt();
Tried to comment your old code with the mistakes:
function show_prompt() {
i = 0;
do {
//there is no need to declare number twice
//also you don't sum somewhere the numbers you get from the user
var number = prompt("Please Enter a Number");
var number = parseInt(number);
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
}
show_prompt();
//number is out of scope of function show_prompt so is undefined
var avrg = number + number + number + number + number
//to get an avg you have to divide the sum by the number
document.write('Average of scores : ' + avrg);
Notice your var number is scoped within show_prompt(), it is not visible outside of it.
You need to have your show_prompt function not loop, and return the number, and have another function that calls show_prompt multiple times, takes the returns and calculate the average.. Also, your code is just calculating the sum, not the average
I'm not going to show you the exact code, but here's the idea
calc_average:
var sum=0;
loop 5 times:
sum = sum + show_prompt();
average = sum/5;
show_prompt:
var number = prompt('blah blah');
return number