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);
Related
I've been trying to figure this out for a while but have run out of possible solutions. This is for a school assignment that is meant to create a "triangle" based on the number inputted (so if I put 3, the first line will have 1 asterisk, the second will have 2, and the third 3). The code is running fine but I'm getting an extra empty line because of the "\n" and am unsure how to remove it. My code:
function drawTriangle(size) {
let string = ""; //declares a variable string
for (let i = 1; i <= size; i++) { //loop continues upto size
for (let j = 0; j < i; j++) { //loop starts from 0 and ends at i
string += "*"; //* is added to string
}
string += "\n"; //when 1 row is finished, next line is printed on new line
}
console.log(string); //outputs the string to the console
}
As per Bergi's comment, create a local array variable and add line break at the end by using .join("/n").
Live Demo :
function drawTriangle(size) {
let str = ''; //declares a variable string
const arr = [];
for (let i = 1; i <= size; i++) { //loop continues upto size
for (let j = 0; j < i; j++) { //loop starts from 0 and ends at i
str += "*"; //* is added to string
}
arr.push(str);
str = '';
}
return arr
};
const result = drawTriangle(3).join("\n");
console.log(result);
I need a function that works like split
var string = "a|b|c"
console.log(string.split('|'))
to get a string and split it using loop
function splitstr(str, charToSplit){
}
I want the output of ('a|b|c', '|') to be ["a", "b", "c"]
Here is a slightly simpler solution that works correctly:
function splitStr(str, separator) {
const parts = [];
let nextPart = '';
for (let i = 0; i <= str.length; i++) {
if (str[i] === separator || i === str.length) {
parts[parts.length] = nextPart;
nextPart = '';
} else {
nextPart += str[i]
}
}
return parts;
}
console.log(splitStr("abc|abcd|ac", "|"));
You can use the code below.
This code had 8 steps to it.
Loops through the string
Checks if the current item is equal to charToSplit
If it is, it loops through the values in between startIndex and your current index (excluding your current index, which is the character you want to split on)
It first sets the value of output[currentIndex] to an empty string (since using += on something that doesn't exist doesn't work correctly
Then it adds the current letter you are on to output
startIndex is set to your current index + 1 (which is the character after the character that you want to split on)
currentIndex is increased by 1 since you're now on the next set of values
Finally, the code returns output
Note: The final extra loop after the first loop is there to add the last value to your output array.
function splitstr(str, charToSplit) {
var output = [];
var currentIndex = 0;
var startIndex = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] == charToSplit) {
output[currentIndex] = "";
for (var x = startIndex; x < i; x++) {
output[currentIndex] += str[x];
}
startIndex = i + 1;
currentIndex++;
}
}
output[currentIndex] = "";
for (var i = startIndex; i < str.length; i++) {
output[currentIndex] += str[i];
}
return output;
}
console.log(splitstr("abc|abcd|ac", "|"));
i'm trying to make a right aligned triangle. I am able to make a left aligned triangle easily, but can't get the number of spaces to decrease with each additional row.
output should be:
#
##
###
####
#####
let levels = 8;
let hash = '';
for (let i = 1; i <= levels; i++) {
hash += '#';
console.log(hash)
}
Instead of reusing the same string, consider generating each row with repeat() and padStart():
function rightAlignedTriangle (levels) {
for (let i = 1; i <= levels; i++) {
const row = '#'.repeat(i).padStart(levels)
console.log(row)
}
}
rightAlignedTriangle(5)
To implement this using a nested loop instead of string methods, you can manually implement the above two methods as an inner loop on a variable string declared in the outer loop:
function rightAlignedTriangle (levels) {
for (let i = 1; i <= levels; i++) {
let row = ''
for (let j = 0; j < levels; j++) {
if (j < i) { row += '#' } // repeat(i)
else { row = ' ' + row } // padStart(levels)
}
console.log(row)
}
}
rightAlignedTriangle(5)
I am teaching myself programming and I am doing a Udacity course on Javascript. They have a quiz to create a for loop in a function to create a triangle and call that function in another function. I wrote a for loop (pasted below) that worked in Java but is not working in Javascript. Can you point out my mistake please? The code is only printing 1 "*".
Code I wrote:
function makeLine(length){
var line = "";
for(var i = 1; i <= length; i++){
for(var j = 1; j <= i; j++){
line += "* ";
}
return line + "\n";
}
}
function buildTriangle(input){
makeLine();
}
console.log(buildTriangle(10));
function makeLine(length) {
var line = '';
// outer loop is number of lines
for (var i = 1; i <= length; i++) {
// inner loop is number of stars for this line
for (var j = 1; j <= i; j++) {
line += '* ';
}
// after requisite number of stars, add a new line char to end this line, before returning to the outer loop
line += '\n';
}
// return your finished string to the calling function
return line;
}
function buildTriangle(input) {
// need to send "input" to the makeline function
// since you are not printing here.. you need to return the result of this function
// to the calling function, so console.log has something to print.
return makeLine(input);
}
console.log(buildTriangle(10));
Also, I might use descriptive variable names instead of i, j just to make it easier to read, and to add clarity.
For example:
for (line_num = 1; line_num <= length; line_num++)
and
for (star_num = 1; star_num <= line_num; star_num++)
makeLine dont use return in loop, in buildTriangle call the function makeLine with arg input and return it
function makeLine(length){
var line = "";
for(var i = 1; i <= length; i++){
for(var j = 1; j <= i; j++){
line += "* ";
}
line += "\n";
}
return line;
}
function buildTriangle(input){
return makeLine(input);
}
console.log(buildTriangle(10));
Based on the name makeLine I am rather convinced that you are supposed to make only a single line there, then make a triangle by repeatedly calling from buildTriangle:
function makeLine(length){
var line='';
for(var i=0;i<length;i++)
line+="*";
line+="\n";
return line;
}
function buildTriangle(input){
var tri="";
for(var j=0;j<input;j++)
tri+=makeLine(j+1);
return tri;
}
console.log(buildTriangle(5));
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.