Nested Loop to add numbers - javascript

I am currently trying to create a double nested loop that adds a number to itself, given the number of instances you want it to be added by.
So when you input something in the Number, for example "5" and you input "3" for the number of instances, then the following would be printed:
5=5
5+5=10
5+5+5=15
More information on my JsFiddle
<div>
<h2>Loop</h2>
Number
<input type='text' id='tbox'>
<br>
Number of Instances
<input type='text' id='theNumber'>
<button onclick=doubleLoop;>
Add Numbers.
</button>
</div>
<div id="content">
</div>
<script>
function doubleLoop(){
var theText = document.getElementById('tbox').value;
var theNumber = document.getElementById('theNumber').value;
var content = document.getElementById('content');
content.innerHTML = '';
for (var i = 0; i < theNumber; i++) {
content.innerHTML = content.innerHTML + (i + 1) + ')';
//start of the second part of the Double Loop
for (var j = 0; j < (i + 1); j++){
if (i === 0){
content.innerHTML = content.innerHTML + theText + '=' + theText + '<br>';
} else if (i > 0) {
content.innerHTML = content.innerHTML + theText.repeat(j) + '=' + (theText * (i+1));
}
}
}
}
</script>

Here you go
https://jsfiddle.net/mkarajohn/qkn2ef4L/
function createString(number, times) {
/*
* We will create each side of the equation separately and we will concatenate them at the end
*/
var leftSide = '',
rightSide = '',
i;
for (i = 1; i <= times; i++) {
leftSide += number.toString();
if ((times > 1) && (i < times)) {
leftSide += '+';
}
}
rightSide = number * times
return (leftSide + '=' + rightSide);
}
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
output += createString(theText, i);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
If there is something that is not clear feel free to ask.
EDIT: If you are hell bent on doing it with two nested loops, here's how it would go:
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
var leftSide = '',
rightSide = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
leftSide = '';
for (var j = 1; j <= i; j++) {
leftSide += theText.toString();
if ((i > 1) && (j < i)) {
leftSide += '+';
}
}
rightSide = theText * i;
output += (leftSide + '=' + rightSide);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);

First things first: You're naming your variables very poorly, it's really difficult to understand what you're trying to do, specially when you don't say what you want directly in the question. doubleLoop says how your function works but not what it does. getMultiplicationProcess would have been a better name. Also, you could be passing the values as arguments and just returning the result, it would look A LOT better.
Anyway, I couldn't figure how you were trying to achieve this. I've renamed your variables and did everything my way. Never name a variable theNumber or theText because doing so says nothing about what information it holds. You could have named them firstInput and secondInput but even that way it would not be clear.
Here's the code, scroll down for explanation:
var submit = document.getElementById("submit"),
firstInput = document.getElementById("tbox"),
secondInput = document.getElementById("theNumber"),
answerField = document.getElementById("content");
submit.addEventListener("click", function () {
answerField.innerHTML = getMultiplicationProcess(Number(firstInput.value), Number(secondInput.value), "<br/>");
});
function getMultiplicationProcess(multiplicand, multiplier, lineBreak) {
var result = "";
for (var i = 0; i < multiplier; ++i) {
for (var j = 0; j < i + 1; ++j) {
if (i === j) {
result += multiplicand + " = " + (multiplicand * (i + 1));
} else result += multiplicand + " + ";
}
result += lineBreak || "\n";
}
return result;
}
JSFiddle
Explanation:
The outer for loop runs as many times as the second input, or multiplier. So if you input 5 and 3 respectively this loop will run three times. It represents each line of the resulting string.
The inner loop runs as many times as the current iteration number of the outer loop more one. So for our example inputs it will run like this:
0: 1; 1: 2; 2: 3;
I use it to place the multiplicand multiple times in the current line.
The first line will contain a single 5 (not including the answer for this multiplication) so j is i + 1 which is 1 because during the first iteration from the outer loop i equals 0:
5 = 5
The second line contains 2 5s and i is 1 because we're in the second iteration for the outer loop, so j = i + 1 = 2 which is how many fives we'll place in the string:
5 + 5 = 10
if it's the last iteration of the inner loop instead of adding "5 + " to the resulting string it places "5 = (i + 1) * multiplier" which will be the result for the current line. Then the inner loop ends, the outer loop adds a line break and restarts the process for the next line.

