Im trying to accept 2 inputs from a user then compare the 2 to find the smallest number.
Finally print to the console. I feel Im going in the wrong direction.
Any advice?
Below is my code
//prompt variable for user input
let num1 = prompt("Enter 1st number ", "i.e. 7 ");
let num2 = prompt("Enter 2nd number ", "i.e. 4 ");
// for loop returning lowest input
for (let i = 1; i < num1.length; i++){
if (num1[i] <= num2){
num2 = num1[i];
}
}
console.log(num2);
If there's only 2 inputs and you're trying to console.log the smallest number then you can just use an if statement. No need to iterate through num1.
let num1 = 5;
let num2 = 10;
if(num1 > num2){
console.log(num2);
}else if (num2 > num1){
console.log(num1);
}else{
console.log(num1 + ' and '+num2+' are equal');
}
Related
Hello there I have been challenged to write a program in JavaScript despite not really knowing much about it that asks the user for a number and then calculates the factorial of that number. I used already asked questions and managed to get the calculation to work but couldn't get the required output. I have to get it in the following output without using any fancy libraries or extra variables/arrays (which I can't think of how to do) :
(assuming user input is 5):
The factorial of 5 is 5*4*3*2*1=120
OR
5! is 5*4*3*2*1=120
Here is the code I've got so far:
//prompts the user for a positive number
var number = parseInt(prompt("Please enter a positive number"));
console.log(number);
//checks the number to see if it is a string
if (isNaN(number)) {
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (number < 0) {
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorial = 1;
for (count = 1; count <= number; count++) {
factorial *= count;
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The factorial of " + number + " is " + factorial + ".");
}
I know there are many similar questions to this as I looked around and used them to help me get this far but it is getting the output into the required format that I'm struggling with. I am told it is possible with a loop but don't know where to begin implementing that and I'm only allowed to use that solution.
Unfortunately this is part of a larger program in the challenge and I can only use the following variables:
Number (variable initialised as 0 to hold user input)
Factorial (variable initialised to 1 to hold value of calculated factorial)
Count (variable to hold number of times loop is executed for performing factorial calculation)
Probably you just need to build a string in that loop (on top of calculating the actual value):
let input=parseInt(prompt("Number?"));
let output="";
let result=1;
for(let i=input;i>1;i--){
result*=i;
output+=i+"*";
}
console.log(input+"! is "+output+"1="+result);
The "no-array clause" in your task presumably means that you are not supposed to build an array and use join() on it, like
let arr=[1,2,3,4,5];
console.log(arr.join("*"));
I have updated your code mainly here, Also make sure you are using the same variable num in your code and not number:
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}
//prompts the user for a positive number
var num = parseInt(prompt("Please enter a positive number"));
console.log(num);
//checks the number to see if it is a string
if (isNaN(num))
{
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (num < 0)
{
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The " + num + "! is " + factorials.join('*') + " is " + result + ".");
}
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 have to make a game of dice where I add the values of both the dice and give the sum. You get another turn if both the dice end up on the same number (such as 2 and 2 which is 4) then you roll the dice again and the 2 new numbers get added to the previous sum (like 4 mentioned earlier).
For example -
1st try 3 and 3, sum is 6.
2nd try 4 and 5, sum is 6 + 4 + 5 = 15
I'm able to get the first sum right, but the subsequent numbers are getting messed up sometimes even giving twice as much.
function oneRandom(){
var my1 = Math.floor(Math.random() * 6 ) +1 ;
var my2 = Math.floor(Math.random() * 6 ) +1 ;
var num1 = Number(my1);
var num2 = Number(my2);
var sum = num1 + num2;
console.log(sum);
var resultfield = document.getElementById("total").innerHTML = "<h1>"+sum+"</h1>";
document.getElementById("cilc").style.display = "none";
if (getImage.src == get2.src){
document.getElementById("cilc").style.display = "block";
var sum2 = num1 + num2;
var total = sum2 + sum;
var resultfield = document.getElementById("total").innerHTML = "<h1>"+total+"</h1>";
}
}
The getImage and get2 are arrays to match dice images to give another turn in case of same numbers loading.
You can try this,
function rollDice (times) {
var num1 = Math.floor(Math.random() * Math.floor(6));
var num2 = Math.floor(Math.random() * Math.floor(6));
console.log(times, num1, num2);
var total = num1 + num2;
return num1 === num2 ? total + rollDice(times + 1) : total;
}
console.log(`result is ${rollDice(0)}`);
When I run the code it doesn't multiply my number it just outputs in a loop until it reaches 1
I have tried multiple different ways and this one is the closest i've gotten
......................................
var BR="<br />"; //html line break
function factorial(Num) {
document.write("The factorial of your number is" +Num +BR);
if (Num == 1 ) return 1;
else return (Num * factorial(Num-1));
}
.....................................................
.......................................
var Num; //users number
var Numfactorial;
var ES="";
var factorial
Num=prompt("Enter a number between 1-20" +ES);
Numfactorial=factorial(Num);
.........................................
It's supposed to take the number and multiply it down, so say you put in 20 it should go 19*18*17... down until it multiplies 1 and then outputs the product.
Place the document.write outside your function, and just print the result (Numfactorial) to the page. You also need to parse Num to a number, and remove var factorial:
var BR = "<br />";
function factorial(Num) {
if (Num == 1) return 1;
else return Num * factorial(Num - 1);
}
var Num;
var Numfactorial;
var ES = "";
Num = parseInt(prompt("Enter a number between 1-20" + ES));
Numfactorial = factorial(Num);
document.write("The factorial of your number is " + Numfactorial + BR);
Well, that is the expected output of your code. Your function factorial is returning your value which you aren't using to display the value. You should instead write it like this:
....................................................
var BR="<br />"; //html line break
function factorial(Num) {
if (Num == 1 ) return 1;
else return (Num * factorial(Num-1));
}
.....................................................
.......................................
var Num; //users number
var Numfactorial;
var ES="";
var factorial
Num=prompt("Enter a number between 1-20" +ES);
Numfactorial=factorial(Num);
document.write("The factorial of your number is" +Numfactorial +BR);
.........................................
This question already has answers here:
Javascript prompt and alert inputting a number and it will loop and you will input numbers to get the average of it
(3 answers)
Closed 4 years ago.
How can I store all of my numberGrades values so they can included in my calculation, I"m new to this so if someone could update my code that would be perfect?
//user input number of grades to be entered
numGrades = prompt("Enter number of grades to be entered: ", ES);
//number of grades to be entered LOOP
for (index = 1; index <= numGrades; index++) {
numberGrades = prompt("Enter Grade " + index, ES);
}
//Calculation
gradePointAverage = numberGrades / numGrades;
document.write("Your GPA is " + gradePointAverage + PA);
prompt method returns a string, so you have to cast it to int or float using parseInt or parseFloat.
What you were doing is only getting the last value of your grades. What you want is to sum them all together THEN divide them by the number of grades
There are 2 solutions :
Store the inputs into an array
Sum them all together each time a user input a value
// First solution
// Create an array and append each value
numberGrades = [];
for (index = 1; index <= numGrades; index++) {
valuePrompt = prompt("Enter Grade " + index, ES);
numberGrades.append(parseFloat(valuePrompt));
}
//Calculation
sumOfGrades = numberGrades.reduce((a, b) => a + b, 0)
gradePointAverage = sumOfGrades / numGrades;
// Second solution
// Add every prompt by the user
numberGrades = 0;
for (index = 1; index <= numGrades; index++) {
valuePrompt = prompt("Enter Grade " + index, ES);
numberGrades += parseFloat(valuePrompt));
}
//Calculation
gradePointAverage = numberGrades / numGrades;