Java > Array-2 > countEvens (CodingBat Solution)

Problem:

Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.

countEvens({2, 1, 2, 3, 4}) → 3
countEvens({2, 2, 0}) → 3
countEvens({1, 3, 5}) → 0


Solution:

public int countEvens(int[] nums) {
int even = 0;
  for (int count=0; count < nums.length; count++) {
  if (nums[count] % 2 == 0)
  even++;
  }
  
  return even;
  
  }


8 comments :

  1. public int countEvens(int[] nums) {
    int even = 0;
    for(int count=0; count < nums.length; count++)
    {
    if(nums[count] % 2 == 0)
    {
    even++;
    }
    }
    return even;
    }

    ReplyDelete
  2. public int countEvens(int[] nums) {

    int count=0;

    for(int i=0;i<nums.length;i++){
    if(nums[i]%2==0){
    count++;
    }
    }

    return count;
    }

    ReplyDelete
  3. public final int countEvens(int[] nums) {
    int evenCount = 0;
    for(final int i: nums){
    if(i % 2 == 0){
    evenCount ++;
    }
    }
    return evenCount;
    }

    ReplyDelete
  4. public final int countEvens(int[] nums) {
    int evenCount = 0;
    for(final int i: nums){
    if(i % 2 == 0){
    evenCount ++;
    }
    }
    return evenCount;
    }

    ReplyDelete
  5. public final int countEvens(int[] nums) {
    int evenCount = 0;
    for(final int i: nums){
    if(i % 2 == 0){
    evenCount ++;
    }
    }
    return evenCount;
    }

    ReplyDelete
  6. public int countEvens(int[] nums) {
    int count = 0;
    for(int i : nums){
    if(i % 2 == 0)
    count++;
    }
    return count;
    }

    ReplyDelete
  7. public int countEvens(int[] nums) {
    int EvenCounter=0;
    if(nums.length!=0||nums!=null){

    for(int i=0;i<nums.length;i++){
    if(nums[i]%2==0){
    EvenCounter+=1;
    }
    }
    }
    return EvenCounter;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact