Looping through numbers from 0 to 100, calculating and displaying the total sum of even numbers and odd numbers separately in an array

I am attempting to iterate through numbers from 0 to 100 and calculate the sum of even numbers and odd numbers in an array format, for example [2550, 2500].

let total = 0;

for(let num = 0; num <= 100; num++) { 
  total = total + num;
}

console.log(Array.from(String(total)));

However, this code outputs  ['2', '5', '0', '0']

Could someone please guide me on how to display both sums as arrays?

Additionally, I need help with incorporating this code into another conditional statement so that I can obtain both the sum of odd numbers and even numbers. I'm having trouble deciding whether to use else if or if else....

Answer №1

To determine if a number is even or odd, simply check the remainder when divided by 2. If the remainder is zero, it's even; otherwise, it's odd.

let totalEven = 0;
let totalOdd = 0;

for(let num = 0; num <= 100; num++) {
    if(num % 2 === 0) {
        totalEven += num;
    } else {
        totalOdd += num;
    }
}

Finally, you can output the totals for both even and odd numbers using

console.log([totalEven, totalOdd])
.

Answer №2

Since you've tagged this question with , I believe it's worth mentioning the concept of triangular numbers:

function calculateOddEvenSum(value) {
    const floorVal = Math.floor(value / 2);
    const ceilVal = Math.ceil(value / 2);
    return [ceilVal * ceilVal, floorVal * (1 + floorVal)];
}

console.log(calculateOddEvenSum(100))

Without using a function:

const value = 100; // Example
const floorVal = Math.floor(value / 2);
const ceilVal = Math.ceil(value / 2);
const resultArray = [ceilVal * ceilVal, floorVal * (1 + floorVal)];
console.log(resultArray)

Answer №3

This code snippet calculates the total sum of numbers within the range of 0 to 100.

The variable m holds the sum of the range(0-100), which is 5050.

for(let i=0;i<=100;i++) { 
  m = m + i;
}

The following line splits the digits of the variable m and creates an array from them.

console.log(Array.from(String(m)));

['5','0','5','0']

You can create two variables for even_sum and odd_sum, then check if a number is odd or even, adding it to the appropriate sum.

let even_sum=0;
let odd_sum=0;

for(let i=0;i<=100;i++) { 
    if (i%2==0)
        even_sum+=i;
    else
        odd_sum+=i;
}

To return the values as an array, you can use the following code:

console.log([even_sum,odd_sum])

Answer №4

Utilize an array to calculate the sum of each parity separately.

arr=[0,0];
for (i=0;i<101;i++)
arr[i%2]+=i;
console.log(arr);

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

Exploring Nashorn's Global Object Variables Through Access and Intercept Techniques

I recently came across a question called "Capturing Nashorn's Global Variables" that got me thinking. I'm facing limitations when it comes to capturing the assignment of variables to the global object. For example, let's say I evaluate the ...

Is it possible to access the grid in ASP.NET Kendoui through code?

