How to add spaces to for loop output in javascript?
You can add
to do it
for (var i = -52; i <= 1066; i++) { document.write(i+" ");}
Adding spaces in front the string in a for loop
You're on the right track. There are three steps that you need to do here. You need to create a cross like this (assuming number is 13):
*
*
*
*******
*
*
*
You need to create Math.floor(13/4)
(comes out to 3) rows of a single star, with each star after Math.floor(13/4)
spaces. Then you need a row of Math.ceil(13/2)
stars starting at position 0. Lastly, you need the same number of stars as you did before that row, so you can just do the same thing again.
Using your code, I would do something like this:
let num = prompt("Enter an odd number");
while (num%2 == 0) {
console.log("User did not enter an odd number");
num = prompt("Enter an odd number");
}
console.log("User's number is " +num);
let star = " ";
let pos = Math.floor(num/4);
let vertical = star.repeat(pos) + "*";
for (var i = 0; i < pos; i++) {
console.log(vertical);
}
console.log("*".repeat(Math.ceil(num/2)));
for (var i = 0; i < pos; i++) {
console.log(vertical);
}
Add spaces to string with loop
The thing you want is to print a number of spaces that is equivalent to the current line number - 1. So you'll have to create a for loop for that.
import java.util.*;
public class Pattern
{
public static void main(String[] args)
{
int input;
Scanner kb = new Scanner(System.in);
System.out.print("Enter a positive number: ");
input = kb.nextInt();
while (input <= 0)
{
System.out.print("That isn't positive, try again: ");
input= kb.nextInt();
}
for (int number = 0; number < input; number++)
{
System.out.print("#");
//print spaces equal to the number variable
for(int count = 0; count < number; count++)
{
System.out.print(" ");
}
System.out.println("#");
}
}
}
For loop print in single line separated by spaces - JS
Concatenate with a string in the loop instead, then console.log
that string:
let n = 10;let str = '';for (let i = 1; i <= n; i++) { str += i + ' ';}console.log(str.trim());
Related Topics
Extracting Key:Value Pairs Assoc With Regex from String on JavaScript
How to Allow Chrome to Access My Camera on Localhost
How to Replace a String With Square Brackets Using JavaScript Replace Function
How to Place Button on Right Side in Reactjs
Setting Iframe Height to Scrollheight in Reactjs
Form Builder - Cannot Read Property 'Get' of Undefined, Issue With Validators
Bootstrap Modal Hide Not Working With Jquery Ajax
How to Insert Space Every 4 Characters for Iban Registering
How to Set Maximum Length in Input Type=Number
Change the Arrow Buttons in Slick Slider
Create Parent and Child Relationship Using Lodash
How to Format Material Datepicker Date Value to "Mm-Dd-Yyy" Format in Angular 6
How to Move the Mouse Pointer and Click With Selenium Webdriver JavaScript
Callback Function Cannot Access Variable Within Parent Function'S Scope