Related

add x number of every 10th element

I want to add number of every 10th element.
For example,
function myFunction() {
for (var i = 1; i <= 100; i++)
{
var d = i;
document.getElementById("demo").innerHTML += d+"<br/>";
}
}
Output:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100
But, I want like this
1,2,3,4,5,6,7,8,9,10,16,17,18,19,20,21,22,23,24,25,31,32,33,34,35,36,37,38,39,40....
I want to add 5 after 10th number, add 10 after 20th number, add 15 after 30th number, add 20 after 40th number, add 25 after 50th number. I know this is simple. But, I couldn't get any result.
JsFiddle
You could take an offset and increment this value by five if the result of the index variable is dividable by ten.
var i,
offset = 0,
result = [];
for (i = 1; i <= 100; i++) {
result.push(i + offset);
if (i % 10 === 0) offset += 5;
}
console.log(result.join(' '));
You could use the modulo operator % to check if the current number (i) is a multiple of 10, then if it is, add 5 to i:
if (i % 10 === 0) {
i += 5;
}
Moreover, I recommend that you keep a string of all the numbers you want to append to your page, as querying and adding contents to the DOM each loop iteration is an expensive operation which can be avoided
See example below:
function myFunction() {
var resultStr = ""
for (var i = 1; i <= 100; i++) {
resultStr += i + "<br/>";
if (i % 10 === 0) {
i += 5;
}
}
document.getElementById("demo").innerHTML += resultStr;
}
myFunction();
<div id="demo"></div>
I used a counter to account for in increment on the 10th element, and am simply putting the results on the console. Obviously there are some that would simply just add 5, the counter option is just a design preference.
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];
function myFunction(arr){
var counter = 0;
for(var i = 0; i<arr.length; i++){
if (i%10 ==0){
counter++;
}
arr[i] = arr[i]+(5*(counter-1));
}
console.log(arr);
};
myFunction(arr);
Do something like:
function myFunction() {
for (var i = 1; i <= 100; i++)
{
var j=Math.floor(i/10);
var x=5*j;
var d = x+i;
document.getElementById("demo").innerHTML += d+"<br/>";
}
}
Expanding on the performance issue presented by Nick Parsons
var resultStr = ""
for (var i = 1; i <= 100; i++) {
resultStr += i + "<br/>";
if (i % 10 === 0) {
i += 5;
}
}
document.getElementById("demo").innerHTML += resultStr;
innerHTML is just horribly slow.
Consider the following code that employs a document fragment and the vanilla .append() method
const fragment = document.createDocumentFragment();
for (var i = 1; i <= 100; i++)
{
if( i % 10 === 0 )
i += 5;
fragment.append( document.createTextNode( i ) );
fragment.append( document.createElement('BR') );
}
document.getElementById('demo').append( fragment );
From my testing, it's about 2000(!) times faster to use a document fragment.
Change your fucntion like that:
function myFunction() {
for (var i = 1; i <= 100; i++) {
var d = i;
if (i > 1 && i % 10 === 1) {
d = (i % 10) * 5 + i;
}
document.getElementById("demo").innerHTML += d + ",";
}
}

Print Triangle using javascript function

