Extra + in output when looping; javascript - javascript

My desired output is: 5 + 6 + 7 + 8 + 9 + 10 = 45
The output I'm getting is: 1 + 2 + 3 + 4 + 5 + = 15 (with an extra + side on the end). I'm not sure how to get it to output without the extra + at the end, and am clearly not searching for the right terms to figure it out. Thanks!
Here's my code:
function exercise7Part2() {
// PART 2: YOUR CODE STARTS AFTER THIS LINE
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart + " + ");
loopStart++;
}
document.write(" = " + total);
}

It's because you're printing loopState + "+" which will always print the + at the end. Instead you must check if it's the last value and prevent the + from printing or else, use a ternary operator to print it.
In this example, I'm checking if both loopStart and loopMax are not equal. if they're not equal then am appending + at the end.
It will be like:
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
Here (loopStart!=loopMax ? "+" : "") is a ternary operator. The loopStart!=loopMax is an boolean expression. It's evaluated and if it's true the first parameter after ? will be used so in this case + and if its false anythign after : will be used so in this case its "" empty string.
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
loopStart++;
}
document.write(" = " + total);
With normal if condition block
while (loopStart <= loopMax)
{
total += loopStart;
if(loopStart===loopMax) {
document.write(loopStart);
} else {
document.write(loopStart+ "+");
}
loopStart++;
}

// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
loopStart++;
}
document.write(" = " + total);

Related

Cannot get a JavaScript program to add odd numbers

Here's the problem:
Create a sum program that calculates the sum of all odd numbers between 1 and the number entered by the user. For example if the user enters in the number 7 the program would calculate 1 + 3 + 5 + 7. The total and the expression should be displayed on the document. The answer would be 16.
My code so far
//declare the variables
var sternum = prompt("enter a number");
var tantalum = 1;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(sternum % 2 == 0) {
}
else{
document.write(increase + expression);
increase = increase + 1;
tantalum = tantalum + increase;
}
}while(increase < sternum);
document.write(sternum + " = " + tantalum);
You have created an infinite loop. Make sure you increment increase every iteration:
var sternum = prompt("enter a number");
var tantalum = 0;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(increase % 2 == 0) {
}
else{
document.write(increase + expression);
tantalum = tantalum + increase;
}
increase = increase + 1;
}while(increase <= sternum);
document.write(" = " + tantalum);
To make it more efficient you could change increase = increase + 1; to increase = increase + 2;. No need to process even numbers. Also tantalum should be set to 0 to start.

I want to write javascript code to get a addition countdown