When trying to access my grid from Javascript code, I seem to have made mistakes. Can you help me locate them? This is the Grid code I am using: <div id="kendoo"> @(Html.Kendo().Grid<SalePortal.ServiceReference.Product>() .Name("Grid") .Col ...

Develop a Greasemonkey userscript that eliminates specific HTML lines upon detection

I am attempting to create a Grease Monkey script that can eliminate specific lines in HTML code. For example, consider the following: <ul class="actionList" id="actionList" style="height: 158px;"> <li class="actionListItem minion minion-0 fi ...

Trouble arises when the properties of this.props are supposed to exist, yet they are not

Wow, what a name. I am struggling to come up with a better title given my current state. The problem at hand is as follows: When using React, I set the state to null during componentWillMount. This state is then updated after data is fetched from a serve ...

Not all elements are removed by an array

$channels = array('imaqtpies','imsoff','zzero71tv', 'kaptenen', 'onlySinged', 'nightblue3') ; $nr = 0; $callAPI = implode(",",$channels); $online = 'online.png'; $offline = ' ...

Updating a route in Next.js? Make sure to remove the classList as you

Looking to remove a specific class whenever the route changes in Next.js, I've attempted the following approach: React.useEffect(() => { const activatedLink = router.query.tags const classActivated = document.querySelector('.'+activated ...

Having trouble activating the Invalidate Cache function in rtk query with tags

Here is a snippet from my Api.js file: export const api = createApi({ reducerPath: 'api', baseQuery: fetchBaseQuery({ prepareHeaders: (headers, { getState }) => { const userInfo=JSON.parse(localStorage.getItem('userInfo' ...

Is it necessary to validate my form multiple times?

Everything seems to be in order with my code here. However, I encountered an issue where I need to implement some code validation to prevent form submission if there are any errors present. Below is the additional code I included: Jquery code: var use ...

Consolidate all important values into a single NSMutable Array

Looking for a solution to combine multiple "ingredients" key values from a JSON file into one array? Here's a snippet of the JSON structure: { "locations": [ { "ingredients" : "Biscuits\n3 cups All-purpose Flour\n2 Tablespoons Ba ...

Issue with generating WebGL shaders

As I embark on creating a basic application in WebGl and JavaScript following online tutorials, I encountered a peculiar issue while working on some fundamental shaders. The function responsible for generating the shader program presents itself as follows: ...

What is the process of displaying multiple static files using Express?

I am currently working on a project where I am using Express to render various HTML files from my public folder. These files are static in nature. Additionally, I want to display a 404 page if an invalid route is accessed. Below is the code snippet I have ...

Transferring a JavaScript object to a Vue.js component

I am facing an issue with displaying products using the product component. Initially, in my vue.js application, I retrieve products via ajax as shown below: var app = new Vue({ el: '#app', data: { products: [] // will be ...

Tips for implementing fluid transitions between mouse X and Y coordinates using JavaScript

I recently developed a function that enables a DOM element to follow the mouse cursor. You can check out the code here. Currently, I am looking for suggestions on how to add a nice animation to this feature. Ideally, I want to incorporate a slight delay w ...

Refreshing a div component in Rails by using JavaScript after form submission

In my database, I have a table called "whatsup" and another one called "users". The structure is set up in such a way that each whatsup belongs to a user. Users can create new whatsups using Ajax, as shown below: $("#chat").append("<%= j render(@whatsu ...

How can I determine if my clients are utilizing the CDN or NPM versions of my JavaScript library?

At this moment, I'm contemplating releasing an open-source version of my library on NPM. My main concern is figuring out how to track the usage of my CDN or NPM by clients. Is there a method available to achieve this? ...

How to replicate the functionality of jQuery's each() method to get the height

My objective is to achieve uniform heights for all bootstrap card headers, bodies, and footers without relying on JavaScript. After researching, I came across a jQuery code snippet (https://codepen.io/felinuxltda/pen/KKVVYYN?editors=1111) that helped me ac ...

"Unleashing the Power of Effortless Object Unwr

Looking for a better way to convert a raw json snapshot from Firebase into a JS class. My current method is lengthy and inefficient. Does anyone have a more optimal solution? Class: class SuggestedLocation { country_slug region_slug slug marker_ty ...

Getting Started with the Basic Example of Redux-Router

Recently, I decided to give redux-router a try and wanted to run the basic example. However, when I tried running the command: npm start I encountered an error message that said: node: bad option: -r Being new to the JavaScript modern ecosystem, I&apos ...

Looking for a specific value within an array in PHP

Within my program, I have arrays structured as shown below. I am trying to determine if a specific value exists within an array. return [ "affiliates" => [ "name" => 'Affiliates', "value" = ...

What is the best method to eliminate elements from one array based on the presence of an element in another array in Python

I need help removing all the nans from D1 or B1, as well as the same i-th elements from all the arrays (e.g. 2nd element of each array, and so on). import numpy as np V1 = [ 7.98083 16.5216 18.4423 15.644 15.539 15.89 12.092 19.4274 14.953 15 ...