Calculating the total of n natural numbers by utilizing a for loop

I have a question that involves calculating the sum of ten natural numbers, but for some reason the code provided is not working as expected.

<!DOCTYPE html>
<html>
<head>
    <title>Sum of first 10 Natural numbers</title>
</head>
<body>
    <script>
       var sum = 0, n;
       parseInt(prompt("Enter the number: "));
       for (let i = 0; i <= n; i++) {
        sum += i; 
       }
       alert("Sum of Numbers: " + sum);
    </script>
    
</body>
</html> 

Answer №1

The issue with your code not functioning correctly was due to the failure to store the prompt value in a variable.

let total = 0, x;
x = parseInt (prompt("Please enter a number: "));
for (let j = 0; j <= x; j++) {
  total += j; 
}
alert ("Total of Numbers: " + total);

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

Why are my menu and title shifting as I adjust the page size?

I'm having trouble finalizing my menu and headings. Whenever I resize the browser window, they shift to the right instead of staying centered as I want them to. I would really appreciate any help with this. Below is the HTML and CSS code. var slide ...

Creating an iPad-inspired password field experience in a text input with jquery: A step-by-step guide

Looking for a plugin that mimics the iPad's password field behavior for credit card number entry. The focus should only reveal the entered digit and then switch to a bullet as the next digit is typed. Additionally, all previously entered digits should ...

Unable to perform a default import in Angular 9 version

I made adjustments to tsconfig.json by adding the following properties: "esModuleInterop": true, "allowSyntheticDefaultImports": true, This was done in order to successfully import an npm package using import * as ms from "ms"; Despite these changes, I ...

Having difficulties grasping the concept of how to communicate effectively with my MySQL database

Apologies in advance for asking a question that may have been answered elsewhere, but I've been struggling for hours to transfer the information into my own program. Despite my attempts, I always encounter the same obstacles. So, I decided it would be ...

issues encountered with sending a multidimensional array using ajax, specifically with the index[0]

I'm struggling with sending a multidimensional array from PHP to Javascript/jQuery, encountering a peculiar issue. Upon transmitting index 0 through json_encode($array);, the desired response format is successfully received by the client: [[0,0],[1, ...

Executing synchronous animations in Jquery with callback logic

My jQuery plugins often rely on user-defined callbacks, like in the example below: (function($) { $.fn.myplugin = function(options) { var s = $.extend({}, options), $this = $(this); if (typeof s['initCallback'] = ...

Ensure that the form is validated even when setState is not executed immediately

I am currently working on a form in React and I am facing an issue with validation. When the Submit Form button is clicked without filling in the input fields, an error should be displayed. This part is functioning correctly. However, even when the fields ...

"Enhance Your Online Shopping Experience with Woocommerce Ajax Filters and

I have a structure that looks like this: Company Google Apple Microsoft Material Wood Metal Plastic Essentially, Brand & Material are attributes in the Woocommerce system, while the rest are variables. I am currently working on implementing AJAX fi ...

Smooth-scrolling feature with touch interaction available in the scrollbar extension

Anyone here aware of a high-quality jQuery or CSS plugin for scrollbars that supports touch functionality and smooth easing? I've been on the lookout for one, but haven't had any luck so far. Even if it comes with a price tag, I'm interested ...

Tips for accessing elements other than the root element using this.$el

Within my template, the structure is as follows: <div v-show="showContent" class="content-block-body"> <div class="slider-pro"> <div class="sp-slides"> <slide v-for="block in subItems" ...

The issue of memory leakage in Three.js

I have come across an unusual memory leak in three.js (r73). Here are the steps to reproduce it: 1) Go to the following link using Google Chrome (version 46.0.2490.80 m) 2) Open DevTools -> Profiles -> Take Heap Snapshot. Check out my screenshot be ...

Tips for preventing the occurrence of numerous instances of braintree.setup in Angular

I am encountering an issue with a Braintree payment form displayed in a modal window: $scope.displayModalBraintree = function () { $scope.modal = 'modal_payment_form.html', $scope.$on('$includeContentLoaded', function () { ...

Utilizing Node and Express to promptly respond to the user before resuming the program's

I am accustomed to receiving a user's request, handling it, and providing the outcome in response. However, I am faced with an API endpoint that requires about 10 tasks to be completed across various databases, logging, emailing, etc. All of these ta ...

Is there a way to extract data from a JSON file with dc.js?

As a beginner in programming, I am looking to learn how to import data from a JSON file using dc.js. ...

Each time the server restarts, Express.js will run a function asynchronously

Looking for guidance on implementing a function in my Express.js app that can fetch data from the database and then cache it into Redis. The goal is to have this function executed only upon restarting the Web server. Any suggestions on how I can achieve t ...

"415 (Unsupported Media Type) encountered when making a POST request in a REST API

I've encountered an issue with a React component where a checkbox triggers a POST request to a REST API with a single parameter. Despite setting a breakpoint in the WebAPI code, it's not being hit and I'm receiving a 415 Unsupported Media Ty ...

Change the CSS element if the current URL is not example.com/page1 or example.com/page2

When I apply the following JS code snippets, my output is incorrect or does not display at all. Below are the codes in question: if (location.href != "website.com/page1" || "website.com/page2") { element.style.backgroundColor='none'; ...

Icon button not found

I have created a reusable hook component for input fields. The TextField renders perfectly, but the IconButton is not showing up. const InputHookComponent = (props) =>{ const [val, setval]=useState(""); const cmp = <TextField type={ ...

Why does Internet Explorer throw a null pointer exception while Firefox does not?

My script loops through an array of HTML tag IDs, with some elements being empty. It works perfectly in Firefox but throws a null pointer or 'not an object' error in IE. if((storedVars.id) != ("")){selenium.browserbot.getCurrentWindow().document ...

converting nested object structures in typescript

I'm trying to flatten a nested object in my Loopback and Typescript controller Here's the structure of my model : export class SampleModel { id: number; code: number; guide?: string; gradeData?: string; } Take a look at this example obj ...