Blog
Solution for sum of odd and even numbers
- January 9, 2018
- Posted by: admin
- Category: javascript Programming

Solution for sum of odd and even numbers
NOTE – to watch the video of the solution, log in to youtube with your registered email at the Academy
Hi, this is Aniruddha from DCT Academy Bangalore. We are going to be looking at the solution for the problem “sum of odd and even elements ”.
Given an integer N, you have to print the sum of odd numbers and even numbers from 1 to N. For example, let us say if the value of n is 5 then the output is going to be 9 is the sum of odd numbers and 6 is the sum of even numbers. If the input of n is 6 then the sum of odd numbers is gonna be 9 and the sum of the even number is going to be 12.
Example: Input: 5 6 Output: 9 6 9 12
Now let’s go ahead and solve this particular problem. I’m going to create several variables, to begin with. I’m going to create a variable called as n and assign an input of a value of 5. Next, I’m going to create two new variables to hold the sum of odd numbers and the sum of even numbers. I’m going to call it as oddSum initially and I will assign it to 0, I’ll create another variable called as evenSum and again I will assign the value to be 0. I’ll create a variable called as I and assign it to the value of 1 because i is from 1 to the value of N.
var n = 5; var oddSum = 0; var evenSum = 0; var i = 1; // initialization
Let’s go ahead and use a while loop and here I’m going to be looking for a condition, while var i is less than or equal to the value of var N, now we need to keep in mind that while you’re working with loops you’re going to take care of three things :
- initialization
- condition
- incrementation / decrementation
while(i <= n){ // condition i++; // incrementation }
Now let’s add a conditional check. I’ll now say if var i % 2 == zero that is if the remainder is zero then it’s going to be an even number. If var i is an even number then for my var evenSum I will add the value of my var i, if it is not 0 then I would add it to my var oddSum the value of var i.
if(i % 2 == 0) { evenSum += i; } else { oddSum += i; }
now let’s console.log our var oddSum, and var evenSum
console.log(oddSum, evenSum);
Let’s run this program I get the output as 9 and 6 if I change the value of my n to be the value of 6 then I get the output as 9 and 12 as expected.
Solution
var n = 6; var oddSum = 0; var evenSum = 0; var i = 1; // initialization while(i <= n){ // condition if(i % 2 == 0){ evenSum += i; } else { oddSum += i; } i++; // incrementation } console.log(oddSum, evenSum);