3

I'm writing a program in Javascript that separates even and odd numbers, puts them into an array, adds the sum of numbers, and finds the average.

I'm having an issue not allowing zeros not to count. Because its adding to the array, and when the user types in 6+6, sum is 12, average is calculating to 4 because of the extra 0 in the array.

Is there anyway to not allow the zeros to count? Here is what I have so far..

var evenarray = [];
    var oddarray = [];
    var avgEven = 0;
    var avgOdd = 0;
    var isValid;
    function numberFunction(){

        do  
        {

            var numbers = prompt("Please enter numbers. Enter empty string to exit.");

            if(numbers % 2 == 0)
            {   
                    evenarray.push(numbers);
                    var sumEven = 0;
                        for (var i=0; i < evenarray.length; i++)
                        {
                            sumEven = sumEven + Number(evenarray[i]);
                        }
                    var avgEven = sumEven/evenarray.length;
                    //alert("even");

            }
            if(numbers % 2 !== 0)
            {
                    oddarray.push(numbers);
                    var sumOdd = 0;
                        for (var i=0; i < oddarray.length; i++)
                        {
                            sumOdd = sumOdd + Number(oddarray[i]);
                        }
                    var avgOdd = sumOdd/oddarray.length;
                    //alert("odd");
            }

            //if(isNaN(numbers)){

                //alert("Only numeric data only");
                //}
        }

        while(numbers !== "");
5
  • 1
    Where is the zero coming from? What does evenarray look like when you're trying to calculate it? Also, you should use parseInt instead of Number to ensure that the values are numbers, however, you're only allowing numbers to be pushed into the array, so you don't even need that check... Commented Jan 19, 2014 at 18:51
  • Can you post an example of input and output and reproduce the issue here jsfiddle.net? Commented Jan 19, 2014 at 18:52
  • To exclude 0's being added why dont you create a filter for 0 ex. if(numbers % 2 == 0 && numbers !== 0) and if(numbers % 2 !== 0 && numbers !== 0) Commented Jan 19, 2014 at 18:57
  • Yes, exactly. What I have so far jsfiddle.net/B5aQv Commented Jan 19, 2014 at 19:04
  • its strange to calculate sums and averages at every time the loop is running. you should calculate those after terminating the loop. Commented Jan 19, 2014 at 19:04

4 Answers 4

1

Just do nothing when the number is actually 0:

if (numbers == 0)
{
}
else if(numbers % 2 == 0)
{   
  evenarray.push(numbers);
  var sumEven = 0;
  for (var i=0; i < evenarray.length; i++)
  {
    sumEven = sumEven + Number(evenarray[i]);
  }
  var avgEven = sumEven/evenarray.length;
}
else  // only odds remain
{
  oddarray.push(numbers);
  var sumOdd = 0;
  for (var i=0; i < oddarray.length; i++)
  {
    sumOdd = sumOdd + Number(oddarray[i]);
  }
  var avgOdd = sumOdd/oddarray.length;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Returning would jump out of the loop, so that's probably a terrible approach. You could continue when numbers == 0, if that looks better to you. The end result is exactly the same, and I was trying to introduce as few new ideas as possible in the process of showing a working approach.
Ahh, missed to do loop, you're right. Dunno, maybe I'd use continue I guess, or just probably take a completely different approach.
Thanks Paul, I used this approach. Super simple, don't know how it slipped my mind. Still only a few months of programming under my belt. Is there a better way to exit the loop rather than having an empty string to exit? When I put in an empty string, it considers it a 0 still and comes up with an alert box that I put under: if (numbers == 0) { alert("zeros or letters not allowed"); } I realize I can not have the alert to make that work, but any way to ignore the alert when exiting? **sorry not sure how to make the code show up as a block under these comments.
0

You can do :

if(numbers % 2 == 0 && numbers !=0) ...
if(numbers % 2 != 0 && numbers !=0) ...

so that you don't do anything when numbers == 0;

It's a little strange to call your variable numbers instead of number.

1 Comment

Thanks for the reply everyone, i'll definitely try it when I get in. and switch my variable to "number", just did it quickly yesterday so still a little sloppy.
0

your function should be,

function numberFunction(){

    do  
    {
        var numbers = prompt("Please enter numbers. Enter empty string to exit.");
        if(numbers !=0 && !isNaN(numbers)) 
            (numbers %2 == 0)? (evenarray.push(parseInt(numbers))) : (oddarray.push(parseInt(numbers)));
    }while(numbers !== "");

    for(var i = 0; i < evenarray.length; i++)
        sumEven += evenarray[i];

    for(var i = 0; i < oddarray.length; i++)
        sumOdd += oddarray[i];

    avgEven = sumEven / evenarray.length;
    avgOdd = sumOdd / oddarray.length;

document.getElementById("even").innerHTML = evenarray.toString();
document.getElementById("sumEvenTotal").innerHTML = sumEven.toString(); //displays sum of even numbers.
document.getElementById("averageOdd").innerHTML = avgOdd; //displays average of odd numbers.
document.getElementById("averageEven").innerHTML = avgEven; //diplays average of even numbers.
document.getElementById("odd").innerHTML = oddarray.toString(); //displays all odd numbers that were entered.
document.getElementById("sumOddTotal").innerHTML = sumOdd.toString();
}

Comments

0

As you already have other answers with solutions to your particular issue, I would suggest a different approach. Think of the data you're manipulating: an array. Try to solve the issue only with data, no user input, no DOM manipulation; just data. This helps to separate concerns, and make your code easier to understand.

Since we're working with arrays, we can make use of some of the built-in JavaScript methods that are present in modern browsers, such as filter and reduce. These methods are in a way, alternatives to for loops, with some pre-defined behavior, and a callback function.

Now, let's think of the steps involved in solving your problem.

  1. Get numbers from the user. We can represent this data as an array, as you were already doing.
  2. We want all odd numbers, their sum and average.
  3. We want all even numbers, their sum and average.
  4. We display the data to the user.

In this solution I'm assuming you already have an array with the data, and will be focusing on points 2 and 3. Remember, think of data, user interaction shouldn't be mixed with your data logic. Instead of asking the user for a number on each loop, you could ask the user for a list of numbers directly; you avoid multiple prompts this way, and it lets you separate data and interaction nicely. Ideally you'd validate all user input to match your requirements.

// Helpers to work with numbers
var odd = function(x) {
  return x % 2 === 0;
};

var even = function(x) {
  return x % 2 !== 0;
};

var add = function(x, y) {
  return x + y;
};

function solve(ns) {
  // Solve the problem
  // with odd or even numbers
  var result = function(fn) {
    var xs = ns.filter(fn); // odd or even
    var sum = xs.reduce(add);
    return {
      numbers: xs,
      sum: sum,
      average: sum / xs.length
    };
  };
  // Return an object
  // with odd and even results
  return {
    odd: result(odd),
    even: result(even)
  };
}

var numbers = [1,2,3,4]; // from user input
var result = solve(numbers);

console.log(result.odd);
//^ {numbers: [2,4], sum: 6, average: 3}

console.log(result.even);
//^ {numbers: [1,2], sum: 4, average: 2}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.