Javascript Addition Program - javascript

This is a javascript program for adding two numbers but the problem is the code is too big and everytime I need to change the number to the integer by parseInt so if I need to add more numbers the code will become more lengthy. How can I make it more simple?
<!DOCTYPE html>
<html>
<head>
<title>adding</title>
</head>
<body>
<script type="text/javascript">
var x;
var y;
var z;
var n;
var result;
x=prompt("1st number");
y=prompt("2nd number");
z=parseInt(x);
n=parseInt(y);
result= n + z;
alert(result);
</script>
</body>
</html>`
`

create a js function:
function addNumbers(arr) {
var result = 0;
for (var i = 0; i < arr.length; i++){
result += parseInt(arr[i]);
}
return result;
}
function evaluate(){
var numberArray = document.selectElementById("numbers").value.split(",");
alert(addNumbers(numberArray));
}
and add a html input field:
<input id="numbers"/>
<button onclick="evaluate()"></button>
this will add all numbers you typed into the input field (comma seperated)
note:
this will only work with valid inputs, i.e.:
1,2,4,-8 would work
1 2,5,2 would not work
e,2,3 would not work

Related

Trying to add every single number within a range using a for loop to create a sum

I can't figure out the issue with my code. The output should add every number in a range (like 1 and 2 when entered will output 3). However, 1 and 3 outputs 12 for no discernible reason.
function Sum(){
var int1=document.getElementById("TextBox1").value;
var int2=document.getElementById("TextBox2").value;
for(i=int1; i<=int2; i++){
var total=int1;
total+=i;
if(i==int2){
alert("The sum of all numbers is "+total);
}
}
}
function Sum(){
var int1=document.getElementById("TextBox1").value;
var int2=document.getElementById("TextBox2").value;
for(i=int1; i<=int2; i++){
var total=int1;
total+=i;
if(i==int2){
alert("The sum of all numbers is "+total);
}
}
}
<html>
<head>
<title>
For Sum Exercise
</title>
</head>
<body>
<script>
</script>
User Number 1:<input id="TextBox1"><br><br>
User Number 2:<input id="TextBox2"><br><br>
<button onClick="Sum()">Sum</button><br>
</body>
</html>
You need to take a number from the input. value is from type string. With an unary plus +, you get a number.
You need to declare i as well.
Declare total in advance and take zero as value outside of the loop.
After the loop make the output.
function Sum() {
var int1 = +document.getElementById("TextBox1").value,
int2 = +document.getElementById("TextBox2").value,
total = 0,
i;
for (var i = int1; i <= int2; i++) {
total += i;
}
document.getElementById("sum").innerHTML = "The sum of all numbers is " + total;
}
User Number 1: <input id="TextBox1"><br><br> User Number 2: <input id="TextBox2"><br><br>
<button onClick="Sum()">Sum</button><br>
<p id="sum"></p>

Push method displayed incorrectly

I have an issue with this code. I want to push the odds number in a array called number. But when I display it with document.write it doesn't print out the way it supposed to. Please help!!
Here's what it displays: 11,31,3,51,3,5,71,3,5,7,9 instead of: 1,2,3,4,5,6,7,8,9
<!DOCTYPE html>
<html>
<head>
<title>Trial</title>
</head>
<body>
<script>
var number = [];
var i;
for (i = 0; i < 5; i++) {
var x = 2 * i + 1;
number.push(x);
document.write(number)
};
</script>
</body>
</html>
Put documet.write() after for loop. You are actually writing array of numbers at each stage.
var number= [];
var i;
for (i=0; i<5; i++)
{var x =2*i+1;
number.push(x);
};
document.write(number)

How can I make a modulus operator add odd numbers between two numbers in JavaScript?