function makeLine(length) {
var line = "";
for (var i = 1; i <= length; i++) {
for (var j = 1; j <= i; j++) {
line += "*";
}
}
return line + "\n";
}
console.log(makeLine(2));
I am trying to print triangle, i dont know where i am doing wrong, can some please explain the logic behind printing triangle using nested loops
*
**
***
After you finish printing a line, you need to add a newline "\n" so that you move to the next line. You could do this as below :
function makeLine(length) {
// length has the number of lines the triangle should have
var line = "";
for (var i = 1; i <= length; i++) {
// Enter the first for loop for the number of lines
for(var j=1; j<=i; j++){
// Enter the second loop to figure how many *'s to print based on the current line number in i. So the 1st line will have 1 *, the second line will have 2 *s and so on.
line += "*";
}
// Add a newline after finishing printing the line and move to the next line in the outer for loop
line+="\n";
}
// Print an additional newline "\n" if desired.
return line + "\n";
}
console.log(makeLine(2));
don't forget about .repeat()
function makeLine(length) {
var line = "";
for (var i = 1; i <= length; i++) {
line+="*".repeat(i)+"\n";
}
return line;
}
console.log(makeLine(3));
The \n was at an incorrect position.
function makeLine(length) {
var line = "";
for (var i = 1; i <= length; i++) {
for (var j = 1; j <= i; j++) {
line += "*";
}
line += "\n";
}
return line;
}
console.log(makeLine(5));
function hashTriangle(length)
{
let str="";
for(let i=0;i<length;i++)
{
str+="#";
console.log(str);
}
}
hashTriangle(7);
console.log() prints a new line. So it is not necessary for nested loops and confusing newline characters to be appended to our string.
function makeLine(length) {
var line = "";
for (var i = 1; i <= length; i++) {
for (var j = 1; j <= i; j++) {
line += "*";
}
// add new line after loop is completed
line = line + "\n"
}
return line + "\n";
}
console.log(makeLine(5));
you need to add \n to line when the inner loop is completed
const printTriangle=(symbol,gapSymbol,num) =>{
// const num =25;
let gap = 1;
const Sgap = symbol+' ';
for(i= num-1;i>=0;i--){
let prefixSuffix=''
prefixSuffix = gapSymbol.repeat(i);
let line = ''
if(i == num -1){
   line = gapSymbol.repeat(i)+symbol+gapSymbol.repeat(i);
}
if(i != num -1 && i !=0){
     line = gapSymbol.repeat(i)+symbol+gapSymbol.repeat(gap)+symbol+gapSymbol.repeat(i);
    gap = gap+2;
}
if(i<1){
    line = ''+Sgap.repeat(1)+Sgap.repeat(num-2)+Sgap.repeat(1);
}
console.log(line)
}
}
printTriangle('*','.',15)
This is a JavaScript function that generates a triangle shape using the console.log method. The function takes in three parameters:
symbol: the character to be used to draw the triangle
gapSymbol: the character to be used as a gap in between the symbols
num: the size of the triangle (the number of symbols on the base)
The function starts by initializing the variable gap with the value 1 and Sgap as a string of symbol followed by a space. It then uses a for loop to iterate num number of times, starting from num - 1 down to 0.
For each iteration of the loop, the function uses a single line variable to store the string to be logged. The prefixSuffix variable is used to store the repeated gapSymbols, which are used in each iteration of the loop.
The logic for each iteration is controlled by conditional statements, which determine the shape to be drawn based on the value of i. If i is equal to num - 1, the line is constructed using a single symbol surrounded by repeated gapSymbols. If i is not equal to num - 1 and i is not equal to 0, the line is constructed using repeated gapSymbols, a symbol, a gap of repeated gapSymbols, and another symbol, all surrounded by repeated gapSymbols. If i is less than 1, the line is constructed using repeated Sgaps.
Finally, the constructed line is logged using the console.log method.
Simple solution using padStart, padEnd, repeat method for printing right and left triangle
Left triangle
const printLeftTriangle = (n) => {
let output='';
for (let i = 1; i <= n; i++) {
output +="*".repeat(i).padStart(n) + "\n";
}
return output;
}
console.log(printLeftTriangle(5));
Right triangle
const printRightTriangle = (n) => {
let output='';
for (let i = 1; i <= n; i++) {
output +="*".repeat(i).padEnd(n) + "\n";
}
return output;
}
console.log(printRightTriangle(5));
try this solution please:
const halfTriangle = N => {
for (let row = 0; row < N; row++) {
let line = "";
for (let col = 0; col <= N; col++) {
if (col <= row) {
line += '#';
} else {
line += ' '
}
}
console.log(line);
}
}
halfTriangle(4)
// creates a line of * for a given length
function makeLine(length) {
let line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line + "\n";
}
// your code goes here. Make sure you call makeLine() in your own code.
function buildTriangle(length) {
// Let's build a huge string equivalent to the triangle
var triangle = "";
//Let's start from the topmost line
let lineNumber = 1;
for (lineNumber = 1; lineNumber <= length; lineNumber++) {
// We will not print one line at a time.
// Rather, we will make a huge string that will comprise the whole triangle
triangle = triangle + makeLine(lineNumber);
}
return triangle;
}
// test your code
console.log(buildTriangle(10));
Center Tringle
let line='';
for(let i=1; i<=5;i++){
line += ' '.repeat(5-i)
line += '*'.repeat(i+i-1)+'\n'
}
console.log(line);

