Write a javascript code to print all the odd numbers from 15 backwards to 3

Before reading this code you should have an understanding of for loop and if-else statements in Javascript.

Algorithm:

Line 1: In line number 1 we use for loop. The variable i will be initialized the value 15 since we want to start the loop from 15 and we need to check the condition i>2 since we want to end the loop at 3.
At each loop value of i will be reduced by 1.

Line 3: We will use if statement to check weather the value of i is even or odd. If the value of i is odd then we will print the i.

for(var i = 15;i>2;i--)
  {
    if(i%2!=0)
      {
        console.log(i);
      }
  }

The output of the code is

15
13
11
9
7
5
3

Another way to write the same code is

for(var i = 15;i>2;i = i-2)
  {
    console.log(i)
  }

The output of the code is

15
13
11
9
7
5
3

Facebook
Twitter
LinkedIn
Pinterest

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME !!
Johan William

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

RECENT POSTS

TEST