DEV Community

Amera White
Amera White

Posted on • Updated on

JS Code Challenges : 1

JS Code Challenge 1

Problem:

Create an algorithm using a for loop that can add the sum of all natural numbers up to 100.

The Breakdown:

  • Natural numbers are positive whole integers

ex: 1, 2, 3

  • Find sum of natural numbers

ex: Find the sum of natural numbers of 5

1 + 2 + 3 + 4 + 5 = 15

  • Goal is to find the sum natural number up to 100

Hint: Use a for loop.

Solution:

Step 1

We need to have a constant variable that will not change.

That should be the value of 100.

const val = 100; 
Enter fullscreen mode Exit fullscreen mode

Step 2

We need a variable to hold our sum. We also know our sum is NOT constant and will be changing as we are on our way to the sum natural numbers up to 100.

let sum = 0;
Enter fullscreen mode Exit fullscreen mode

Step 3

Now that we have these variables we should be able to initialized a loop. We will use a for loop that will decrement.

for (let i = val; i >= 1; i-- ){ 

     //code to execute  

 }  
Enter fullscreen mode Exit fullscreen mode
  • Start by letting i equal our val (100)

  • Next, we want the loop to continue until i is greater than or equal to 1 (only natural numbers remember)

  • Then, for each loop we want to decrement

Step 4

Okay so, now we need to figure out what logic to implement every time the loop is executed.
Inside our code block ...

for (let i = val; i >= 1; i-- ){

   sum = sum + i  

 }   

//can also be written as sum += i

Enter fullscreen mode Exit fullscreen mode
  • To keep up with the changing sum, we want to update sum by making it equal to whatever the previous sum value is plus i

Test:

To test if we are going in the right direction, since we already know the sum of natural numbers of 5 is equal to 15 (from our Breakdown example).

Let's plug 5 into our loop, then console log the result. ***Don't forget to change it back to val after you're done the test.

for (let i = 5 ; i >= 1; i-- ){ 

 sum = sum + i

}

console.log('answer', sum); //returns 15     

Enter fullscreen mode Exit fullscreen mode

This means our loop is working correctly...Congrats!

Step 5
Alright, let's console log the current value of sum to get our answer.

for (let i = val; i >= 1; i-- ){ 

 sum = sum + i  

 }     

 console.log('answer', sum ); //returns 5050 


Enter fullscreen mode Exit fullscreen mode

Now, it’s your turn!

Practice

  • Try writing this out from scratch

  • Choose a different number to find the sum of its natural numbers

  • Use something other than a for loop to solve

Follow me for more!

Top comments (0)