so basically this the prompt:
Addition countdown
you enter a number and the code should be adding a number while countingdown, for example if the user enter 10, then the result should be:
10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55.
This is what I have so far:
var num = Number(prompt("Enter a Number Greater than zero"));
while (num > 0){
first = num;
second = num-=1;
document.write(first + " +" + second + " +");
value = first + num;
document.write(value)
num--;
}
but I keep on getting something like this:
4 +3 +72 +1 +3 (let's say 4 is the number the user inputs)
I'm stuck can someone please help me????!!
You can keep total in one variable outside of while loop.
var num = Number(prompt("Enter a Number Greater than zero"));
var total = 0;
while (num > 0) {
total += num;
document.body.innerHTML += (num == 1 ? num + ' = ' + total : num + ' + ');
num--;
}
You could change the algorithm a bit, because for the first value, you need no plus sign for the output.
var num = Number(prompt("Enter a Number Greater than zero")),
value = 0;
document.body.appendChild(document.createTextNode(num));
value += num;
num--;
while (num > 0) {
document.body.appendChild(document.createTextNode(' + ' + num));
value += num;
num--;
}
document.body.appendChild(document.createTextNode(' = ' + value));

number to be printed in a format using javascript

I am using java script to print a 10 digit number. example 1234567891. But i want that number to be printed in a particular format link 123.456.789-1. Can somebody please help me to sort this.
Very simple way to do it:
var num = "1234567891";
var formattedNum = formatNum(num);
console.log(formattedNum); //returns 123.456.789-1
function formatNum(num) {
var arr = num.split('');
var output = '';
for (var i = 0; i < arr.length; i++) {
output += arr[i];
if (i === 2 || i === 5) output += '.';
if (i === 8) output += '-';
}
return output;
}
First, convert to a string with leading zeroes,
then insert the punctuation as you desire.
function formatnum(n) {
n = ("0000000000" + n).substr(-10); // take the last 10 digits of the padded string
return ( n.substr(0,3) + "." + n.substr(3,3) + "." + n.substr(6,3) + "-" + n.substr(9,1) );
}

Entering 3 Numbers in Prompt and Getting the Max in JavaScript

I'm new to this. I'm working on exercises for a class and as the subject states I'm trying to have the user enter 3 numbers in the prompt window that appears. This works fine, but I'm trying to get the highest number that was entered to appear after the prompt is over. As I've noted in the code, can anything be added to Math.max to make this work, it's very close to working, but isn't quite there. I appreciate any help.
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Number Input with Prompt
</title>
<script type = "text/javascript">
<!--
var total;
var inputNumber;
var value;
var highestNumber;
var finalMax = Math.max. //<-----Can anything be added here to get the maximum number entered in the prompt window that appears?
total = 0;
inputNumber = 1;
while ( inputNumber <= 3 ){
highestNumber = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
while(isNaN(value = parseInt( highestNumber ))){
highestNumber = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
}
total = total + value;
inputNumber = inputNumber + 1;
}
document.writeln(
"<h1>The highest number is " + finalMax + "</h1>" );
// -->
</script>
</head>
<body>
</body>
</html>
This approach compares the response to an up-to-date highest.
logic = "If value > highestNumber, highestNumber = value"
<script type = "text/javascript">
<!--
var total;
var inputNumber;
var value;
var highestNumber;
//var finalMax = Math.max. //<-----Can anything be added here to get the maximum number entered in the prompt window that appears?
total = 0;
inputNumber = 1;
while ( inputNumber <= 3 ){
value = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
while(isNaN(parseInt( value ))){
value = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
}
if (highestNumber == undefined || highestNumber < value) {
highestNumber = value;
}
total = total + value;
inputNumber = inputNumber + 1;
}
document.writeln(
"<h1>The highest number is " + highestNumber + "</h1>" );
// -->
</script>
A better way to do that would be like this
var nums = new Array();
for(var i=0; i<3; i++){
nums[i] = window.prompt( "Enter number " + (i+1) + " of 3:" , "" );
}
document.writeln("<h1>The highest number is " + Math.max.apply(null, nums) + "</h1>" );
This approach logs all answers and runs the compare at the end, thus making use of Math.max()
logic = "highestNumber = Math.max(first,second,third)"
<script type = "text/javascript">
<!--
var total;
var inputNumber;
var value;
var highestNumber = [];
//var finalMax = Math.max. //<-----Can anything be added here to get the maximum number entered in the prompt window that appears?
total = 0;
inputNumber = 1;
while ( inputNumber <= 3 ){
value = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
while(isNaN(parseInt( value ))){
value = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
}
highestNumber[inputNumber] = value;
total = total + value;
inputNumber = inputNumber + 1;
}
finalMax = Math.max(highestNumber[1], highestNumber[2], highestNumber[3]);
document.writeln(
"<h1>The highest number is " + finalMax + "</h1>" );
// -->
</script>
If you need or want to use Math.max to find your maximum, you should add each valid entry to an array of numbers and call Math.max.apply(null, numbers);
The following fiddle shows this in action: http://jsfiddle.net/T2Gxm/

Take a 4 digit input and change order

I am trying to prompt user for a 4 digit number. Then, replace each
digit by (the sum of that digit plus 7) modulus 10. Then swap the first digit with the third, and swap the second digit with the fourth. Then output the encrypted digits.
So, if i enter in 1234 it should encrypt it to 0189 or enter in 5948 and it encrypt it to 1526
The problem is i get 9810 and 6251. So, its reading it backwards. I am close but its in the wrong order.
<script type="text/javascript">
var temp;
var number;
var first;
var second;
var third;
var fourth;
var fifth;
//prompt for first number
do {
inputNumber = window.prompt("Enter only a 4 digit number");
if ((isNaN(inputNumber) || !(inputNumber.length == 4)))
window.alert("please enter a number or length of 4");
} while ((isNaN(inputNumber)) || !(inputNumber.length == 4));
//temp = inputNumber;
temp = parseInt(inputNumber);
first = temp % 10; //process each number one by one
temp = temp / 10;
second = temp % 10;
temp = temp / 10;
third = temp % 10;
temp = temp / 10;
fourth = temp % 10;
swap = first;
first = third;
third = swap;
swap = second;
second = fourth;
fourth = swap;
first = parseInt(first);
second = parseInt(second);
third = parseInt(third);
fifth = parseInt(fifth);
fourth = parseInt(fourth);
first = (first + 7) % 10
second = (second + 7) % 10
third = (third + 7) % 10
fourth = (fourth + 7) % 10
var incrypted = first * 1000 + second * 100 + third * 10 + fourth * 1;
//var incrypted = first * 1000 + second + third * 10 + fourth * 1;
document.writeln("<h1>The number " + inputNumber + " is encrypted as " + incrypted + ".</h1><br />");
</script>
You may be better off handling your numbers individually.
var digits = inputNumber.split("");
digits[0] = (+digits[0]+7)%10;
digits[1] = (+digits[1]+7)%10;
digits[2] = (+digits[2]+7)%10;
digits[3] = (+digits[3]+7)%10;
digits.push(digits.shift());
digits.push(digits.shift());
// rotating by two results in 1234 becoming 3412, same result just more efficient!
var result = digits.join("");
try
var num = "1234"
var digits = num.split("");
var out = [];
for(var i=0; i<digits.length; i++){
digits[i] = (parseInt(digits[i])+7)%10;
}
var end = [digits[2],digits[3],digits[0],digits[1]].join("");
console.log(end.join(""));
A shuffle function:
function shuffle(val){
val = val + "";
function transform(num) { return (+num + 7) % 10 + ""; }
return transform(val[2]) +
transform(val[3]) +
transform(val[0]) +
transform(val[1]);
}
and with some validation:
function shuffle(val){
val = val + "";
if(isNaN(val)) throw "a valid number is required";
if(val.length != 4) throw "a four-digit number is required";
function transform(num) { return (+num + 7) % 10 + ""; }
return transform(val[2]) +
transform(val[3]) +
transform(val[0]) +
transform(val[1]);
}
This comes down to a fundamental misunderstanding of how the % operator works.
The MDN reference states this about the % operator:
The modulo function is the integer remainder of dividing var1 by var2.
For example, 12 % 5 returns 2.
Taking your example, with the input 1234, you are first finding the modulo 10 of 1234 in this code:
first = temp % 10;
The modulo of 1234 is 4 because 1230 is divisible by 10, leaving 4 as the remainder. Thus your logic reversus things. You could just change things at the beginning of your code to be reversed a bit:
fourth = temp % 10; //process each number one by one
temp = temp / 10;.
third = temp % 10;.
temp = temp / 10;
second = temp % 10;
temp = temp / 10;
first = temp % 10;
There is still a problem, when fixed as above you code will output 189 as the answer because you are combing the numbers back together with addition arithmetic rather than string concatenation, as in 0 + 1 + 8 + 9 = 189. Change that last line to look like this and you are fixed:
var incrypted = first + '' + second + '' + third + '' + fourth;
This worked for me;
<script>
var vec = new Array("1","2","3","4");
for(var i = 0; i<4; ++i){
vec[i] = (+vec[i] + 7) % 10;
}
var tmp = vec[1];
vec[1] = vec[3];
vec[3] = tmp;
vec = vec.reverse();
tmp = Number(vec.splice(0,1));
vec.push(tmp);
console.log("vec:", vec);
</script>
logs vec: [0, 1, 8, 9]

Categories

Resources