Javascript for loop sums

I want to find the sums of a set of numbers from a for loop
I currently have
var num = "";
for(var i = 1; i < 11; i +=1){
num = num + i;
}
console.log(num)
which gives me 12345678910 in the JS console
I want to produce 1+2+3+4+5+6+7+8+9+10=SUM
I have tried adding a "+" string:
num = num + i + "+";
but it gives me 1+2+3+4+5+6+7+8+9+10+
My question is how to add the "+" and "=" into the code and get the sum.
If you want the + to display AND the actual sum, then do this
var realSum = 0;
var num = "1";
for(var i = 2; i < 11; i +=1){
realSum = realSum + i;
num = num + "+" + i;
}
num = num + "=" + realSum;
Try this : http://jsfiddle.net/kx9b7qu7/2
Using Eval
var num = [];
for(var i = 1; i < 11; i +=1){
num.push(i)
}
var equation = num.join('+');
var sum = eval(equation);
console.log('Method 1: ',equation + '=' + sum)
Without using Eval
var num = [];
var sum = 0;
for(var i = 1; i < 11; i +=1){
num.push(i)
sum += i
}
var equation = num.join('+');
console.log('Method 2: ',equation + '=' + sum)
Make an util out of it for later use ;) There are also other ways that make use of functional approach (reduce, map) and things that aren't widely supported yet (generators, array comprehensions).
Here are some example functions for consideration and tweaking:
// kind of usual
var sumRange = function (from, to, step) {
var i,
sum = from,
str = from;
for (i = from + step; i <= to; i += step) {
sum += i;
str += '+' + i;
};
str += '=' + sum;
return str;
};
// sum of elements in arithmetic progression
var sumRangeAP = function (from, to, step) {
var i,
n,
str = from;
n = ((to - from) / step) + 1;
for (i = from + step; i <= to; i += step) {
str += '+' + i;
};
str += '=' + ((from + to) / 2) * n;
return str;
};
// memory efficiency (not creating hell a lot of strings) together with some functional stuff
// on the other hand it looks like assignment operators (+, +=) win with .join in terms of speed sometimes
// in many cases, I think, you may not give a shit about whether you use this or that
var sumRangeME = function (from, to, step) {
var i,
sum = from,
str = [from];
for (i = from + step; i <= to; i += step) {
str.push(i);
};
return str.join('+') + '=' + str.reduce(function (prevVal, curVal) { return prevVal + curVal; });
};
console.log(sumRange(0,20,1));
console.log(sumRangeAP(0,20,1));
console.log(sumRangeME(0,20,1));
console.log(sumRange(1,21,1));
console.log(sumRangeAP(1,21,1));
console.log(sumRangeME(1,21,1));
console.log(sumRange(7,36,1));
console.log(sumRangeAP(7,36,1));
console.log(sumRangeME(7,36,1));
In javascript + can also concatenate a string, if that's what seems best - it thinks you are putting two strings together so it concatenates them. Make num start as 0 instead, that should fix it.
Instead of var num="" try with var num=0, because this way the operator + is used as string concatenation. num=0 will do the job.
EDIT: I thought you wanted to see the "math" equation try the following:
var numbers = 0;
for (var i = 1; i < 11; i += 1){
numbers += i;
}
console.log(numbers);
Try this:
var numbers = [];
for (var i = 1; i < 11; i += 1){
numbers.push(i);
}
var string = numbers.join("+");
string += "=" + eval(numbers.join("+"));
console.log(string);
If you're really trying to concatenate then
num = num + "+" + i;

Writing the result of a for-loop to the webpage using innerHTML in Javascript

