Tips for obtaining the correct Javascript output for the number pyramid

I'm currently in the process of creating a half pyramid of numbers, but I'm facing an issue with getting the output to show the total for each line while maintaining everything except the * sign between the numbers. If anyone is able to offer some assistance, it would be greatly appreciated. Here's the code that I've developed:

<!DOCTYPE html>
<html lang="en>
<head>
    <meta charset="UTF-8">  
    <title>Assignment 1</title>
    <script>
        var num = "";
        var match ="";


var size = prompt("Enter the size of the pyramid");
if (size >=1) {
var total="1";

for(var i=1; i<=size; i++)
{
    if (i < size){
  num = num  +  i + " " 

  } if (i==size) {
  num =num + i }


   total= total * i;
  document.write(num   + " = "+ total + "<br>"); 
}
 }else {
 alert("Please enter a number equal to or greater than 1");
 }
var total="1";
    </script>
</head>
<body>
    <main>
        <!-- Will show after the script has run -->
        <h1>Assignment 1</h1>
    </main>
</body>
</html>

-

I am looking for output like this

1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120

and so on. Thanks again

Answer №1

If you want to calculate the product of numbers using a loop, you can implement it with a slight modification in the iteration:

var result = 1;
var numberList = [];
for(let j=1; j<=6; j++) {
  numberList.push(j);
  result *= j;
  console.log(numberList.join('*') + '=' + result)
}

Output from running the code snippet:

1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120
1*2*3*4*5*6=720

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

Ways to invoke a function within a React Material-UI component

Currently, I am in the process of setting up a chat system that allows users to add emojis. To achieve this feature, I have devised a function that produces a component containing both text and an image. Here is the function I have implemented: test: fu ...

Inquiry about Date and Time Selection Tool

I am working on a PHP project that includes two textboxes: one for selecting dates and the other for choosing a specific time. What I need assistance with is disabling any times before the selected date in the second timepicker textbox if today's dat ...

Get the ability to overlay text onto an image by using jQuery for downloading

Currently, I am facing an issue with an online photo editor in my project. The problem is that I am unable to download the image after adding and editing text on it. The texts added are editable but the image cannot be downloaded after the changes. I nee ...

Sorting technique failing to reorganize list

I'm currently troubleshooting why my sorting function is not functioning as expected. My goal is for it to operate similarly to this example: https://codepen.io/levit/pen/abmXgBR The data I am working with is retrieved from an API: <BookCard v-fo ...

Issue encountered while parsing JSON file using AngularJS

Having some trouble reading a json file in AngularJS using $http.get and encountering errors in the browser console. Check out my Plunker example: http://plnkr.co/edit/SDRpu1MmrTPpgpdb6Kyk?p=preview Below is the code snippet: Javascript:- var jayApp = ...

Remove the carriage return and newline characters from a Python variable

After successfully obtaining the page source DOM of an external website, I found that it contained \r\n and significant amounts of white space. import urllib.request request = urllib.request.Request('http://example.com') response = ur ...

How can we prevent excessive hook calls when utilizing components in React?

I've run into an issue with the modal component hook I created below. I want to set up this modal at the app level so that I can easily access it via a global state like Zustand whenever necessary. Here is the structure of the modal component: Crea ...

Sending values to URL using the <a> tag in HTML

I currently have the selected language stored in a variable (var lan= urlParam('language')). I am trying to pass this language as a parameter (without PHP) in a URL within an "a" tag, like so: <a href="http://hotelscombined.sitewish.gr/HotelN ...

What is the speed difference between calling functions from require's cache in Node.js and functions in the global scope?

Let's imagine a scenario where we have two files: external.js and main.js. // external.js //create a print function that is accessible globally module.exports.print = function(text) { console.log(text) } Now let's take a look at main.js: ...

What is the process for submitting data using AJAX in Django?

I am facing an issue with my dynamically updating form. When I submit the form, I want to post the data to a views function and receive a response. Below is the code from my template file: $("#myForm").submit(function(){ event.preventDefault(); va ...

Appium with Node.js (wd) becomes unresponsive when unable to locate element

Encountering an issue while using appium with nodejs (wd) and mocha, as there is a loading view in the android app (blackbox testing & I'm not the developer) that needs to be waited for its disappearance. Attempted the following solution: wd.addPromi ...

Making adjustments to a row in the free jqGrid is a breeze with the ability

Using free jqGrid 4.12.1, I aim to incorporate functionality for adding, editing, and deleting rows in the grid with server-side calls for each operation. Below is the implementation of editurl and 'actions' formatter, { name: "actions", wi ...

Tips for importing the mongoose-long plugin using the ES6 method

How can I rewrite the given import syntax into ES6 import format? import mongoose from 'mongoose'; import 'mongoose-long'(mongoose); import { Types: { Long } } from mongoose; ...

Navigating through Sails.Js: A Guide to Implementing Pagination

Looking to implement paginated tables in your application using sails.js, mongodb, and waterline-ORM? Wondering if there is a recommended method for pagination in sails.js? ...

Error: Trying to access "dishes" property on an undefined object gives a TypeError

Need Assistance Urgently! I have developed a web application using react and integrated it with node js. In the app, I am required to pass the status of a dish to the DishDetail Component indicating whether it is marked as "Favorite" or not. If a dish is ...

Guide on dynamically applying a CSS rule to an HTML element using programming techniques

Currently working with Angular 6 and Typescript, I am facing a unique challenge. My task involves adding a specific CSS rule to the host of a component that I am currently developing. Unfortunately, applying this rule systematically is not an option. Inste ...

Retrieve the value of the specific element I have entered in the ngFor loop

I've hit a wall after trying numerous solutions. Here is the code I'm working with: HTML: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styl ...

Expandable Grid Sections in React MUI

Is there a way to create a grid layout where items with showDefault: true are always displayed at the top, and then users can click an arrow button to expand the grid and also show the items with showDefault: false? Any suggestions on how to achieve this? ...

Opting for PHP over JSON in a jQuery live search code

Is it possible to modify my jQuery Google Instant style search script to pull content from a PHP script instead of using the BingAPI? Below is the current code being used: $(document).ready(function(){ $("#search").keyup(function(){ var searc ...

I encountered a SyntaxError that reads "Unexpected token instanceof" while using the Chrome Javascript console

I find it quite surprising that the code below, when entered into the Chrome JavaScript console: {} instanceof Object leads to the error message displayed below: Uncaught SyntaxError: Unexpected token instanceof Could someone kindly explain why this ...