Sum of Numbers Until N

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring the concept of summing all the numbers between 1 and a given number n. We will be using the formula (n * (n + 1)) / 2 to calculate the sum of numbers. Through this lab, you will gain a better understanding of how to solve mathematical problems using programming.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28634{{"`Sum of Numbers Until N`"}} javascript/data_types -.-> lab-28634{{"`Sum of Numbers Until N`"}} javascript/arith_ops -.-> lab-28634{{"`Sum of Numbers Until N`"}} javascript/comp_ops -.-> lab-28634{{"`Sum of Numbers Until N`"}} end

Function to Calculate Sum of Numbers Until N

To calculate the sum of numbers between 1 and n, you can use the formula (n * (n + 1)) / 2. Here's an example code in JavaScript:

const sumN = (n) => (n * (n + 1)) / 2;

To use this function, pass the value of n as an argument. For instance, sumN(100) will return 5050. To start practicing coding, open the Terminal/SSH and type node.

Summary

Congratulations! You have completed the Sum of Numbers Until N lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like