I am learning Javascript and I am now getting bored of the console, so I would like to "write" to the webpage itself.
I am writing the result of a for loop to the page, I want to print the result, putting a comma after every index, I have managed to accomplish this but there is a comma at the end of the last result, how do I stop the comma after the 9th index? I assume I need to use an index of some sort (i[9]) but I'm not sure how to say stop writing commas.
Here is my code:
var x = document.getElementById("para1");
x.innerHTML = "Result: ";
for(var i = 1; i < 11; i++) {
result= i + "," + " ";
x.innerHTML += result;
}
One other thing, I am printing "result" in the x variable's innerHTML, is there another way to write variable except in the actual HTML of the page? for instance in the x.innerHTML at the end?
I would greatly appriciate any help!
Thanks
I would use an array and then after the loop has finished, join the array on , and then append to the innerHTML:
var x = document.getElementById("para1");
var result = [];
for(var i = 1; i < 11; i++) {
result.push(i);
}
x.innerHTML = "Result: " + result.join(", ");
In general, to do something different for the last one, you have to do it differently:
var x = document.getElementById("para1");
x.innerHTML = "Result: ";
for(var i = 1; i < 10; i++) { // one less here
result= i + "," + " "; // this could be result = i + ", ";
x.innerHTML += result ;
}
result = "10"; // this could be made shorter. I wanted it to parellel
x.innerHTML += result; // the code above.
UPDATE:
To make it more obvious....
original way:
var n = 10;
for(var i = 1; i <= n; i++) {
DoSomething(i);
}
revised way:
var n = 10;
for(var i = 1; i < n; i++) {
DoSometing(i);
}
DoSomethingSpecialLastCase(n)

Loop to print iterations separated with a comma, with no comma at the end

I'm a student and am writing a JavaScript "for" loop that prints into innerHTML. Every concatenation of the string is added to the last followed by a comma. how do I make it so the comma is not printed after the last iteration? Just for piece of mind, the commas aren't part of the assignment, I'm just trying to add practical application. no jQuery tho please
window.onload = function(){
var mySeven = 0;
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i;
printSeven.innerHTML += i + ',' + ' ';
}
}
};
Thanks!
You should use join() instead. It's much cleaner and you don't need to worry about edge cases:
var printSeven = document.getElementById('multiples_seven');
var sevens = [];
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
sevens.push(i);
}
}
printSeven.innerText = sevens.join(", ");
Or an approach that avoids the if() statement and unnecessary iterations:
var printSeven = document.getElementById('multiples_seven');
var sevens = [];
for (i = 7; i <= 1000; i += 7){
sevens.push(i);
}
printSeven.innerText = sevens.join(", ");
And for the sake of understanding, here's how you could do this without join():
var printSeven = document.getElementById('multiples_seven');
var maxValue = 1000;
var list = "";
for (i = 7; i <= maxValue; i += 7){
list += i;
if(i + 7 <= maxValue){
list += ", ";
}
}
printSeven.innerText = list;
Use this function:
function reorderData(){
var sevens = Array();
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
sevens.push(i);
}
}
var newDisplaySelectedArray = sevens.join(",");
jQuery( "#multiples_seven" ).val(newDisplaySelectedArray);
}
First off it is better to not manipulate the DOM inside a loop. You should construct your output in a string or array then add it to the DOM in a single operation :
window.onload = function () {
var mySeven = '';
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i + ', ';
}
}
printSeven.innerHTML += mySeven;
};
To delete the trailing comma you have two options : don't add it in the first place or remove it before adding it to the DOM.
Most other answers have concentrated on not adding it, here is a solution which removes it :
window.onload = function () {
var mySeven = '';
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i + ', ';
}
}
printSeven.innerHTML += mySeven.slice (0, -2);
};
A word of caution, if your for loop does not execute at least one iteration you may remove characters you want to display. In the generic case it is easier to build an array and use the join function as shown in other answers here.
It's easier to check if you are at the first item than if you are at the last, so simply add the commas before the number:
window.onload = function(){
var mySeven = 0;
var printSeven = '';
for (i = 1; i <= 1000; i++) {
if (i % 7 == 0){
mySeven += i;
printSeven += (printSeven.length > 0 ? ', ' : '') + i;
}
}
document.getElementById('multiples_seven') += printSeven;
};

Categories