Below is what I have so far. And do I place the user prompt within the function or leave it where it is? What I am "trying" to accomplish is to add
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<script type="text/javascript">
/* Input: user types in an integer
* Processing: adds all odd numbers between input and 0
* Output: the sum of the odd numbers
*/
function addOdds() {
var n = parseInt(document.getElementById('number').value);
var sum = i=i+2;
for **(var i = -1; i < 6; i = i + 2)** {
if (n == 0) {
break;
}
sum += n;
}
window.alert(sum);
}
</script>
</head>
<body>
Please enter a number. <input type="text" id="number">
<button type="button" onclick="addOdds()"> Get the sum </button>
<div id=""> </div> <!--is this part need? -->
</body>
</html>
var sum = 0;
for (var i = 1; i<=n; i+=2) {
sum+=i;
}
In your function you have:
function addOdds() {
var n = parseInt(document.getElementById('number').value);
var sum = i=i+2;
i is declared below so its value is undefined. Adding 2 returns NaN. Just initialise sum to 0:
var sum = 0;
for (var i = -1; i < 6; i = i + 2) {
I think you need to start from 0, though it's even so start from 1. And you want to go up to value, so:
for (var i=1; i<=n; i++) {
Now just add i if it's not even:
sum += i%2? i : 0;
}
and you're done.
document.getElementById('sum').textContent = sum
}
Assuming that you also have:
<div id="sum"></div>
But I like Wee You's answer. ;-)
Try this code, it will help you..
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<script type="text/javascript">
/* Input: user types in an integer
* Processing: adds all odd numbers between input and 0
* Output: the sum of the odd numbers
*/
function addOdds() {
var n = parseInt(document.getElementById('number').value);
var sum = 0;
for (var i = 0; i < n; i++) {
if (i % 2 != 0) {
sum += i;
}
;
}
window.alert(sum);
}
</script>
</head>
<body>
Please enter a number. <input type="text" id="number">
<button type="button" onclick="addOdds()"> Get the sum </button>
<div id=""> </div> <!--is this part need? -->
</body>
</html>

How to add up all numbers up to, and including, the input number?

I'm a total JS noobie, and I'm trying to make it so that after one input is entered all of the numbers between 0 and that input are added up, including the input. Here is the basic pseudo code I'm trying to accomplish but i can't figure it out?
get count from user
loop up to count{
add current number to sum
}
display sum
display breakline
loop up to count with a different loop type{
add current number to sum
}
display sum
You could try something like this:
// input would be the number that the user will enter
var input = 10;
// the starting number is 0.
var temp = 0;
// the sum.
var sum = 0;
// while the temp would be less or equal to the input,
// then we will add the temp to the sum and we increase it by 1.
// This way, when temp would be equal to imput+1, the statement in
// the while loop would be false, and the statements in the while loop
// wouldn't be executed. At this moment, the sum would hold the sum of
// the integers numbers in the range [0,input].
while(temp<=input)
{
sum+=temp;
temp++;
}
As for the part of displaying is totally depends on where you want to display the result.
If you want to display it on the console.
console.log(sum);
If you want to display it on an alert box.
alert(sum);
etc.
The fastest way to do this is by adding a sequence (looping not required):
let sum = input * (input + 1) / 2
See this link for more information.
var sum = 0;
var input = getCountFromUser(); //However you do it.
for (var j = 1; j <= input; j++) {
sum += j;
}
Or, somewhat shorter:
var sum = 0, input = getCountFromUser(), j = 1;
for (; j <= input;) {
sum += j++;
}
Here it is the full code displaying you want:
<HTML>
<HEAD>
<TITLE>JavaScript Form - Input Text Field</TITLE>
<SCRIPT Language="JavaScript">
<!--//
function showAndClearField(frm){
if (frm.num.value == "")
alert("Hey! You didn't enter anything!")
else{
var result = 0;
var input = frm.num.value; //However you do it.
for (var i = 1; i <= input; i++) {
result += i;
}
alert("Result: " + result)
}
frm.firstName.value = ""
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="test">
<H2>Enter a number.</H2>
<INPUT TYPE="Number" NAME="num"><BR><BR>
<INPUT TYPE="Button" Value="Show and Clear Input" onClick="showAndClearField(this.form)">
</P>
</FORM>
</BODY>
</HTML>

for loop for 0 to n number with digits specification

How can I write a for loop for 16 digit number from 0 to n
I want the output to be like:
0000000000000000
0000000000000001
0000000000000002
0000000000000003
0000000000000004
0000000000000005
Tried this but this isn't working:
for(i = 0000000000000000; i < 0000000000000010; i++){
$("#TestDiv").append(i);
}
check out the JSfiddle
Have a look at using the slice method. For example:
var addLeadingZeros = function(number){
var str = "0000000000" + number; // add leading zeros for single digit number
return str.slice(-10); // slice the whole number down from the end
}
for(var i = 0; i < 100; i++){
$("#TestDiv").append(addLeadingZeros(i));
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function writeNumber(n){
var nLen = n.toString().length;
var zeroLen = 16-nLen;
var arr = [];
var str = "0";
for(var z=0;z<zeroLen;z++){
arr.push(str);
}
arr.push(n.toString());
return arr.join('');
}
window.onload = function () {
var arr = [];
for(i=0;i<11;i++){
var str = writeNumber(i);
arr.push(str);
}
document.getElementById("testDiv").innerHTML = arr.join('<br>');
};
</script>
<div id="testDiv"></div>
</body>
</html>
More efficient with an array. Maybe it doesn't matter so much when the loop is just 10 items, but you're going to write to the DOM 10 times if you access the DOM inside the loop instead of outside the loop just 1 time. All the
small things adds up, so it may matter.
9. Stop touching the DOM, damnit!
That won't work because for number 00000001 is equal to 1 . You've to use strings.
Use like bellow
var str = '';
var zeros = '0000000000000000'; //string of 16 0's
for(i=0;i<11;i++){
var temp = zeros.slice(i.toString().length); // get the 0's 16-length of i
str += temp+i+'<br>';
}
$("#TestDiv").append(str);
DEMO

Categories

Resources