Display numbers from one to twenty in sets of five per row

Currently learning JavaScript and facing a challenge with printing integers from 1 to 20 using a while loop. The requirement is to display only five integers per line. Any assistance would be highly appreciated!

I experimented with different methods, here's my most recent attempt:

var numbers = " ";
var count = 1;
while (count <= 20) {
    if (count % 5 == 0) {
        numbers += count + "\n";
    } else {
        numbers += count + " ";
    }
    count++;
}
alert(numbers);

Answer №1

When working with basic JavaScript concepts like this, it is recommended to use a console instead of directly coding for a web page. By utilizing console.log() to write programs first and then moving on to manipulate DOM elements, you can bypass the cumbersome methods of using alert() or document.write(). I personally found guidance from the book Eloquent JavaScript by following similar practices.

Here are three different loop examples that achieve what you have described. The loops vary in their approach but all serve the purpose similarly:

console.log('\nloop one')
;(function() {
  var x = '',
      i = 1
  while (i <= 20) {
    x += i
    x += i%5 ? ' ' : '\n'
    i++
  }
  console.log(x)
})()

console.log('\nloop two')
;(function() {
  var line = ''
  for (var i = 1; i <= 20; i++) {
    line += i + ' '
    if (i % 5 === 0) {
      console.log(line)
      line = ''
    }
  }
})()


console.log('\nloop three')
;(function() {
  for (var i = 1, line = ''; i <= 20; line = '') {
    for (var j = 0; j < 5; j++)
      line += i++ + ' '
    console.log(line)
  }
})()

node example, with the above code saved in a file named 'example', will produce the following output:

loop one
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20


loop two
1 2 3 4 5 
6 7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 

loop three
1 2 3 4 5 
6 7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 

Answer №2

To enhance your code, consider making some syntax and logic adjustments as demonstrated below:

let i = 1;
while (i <= 20) {
 let x = i % 5; // checking for 5 numbers in a line
 
 if (x === 0) 
  document.write(i + ", <br>"); // adding a line break after 5 numbers
 else
   document.write(i + ", "); 
 i++;  
};

Answer №3

Consider using an array to store values of i along with the method Array.prototype.splice()

var nums = []
, i = 1
, length = 5
, maximum = 20;

while (i <= maximum) {
  nums.push(i++); --length;
  if (length === 0 && nums[nums.length - 1] !== maximum) {
    nums.splice(nums.length, 0, "\n");
    length = 5
  }
}
console.log(nums);
alert(nums.join(" "));

Answer №4

Here's the version I came up with:

http://jsbin.com/lituvanipe/1/edit?js,console

Remember to enable F12! (Make sure the console is open and click "Run")

_padEmpty function is included for formatting purposes, but feel free to remove it and directly call it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for the malfunction of this angular binding?

Looking at the HTML below: <input type="checkbox" name="person" [(ngModel)]="person.selected" /> This input is part of a ngFor loop. Testing has revealed that despite some values of selected being true and others false, all checkboxes appear check ...

Struggling to get the hang of CSS animation?

Here is a code snippet that I am using: //Code for animating skills on view document.addEventListener("DOMContentLoaded", function(event) { function callback(observations, observer) { observations.forEach(observation => { if (observati ...

In Typescript with Vue.JS, the type 'Users[]' does not include the essential properties of type 'ArrayConstructor' such as isArray, prototype, from, of, and [Symbol.species]

Embarking on my journey with typescript and vuejs, I stumbled upon a perplexing error that has halted my progress for the past 48 hours. The error message reads as: Type 'Users[]' is missing the following properties from type 'ArrayConstruct ...

Attempting to create a redirection landing page

