Java > Array-1 > sum3 (CodingBat Solution)

Problem:

Given an array of ints length 3, return the sum of all the elements.

sum3({1, 2, 3}) → 6
sum3({5, 11, 2}) → 18
sum3({7, 0, 0}) → 7


Solution:

public int sum3(int[] nums) {
  return nums[0] + nums[1] + nums[2];
}


5 comments :

  1. public int sum3(int[] nums) {
    int sum=0;
    for(int i=0;i<nums.length;i++)
    {
    sum = sum + nums[i];

    }

    return sum;

    }

    ReplyDelete
  2. public int sum3(int[] nums) {
    int total = 0;

    for(int x : nums){
    total = total + x;
    }
    return total;
    }

    ReplyDelete
  3. public int sum3(int[] nums) {
    return nums[0]+nums[1]+nums[2];
    }

    ReplyDelete
  4. public int sum3(int[] nums) {
    return (nums[0]+nums[1]+nums[2]);
    }

    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