Struggling to make a JavaScript program that sums up odd numbers

Let's tackle this challenge:

Your task is to create a program that adds up all the odd numbers between 1 and the number provided by the user. For instance, if the user inputs 7, the program should calculate 1 + 3 + 5 + 7. The result of this calculation, along with the expression used, should be displayed on the screen. In this case, the answer would be 16.

This is what I have so far:

//Setting up the required variables

var num = prompt("Please enter a number");
var sum = 1;
var currentNum = 1;
var operator = "+";

//Calculating the sum
document.write("The total sum of all odd numbers is: ");
do {
  if(num % 2 == 0) {
  }
  else{
    document.write(currentNum + operator);
    currentNum = currentNum + 1;
    sum = sum + currentNum;
  }
}while(currentNum < num); 

document.write(num + " equals " + sum);

Answer №1

An infinite loop has been created. Ensure that increase is incremented every iteration:

var sternum = prompt("please enter a number");
var tantalum = 0;
var increase = 1;
var expression = "+";

 //sum calculation
 document.write(" the sum of all numbers is: ");
 do {
     if(increase % 2 == 0) {
     }
     else{
       document.write(increase + expression);
       tantalum = tantalum + increase;
     }
     increase = increase + 1;
 }while(increase <= sternum); 

 document.write(" = " + tantalum);

To optimize it, you may change increase = increase + 1; to increase = increase + 2;. Processing even numbers is unnecessary. Moreover, tantalum should be initialized as 0.

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

Pattern for either one or two digits with an optional decimal point in regular expressions

Currently, I'm utilizing for input masking. I am specifically focusing on the "patterns" option and encountering difficulties while trying to create a regex expression for capturing 1 or 2 digits with an optional decimal place. Acceptable inputs: ...

What potential issues arise from utilizing useRef alongside useSelector?

Although I have the capability to access the store by using thunks and/or global stores, I avoid binding my component to the Redux store. This is because the component will be utilized with various stores both inside and outside of the project. The compone ...

Node.js POST request only executes successfully on the second attempt

I am facing a peculiar issue where upon submitting a form, it redirects to the form action URL and then displays a blank page. However, upon reloading the page, the data is displayed. index.jade - http://172.18.0.60:3000/ form#command(action='runc ...

Issues with Rails not successfully sending AJAX data to the controller

I am new to AJAX, so please bear with me while I try to figure this out. My goal is to send data from a chat message box to two places – the chat box itself and to a method in my Rails backend. This way, I can display the message in real-time and also st ...

Component re-rendering and initializing useReducer

I made some revisions to this post. Initially, I shared the entire problem with my architecture and later updated it to focus directly on the issue at hand in order to make it easier for the community to provide assistance. You can now jump straight to the ...

HTML elements not displaying in Ajax form

I am encountering an issue with my ajax based feedback form where the form is displaying the html from the response instead of processing it correctly. Here is the JQuery code: $(document).ready(function() { var form_holder = $('#form-holder'); ...

What is the best way to transfer GitHub OAuth information to a client?

I am in the process of implementing Github authorization and then sending received JSON data to the client. After doing some research, I came across a helpful tutorial at The tutorial suggests following this path: "/" -> "/login" -> "/redirect" -&g ...

Having trouble with res.redirect not working after the page has been rendered with data?

I have a basic forget password feature set up, where users can request a password change and receive an email with a token. Clicking the link in the email will redirect them to a page where they can input their new password. When I click on the email link ...

Revamp your JavaScript code to trigger when the clock strikes bold!

Having trouble setting up JavaScript to automatically bold the next clock time. Any tips on rewriting the JavaScript? For instance, if it is currently 6:49, I want the next clock time of 7:32 to be automatically bolded. And when the time reaches 7:32, I wa ...

Identifying with a jQuery IF statement all input fields that contain null values in order to eliminate the respective elements

My goal is to create a jQuery script that checks all input fields to see if they are empty. If an input field is empty, I want to remove the child image of the next occurring span element. Here is what I have attempted so far: if ($("input").val() == "") ...

Challenges with saving a segment of an AJAX GET response (in JSON) as a string variable

I am facing an issue while attempting to save a section of the result obtained from a GET request through AJAX into a string variable. Essentially, my goal was to ensure that a specific function containing a GET request operation can return the outcome of ...

Managing dynamically appearing elements in Ember: Executing a Javascript function on them

I'm currently working on a project in Ember and facing an issue with calling a JavaScript function when new HTML tags are inserted into the DOM after clicking a button. Below is a snippet of my code: <script type="text/x-handlebars" id="doc"&g ...

Data obtained from the server includes JSON objects along with quotes and regular expressions

While analyzing the functionality of a search page server through element inspection, it was observed that requests are sent via POST with JSON parameters. To verify this observation, I recreated the same POST request using Insomnia with identical paramete ...

What is the best way to retrieve a specific key from a JavaScript Map containing an array?

I am currently iterating through a two-dimensional array to populate a map. The map is using the [i,j] indices as keys and the corresponding arr[i][j] values as values: const arrMap = new Map() for(let i = 0; i < arr.length; i++){ for(let j = 0 ...

What is the origin of the second parameter in an arrow function that returns another arrow function in a React component with Redux?

I'm having trouble understanding where the (val) parameter is coming from in the returned arrow function. I understand that max/minLength is an arrow function taking an argument set on the input field (3 and 25), and it returns another arrow function ...

Guide to properly deserializing a JSON string into a class with a nested List of different class members

I have a scenario where I am sending a JSON stringified "View" object from the browser to an ASP.Net Page Method using Jquery's $.Ajax(). The issue I am facing is that while the Javascript deserialization is successful for all the strings and integers ...

What is the best approach to determine the numerical equivalents of options in a dropdown menu using PHP and JS

Hey guys, I'm really stuck on this problem and I can't seem to find a helpful tutorial anywhere. I've got a form with two drop-down menus, each with a "value" attribute. What I want is for users to be able to select an item from both drop-do ...

Load Bootstrap 4 Modal with Ajax

I recently upgraded from Bootstrap 3 to Bootstrap 4.1 Within my applications, I utilize ajax loaded modals. In the layout, I have: <div class="modal fade" id="myModalToFillInfo" tabindex="-1" role="dialog" aria-labelledby="myModalToFillInfoLabel" ari ...

Retrieving data from MongoDB for rendering on an HTML page

I have successfully inserted data into my MongoDB database, but I am facing issues with the "get" function to display this data on my HTML page. My current setup involves using Node.js with Express framework and Angular for front-end development and routi ...

The issue arises when attempting to utilize ExpressJS middleware in conjunction with NextJS Link feature

Incorporating Next with Express routes, I have set up a scenario where /a should only be accessible to authorized individuals, while /b is open to the public. ... other imports... const app = next({ isDev }) const handle = app.getRequestHandler() async f ...