- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Function to add up all the natural numbers from 1 to num in JavaScript
We are required to write a JavaScript function that takes in a number, say num.
Then our function should return the sum of all the natural numbers between 1 and num, including 1 and num.
For example, if num is −
const num = 5;
Then the output should be −
const output = 15;
because,
1+2+3+4+5 = 15
We will use the below formula to solve this problem −
Sum of all natural number upto n =
((n*(n+1))/2)
Example
The code for this will be −
const num = 5; const sumUpto = num => { const res = (num * (num + 1)) / 2; return res; }; console.log(sumUpto(num)); console.log(sumUpto(7)); console.log(sumUpto(45)); console.log(sumUpto(2)); console.log(sumUpto(8)); console.log(sumUpto(99));
Output
And the output in the console will be −
15 28 1035 3 36 4950
Advertisements
To Continue Learning Please Login
Login with Google