I have a process where I create a new user and save it in my database with the following code snippet: const newUser = new User({ username: userId, password: pass, nameOfUser: user_name, emailOfUser: user_email ); newUser.save(); res.redir ...

Displaying lines of an XML file without the accompanying tags

Currently, I am parsing an XML file line by line: var lines = $(xml).text().split("\n"); $.each(lines, function(n, elem) { console.log(elem); }); However, the code above only displays the content within the tags, not the actual XML lines. I have ...

"The 'BillInvoice' object must be assigned a primary key value before it is ready for this relationship" - Error Message

There is an issue in my Django project related to the creation of a BillInvoice and its associated BillLineItem instances. The error message I'm receiving states: "'BillInvoice' instance needs to have a primary key value before this re ...

Use JavaScript to overlay drawings onto an existing image

Within this particular image, I possess a compilation of pixel coordinates outlining the polygon segments that encompass all the objects contained within it (refer to the image provided below). For example, in relation to the individual, there exists a li ...

Experimenting with jQuery's .hide() and .show() functions with an alert message confirming that the div is not

Below is some simple code to demonstrate an issue: $('.myDiv').click(function() { $('.anotherDiv').hide(); alert('pause the ui'); $('.anotherDiv').show(); }); After clicking on the .myDiv element, the ...

What is the best way to delete an added element once a DIV has been toggled with JQuery?

I'm facing an issue where I need to add an element to a DIV that has a toggle function. However, every time I click the toggle again after adding the element, the same element is appended once more, resulting in duplicate elements. Upon observation, ...

Tips for inserting a button under a div when clicked

I am working on a layout where I have several div cards aligned side by side using the display: inline-block property. What I want to achieve is that when I click on a card, a button is added below the respective div. To accomplish this, I tried using jqu ...

What is the best way to display a Base64 image in a server-side DataTable?

This HTML code is designed to load server-side data into a table. The data is retrieved from the controller using AJAX requests. <script type="text/template" id="tablescript"> <td><%=Name%></td> <td><%=PhoneNumber%> ...

"Addressing the issue of an unrefreshed info-window in AngularJS and Google Maps

I've been facing some challenges with info-windows that display when clicking on custom markers. I managed to get them to show up, but the outcome is not quite right. What happens is, when I click on the first marker, the info box displays its content ...

Inserting a Div Element into a List Using a User-Entered Variable (jQuery)

For a school project, I am currently working on a task involving multiple "Add Task" buttons with prompts that appear when clicked. The goal is to have the entered item added to the bottom of the corresponding list. I have experimented with options like a ...

Ways to verify the presence of an element in a list

I found this interesting JS code snippet: ;(function ($) { $('.filter-opts .opt').click(function(){ var selectedName = $(this).html(); $('.append').append('<li>' + selectedName + '</li> ...

Having difficulty retaining the value of a variable following the retrieval of JSON data

For my current project, I am utilizing the highstocks charting library in combination with JQuery. My goal is to create a single chart divided into three sections, each displaying different data sets. To import the data, I have referenced the sample code p ...

Crafting dynamic parameters in the Express router - A step-by-step guide!

Original Code Example: const express = require('express'); const router = express.Router(); router.get('/data/:d1/:d2/:d3', require('../apifoo').foo); Route: /data/:d1/:d2/:d3 Path: /data/1/2/3 req.params : 'd1' : ...

Combining NPM Script Commands: A Comprehensive Guide

I am aware that NPM scripts can be chained using &&, pre-, and post- hooks. However, I am wondering if there is a way to simply break down lengthy script lines into a single, concatenated line? For instance, can I convert the following: "script": ...

NextJS: Issue: Accessing a client module from a server component is not allowed. The imported name must be passed through instead

My current NextJS setup is structured as shown below: app/page.js 'use client'; import React from 'react'; export default function Home() { return (<div>Testing</div>); } app/layout.js export const metadata = { title ...

Genvalidator: Validate forms by checking for checkbox selection

Currently, I am utilizing genvalidator to conduct tests on input fields within a form. One issue I am encountering is the inability to determine if a checkbox has been checked. Below are the settings for all fields: frmvalidator.addValidation("name","req ...

Discover the ins and outs of integrating YAML front matter into your destination directory path

I am looking to customize the path of my blog posts to include a fancy date format like /blog/2013/09/17 so that the links from my previous octopress blog remain intact. Within the YAML front matter on each markdown page, I have included the date informat ...