I'm trying to sum up all of the elements in an array.
What do I need to put in for blank space of int i = ______; to make this work?
public static int sumArray(int [] A){
int sum = 0;
int i = ___________ ;
while(i>=0){
sum = sum + A[i];
i--;
}return sum;
}
I'm trying to sum up all of the elements in an array. What do I need to put in for blank space of 'int i = ______;' to make this work?
You should specify the size of array A to i by doing i = A.length - 1;.
Alternatively, you can use a for loop instead of while.
Here is the code snippet:
public static int sumArray(int [] A){
int sum = 0;
for(int x : A) {
sum += x;
}
return sum;
}
You've already written the code to get the sum. i just needs to start out at A.length.
There are many other ways to get the sum: using an enhanced "for each" loop; using IntStream.of(A).sum(); other library methods.
To answer your question, you should set int i to A.length - 1. You want length - 1 because Arrays are indexed at 0 which means using length alone will cause you an IndexOutOfBoundsException.
Your method should look like this:
public static int sumArray(int[] A) {
int sum = 0;
int i = A.length - 1;
while (i >= 0) {
sum = sum + A[i];
i--;
}
return sum;
}
However, you can do this in much more cleaner ways.
1) Using Java 8 you can use IntStream like so:
public static int sumArray(int[] A) {
return IntStream.of(A).sum();
}
2) You can use a for loop:
public static int sumArray(int[] A) {
int sum = 0;
for(int i = 0; i < A.length; i++){
sum += A[i];
}
return sum;
}
3) You can use an enhanced for loop:
public static int sumArray(int[] A) {
int sum = 0;
for(int i : A){
sum += i;
}
return sum;
}
Related
I'm new to this forum and to programming and I have my first question :)
The objective is to return the sum of the first two integers in the array. My solution is in the picture I've added. Is there a way to solve this with less if cases? (I know I did not have to do the for loop, but I just learned it and wanted to try it out :D)
Thank you for all answers!
https://i.stack.imgur.com/hx06s.png
Edit: Here's my code:
public int sum2(int[] nums) {
int sum = 0;
if(nums.length == 0){
return sum;
}
if(nums.length == 1){
return nums[0];
}
for(int i = 0; i < 2; i++){
sum += nums[i];
}
return sum;
}
you can use limit() method in stream
public long sum2(int[] nums) {
return Arrays.stream(nums).limit(2).sum();
}
You can handle it in this simple way:
public int sum2(int[] nums) {
if (nums.length == 0)
return 0;
if (nums.length == 1)
return nums[0];
return nums[0] + nums[1];
}
You can't remove the two if statements form the code, unless you want to unnecessarily complicate it, for example, as #axurefrog wrote in his comment:
public int sum2(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length && i < 2; i++)
sum += nums[i];
return sum;
}
This returns the sum of the first n value of the array:
public int sum(int[] arr, int n) {
int sum = 0;
int num = Math.min( arr.length, n );
for( int i=0; i < num; i++ ) {)
sum += arr[i];
}
return sum;
}
Here are two alternative solutions which somewhat look "better":
sum2() with switch so no if statements
sum3() with nested ternary expressions, makes it very short.
It's good practice to avoid multiple return so you can keep the single entry - simple exit point of the algorithm, supporting debugging.
I've left the snippet wrapped up so you can try them by a single copy/paste.
public class Main{
public static int sum2(int[] nums) {
int sum = 0;
switch (nums.length) {
case 0:
break;
case 1:
sum = nums[0];
break;
default:
sum = nums[0] + nums[1];
break;
}
return sum;
}
public static int sum3(int[] nums) {
return nums.length == 1 ? nums[0] : nums.length >= 2 ? nums[0] + nums[1] : 0;
}
public static void main(String []args){
int[] nums1 = {11, 13, 1, 0}; // expected: 24
int[] nums2 = {3}; // expected: 3
int[] nums3 = {}; // expected: 0
System.out.println("sum2: " + sum2(nums1));
System.out.println("sum2: " + sum2(nums2));
System.out.println("sum2: " + sum2(nums3));
System.out.println(' ');
System.out.println("sum3: " + sum3(nums1));
System.out.println("sum3: " + sum3(nums2));
System.out.println("sum3: " + sum3(nums3));
}
}
The output:
sum2: 24
sum2: 3
sum2: 0
sum3: 24
sum3: 3
sum3: 0
You can simply do this without if-else headache
public int sum2(int[] nums)
{
int sum = 0;
for(int i = 0; i < nums.length && i < 2; i++) sum+=nums[i];
return sum;
}
Edit:
Adding i < nums.length in for loop condition to take care of empty array as per comment from Luca Murra
If you're using Java8 or above, and want to have a more generic solution (meaning sum of N numbers) you can use streams as follow:
public long sum2(int[] nums) {
return Arrays.stream(nums).sum();
}
I want to create a program to find the sum of factorial of all numbers in a series till 20.
I have to find 's' in s = 1 + (1*2) + (1*2*3) + ...(1*2*3...20).
I tried a program but it is not working. I am using BlueJ IDE.
int a =1;
int s = 0;
for(int i = 1; i <= 10; i++)
{
while (i >0)
{
a = a * i;
i--;
}
s = s+a;
}
System.out.println(s);
The compiler does not show any error message but when I run the program the JVM(Java Virtual Machine) keeps loading and the output screen does not show up.
You can try this one :
public class Main
{
public static void main (String[]args)
{
int fact = 1;
int sum = 0;
int i, j = 1;
for (i = 1; i <= 20; i++)
{
for (j = 1; j <= i; j++)
{
fact = fact * j;
}
sum += fact;
System.out.println ("sum = " + sum);
fact = 1;
}
}
}
Always give proper variable name and Try to avoid to use same variable at different places i.e you have use variable i in outer and inner loop which is not good habit.
You should be using a different loop variable name in your inner loop, and you also need to use a long to store your sum. In fact, I would first write a method to multiply up to a number in the series. Like,
static long multiplyTo(int n) {
long r = 1L;
for (int i = 2; i <= n; i++) {
r *= i;
}
return r;
}
Then you can invoke that and calculate your sum with a simple loop. Like,
long sum = 0L;
for (int i = 1; i <= 20; i++) {
sum += multiplyTo(i);
}
System.out.println(sum);
I get
2561327494111820313
Using streams:
long s = LongStream.rangeClosed(1, 20)
.map(upper -> LongStream.rangeClosed(1, upper)
.reduce(1, (a, b) -> a * b))
.sum();
System.out.println(s);
Prints 2561327494111820313
I did the same program using Scanner Class
import java.util.*;
class Sum_Factorial
{
public static void main()
{
Scanner in = new Scanner(System.in);
int i; //Denotes Integer
int n; //Denotes Number
int f=1; //Denotes Factorial
int s=0; //Denotes Sum
System.out.println("Enter the value of N : ");
n=in.nextInt();
for(i=1; i<=n; i++)
{
f=f*i;
s=s+f;
}
System.out.println("Sum of the factorial numbers is "+s);
}
}
I have to write a function "alternatingSum(a)" that takes an array of numbers and returns the alternating sum (where the sign alternates from positive to negative or vice versa).
For example:
int[] a = { 5, 3, 8, 4 };
Assert(alternatingSum(a) == 6); // because 5-3+8-4 == 6
So far I have tried to take the array and check to see if the index is odd (not including i=0) then subtract it from the i+1, and if it is even do the same thing except add the two. Am I on the right track with this?
Here is my code:
class foo {
public static int alternatingSum(int[] a){
int sum=0;
for (int i=0;i<a.length;i++){
if (i==0){
sum+=a[0]-a[1];
}
if (i%2 == 0){
sum+=(a[i]+a[i+1]);
}
if (i%2 == 1){
sum+=(a[i]-a[i+1]);
}
}
return sum;
}
public static void testAlternatingSum(){
System.out.println("testing code");
int[] a = { 5, 3, 8, 4 };
assert (alternatingSum(a) == 6); // because 5-3+8-4 == 6
}
public static void main(String[] args){
testAlternatingSum();
}
}
a for loop
I would just keep a boolean flag for even (and toggle it with every loop iteration). If it's an even number, than we're performing addition. But if it's not an even number (it's odd) then we can perform an unary negative operation. That might look something like,
int sum = 0;
boolean even = true;
for (int i = 0; i < a.length; i++) {
sum += even ? a[i] : -a[i];
even = !even
}
return sum;
for-each loop
and you could also use a for-each loop and write it like
boolean even = true;
int sum = 0;
for (int value : a) {
sum += even ? value : -value;
even = !even;
}
return sum;
Easy to read..
int[] alternatingSums(int[] a) {
int sum1 = 0;
int sum2 = 0;
for(int i =0; i < a.length; i++){
if((i % 2) != 1){
sum1 += a[i];
}else{
sum2 += a[i];
}
}
int[] result = {sum1 , sum2};
return result;
}
public int thirdLargest(int[] arr){
int f_l = arr[0];
int s_l = arr[0];
int t_l = arr[0];
for(int i=1;i<arr.length;i++)
{
if (f_l < arr[i]){
t_l = s_l;
s_l = f_l;
f_l = arr[i];
}
else if (s_l < arr[i]){
t_l = s_l;
s_l = arr[i];
}
else if (t_l < arr[i]){
t_l = arr[i];
}
}
return t_l;
}
my code didn't passes some cases,any suggestion?
parameter {24,27,30,31,34,37,40,42}' , passes
parameter {2,-1,-2,-3,-4,-5}' , fails
This is simply cause by the fact that you initialize all values to arr[0]. If all elements are smaller than arr[0] this code won't update the values, even though the second-largest element for example wouldn't be arr[0]. Instead initialize the variables for the third/second/largest value with Integer.MIN_VALUE and start the search with the first element (index = 0) instead of the second.
There is actually a well-known algorithm for this, which is more generic than yours. It is called quick-select and looks like a quick sort with an optimization making it faster (linear time in average) : since we don't need to sort the array, we just recurse on the part of the array containing the index we are looking for (in your case, third item so index 2).
Here is an implementation in Java :
private static final Random rd = new Random();
public static int kthElement(int[] arr, int k) {
return kthElement(arr,k,0,arr.length);
}
private static T kthElement(int[] arr, int k, int min, int max) {
if (min < max - 1) {
int p = pivot(arr,min,max);
return p == k - 1 ? arr[p] :
p < k - 1 ? kthElement(arr,k,p + 1,max) : kthElement(arr,k,min,p);
}
return arr[min];
}
private static int pivot(int[] arr, int min, int max) {
int pivot = min + rd.nextInt(max - min);
swap(arr,pivot,max - 1);
pivot = min;
for (int i=min ; i<max ; i++)
if (arr[i] < arr[max - 1]) swap(arr,i,pivot++);
swap(arr,max - 1,pivot);
return pivot;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Well, as an alternative to your working code, here is a solution that will allow you to find the Nth largest integer in your array using Collections to do the heavy lifting:
import java.util.Arrays;
import java.util.Collections;
public class ArrayNthLargest {
public static int getNthLargest(int[] arrayInput, int n) {
Integer[] sortedArray = new Integer[arrayInput.length];
for (int i = 0; i < arrayInput.length; i++) {
sortedArray[i] = new Integer(arrayInput[i]);
}
Arrays.sort(sortedArray, Collections.reverseOrder());
return (sortedArray[n - 1]);
}
public static void main(String[] args){
int nth = new Integer(0);
int n = new Integer(3);
int[] testArray = {1,2,3,4,5,6,23,44,55,8,1};
nth = getNthLargest(testArray, n);
System.out.printf("The %d sorted array value is %d", n, nth);
}
}
This was actually an interesting question to me to do in O(n) complexity. I hope this solution is order n. I used an ArrayList as a stack (since Stack object won't allow addition of items in specific incidences (I've generalized it).
public int thirdLargest(int[] arr){
public int N_TH = 3; // Assuming this is nth largest you want
public ArrayList<Integer> largest = new ArrayList<Integer>(N_TH);
for(int i = 0;i<N_TH;i++)
largest.add(0); // initialize the ArrayList
for(int i = 0;i<arr.length;i++) {
for(int j=0;j<largest.size();j++){
if(arr[i] >= largest.get(j)) {
// Add the item at the correct index
// Pop the last element
largest.remove(largest.size()-1);
largest.add(j,arr[i]);
break;
}
}
}
return largest.get(N_TH);
}
Let me know if you find any problems with it, I might have mistyped part of trying to put it in OP's method.
EDIT won't work with negative numbers at the moment. You can find the smallest value in arr and initialize largest with that value. Then it'll also with negative numbers
I need to implement a method that returns the alternating sum of all elements with odd indexes minus the sum of all elements with even indexes. The total sum returned should be -1. 1 - 4 + 9 - 16 + 9 = -1.
Here is my code:
public class Arrays
{
public static void main(String[] args){
int [] data = {1 ,4, 9, 16, 9};
oddAndEven(data);
}
public static int[] oddAndEven(int[] data){
int sum = 0;
int sumA = 0;
int index = data.length;
for(int i:data){
if(index % sumA == 1){
sum = sum-i;
}
else{
sum = sum+i;
}
}
System.out.println(sum);
return sum;
}
}
Can someone tell me where I am going wrong please?
This is a class session, so forgive my basic code and errors.
This is how I would do it:
public class test {
public static void main(String[] args) {
int [] data = {1 ,4, 9, 16, 9};
oddAndEven(data);
}
public static void oddAndEven(int[] data) {
int total = 0;
for (int i = 0; i < data.length; i++)
{
if (i%2==0)
total = total + data[i];
else
total = total - data[i];
}
System.out.println(total);
}
I've gotten rid of the return in the method and changed it to void (as you are printing out the result within it, so there is no need to return it.
You don't need the two different sum values, or the length of the array stored.
The total value is used and set to 0. The for loop then goes through the length of the array. The %2 divides the number by 2 and determines the remainder. So for the first loop, it will calculate 0/2 and work out the remainder (obviously 0). As it ==0, the first if statement in the for loop is executed (adding the numbers).
The second time through, it calculates 1/2, which is 0 with 1 remaining - so the else statement is executed and so on.
Additionally, note how I've gotten rid of the braces around the if and else statements. As long as these statements are a single line, the braces aren't needed - taking the out tends to make the program easier to read (in my opinion). Obviously, if more than one line were needed under them, the braces need to be readded.
What about this ?
public class ArrayMeNow {
public static void main(String[] args) {
int [] data = {1 ,4, 9, 16, 9};
int result = oddAndEven(data);
System.out.println(result);
}
private static int oddAndEven(int[] data) {
int multiplier = 1;
int result = 0;
for(int v:data){
result += v * multiplier;
multiplier *= -1;
}
return result;
}
}
public static int oddAndEven(int[] data) {
int sum = 0;
for (int i=0;i<data.length;i++) {
if (i % 2 == 1) {
sum = sum - data[i];
} else {
sum = sum + data[i];
}
}
System.out.println(sum);
return sum;
}
for(int i:data) doesn't change the value of index. And sumA is supposed to be 2.
Change your for-loop to something like:
for (int i = 0; i < data.length; i++)
if (i % 2 == 1)
sum -= data[i];
else
sum += data[i];
You have to return sum which is of type int NOT int[]. Here is another way to do it.
public static int doAlternateAddSubOn(int[] array) {
int sum = 0;
for(int i=0; i<array.length; i++) {
// When index 'i' is Even, the position is Odd
sum = (i%2==0) ? sum+array[i] : sum-array[i];
}
return sum;
}