rss
Twitter Delicious Facebook Digg Stumbleupon Favorites

Tuesday, October 11, 2011

Write a program to find average of consecutive N Odd number and Even number.


In mathematics, the parity of an object states whether it is even or odd.
This concept begins with integers. An even number is an integer that is "evenly divisible" by 2, i.e., divisible by 2 without remainder; an odd number is an integer that is not evenly divisible by 2. (The old-fashioned term "evenly divisible" is now almost always shortened to "divisible".) A formal definition of an even number is that it is an integer of the form n = 2k, where k is an integer; it can then be showed that an odd number is an integer of the form n = 2k + 1. An even number has the form n = 2k where k is an integer.
Examples of even numbers are −4, 8, and 1728. Examples of odd numbers are −5, 9, 3, and 71. This classification only applies to integers, i.e., a fractional number like 1/2 or 4.201 is neither even nor odd.
The sets of even and odd numbers can be defined as following:
  • Even = \{ 2k; \forall k \in \mathbb{Z} \}
  • Odd = \{ 2k+1; \forall k \in \mathbb{Z} \}
A number (i.e., integer) expressed in the decimal numeral system is even or odd according to whether its last digit is even or odd. That is, if the last digit is 1, 3, 5, 7, or 9, then it's odd; otherwise it's even. The same idea will work using any even base. In particular, a number expressed in the binary numeral system is odd if its last digit is 1 and even if its last digit is 0. In an odd base, the number is even according to the sum of its digits – it is even if and only if the sum of its digits is even.

class EvenOdd{
      public static void main(String args[]){
      int n = Integer.parseInt(args[0]);
      int cntEven=0,cntOdd=0,sumEven=0,sumOdd=0;
      while(n > 0){
           if(n%2==0){
               cntEven++;
               sumEven = sumEven + n;
           }
           else{
               cntOdd++;
               sumOdd = sumOdd + n;
           }
           n--;
      }
      int evenAvg,oddAvg;
      evenAvg = sumEven/cntEven;
      oddAvg = sumOdd/cntOdd;
      System.out.println("Average of first N Even no is "+evenAvg);
      System.out.println("Average of first N Odd no is "+oddAvg);

  }
}

0 comments:

Post a Comment

Powered by Blogger.