Find the first occurrence of an odd and count them - java

import java.util.*;
public class FirstOddOccurrence {
public static void main(String[] args) {
int[] x = {2, 4, 6, 7, 4, 3, 2, 7, 6, 7, 7};
int i;
display(x);
System.out.printf("# Occurrences of first odd = %3d\n", firstOddCount(x));
}
private static void display(int[] x) {
int i;
System.out.print("Array: ");
for (i = 0; i < x.length; i++) {
if (i < x.length - 1)
System.out.printf("%3d, ", x[i]);
else
System.out.printf("%3d\n", x[i]);
}
}
public static int odd(int[] x) {
int i;
int y;
for (i = 0; i < x.length; i++) {
y = x[i] % 2;
if (y == 1) {
return x[i];
} else {
return 0;
}
}
return x[i];
}
public static int firstOddCount(int x[]) {
int i;
int c = 0;
for (i = 0; i < x.length; i++) {
if (x[i] == odd(x))
c++;
}
return c;
}
}
I'm trying to find the first occurrence of an odd number in the array that has been provided. What is wrong with my program? I can't seem to get the program to count the first odd occurrences.

Your code here:
if (y == 1) {
return x[i];
} else {
return 0;
}
does not work - if a tested number is even, you immediately return 0. Instead you want to skip these even numbers and wait until an odd number comes up. In the end, if you don't find any odd number, you return 0. Here is the corrected version of odd():
int i;
int y;
for (i = 0; i < x.length; i++) {
y = x[i] % 2;
if (y == 1) {
return x[i];
}
}
return 0;

Andr's solution fixes your issue; odd(x) will return 0 if x[0] is even, and x[0] if it is odd.
You could also improve firstOddCount like so: odd(x) will always return the same value, so only calculate it once.
public static int firstOddCount(int x[]) {
int firstOdd = odd(x);
int c=0;
for(int i=0; i < x.length; i++) {
if (x[i]==firstOdd)
c++;
}
return c;
}

Your particular problem is that you return 0 if you find an even number. That means that the list {2, 4, 6, 8, 1} will give you 0, rather than 1, as the first odd number.
What you should do is ignore leading even numbers and continue to process the list.
However, the way you've organised your program, you're processing the first all-even part of the list twice, once in odd() to find the first odd number, then again in firstOddCount() to count how many of that number there are - that's totally unnecessary.
Once you find the first odd number, I think you can be reasonably certain that number (or any other odd number for that matter) does not exist in the space you've already searched. Otherwise it would have been the first odd number. Hence it makes little sense to go back and look at that initial part of the list again.
A way in which you can easily just process the list once is as follows:
public static int firstOddCount (int numbers[]) {
// Find first odd number or end of list.
int idx = 0, len = numbers.length;
while ((idx < len) && ((numbers[idx] % 2) == 0)
idx++;
// If at end of list, everything is even => count(first(odd)) is 0.
if (idx == len)
return 0;
// Otherwise, start counting from current position.
int count = 1, oddnum = numbers[idx];
while (++idx < len)
if (numbers[idx] == oddnum)
count++;
return count;
}

If you are trying to get one element from group you should use 'break' when your condition matched first time else it will give all...

Related

How would these methods be setup to increment and decrement the last number in an array by 1? Java

For this project I am creating arrays, each with 50 elements, each element with a value between 0 and 9, and using those arrays called "BigIntegers" in addition, subtraction, multiplication and division. There are a few smaller methods called increment and decrement that I am having trouble figuring out. This is the code that I have done...
public class BigInteger {
int[] BigInteger = new int[50];
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//x BigInteger(): creates a BigInteger of all 0's x
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
public BigInteger() {
for (int i = 0; i < 50; i++) {
BigInteger[i] = 0;
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//x BigInteger(n): creates a BigInteger the size of n x
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
public BigInteger(int n) {
for (int i = 49; i > 0; i--) {
BigInteger[i] = n%10;
n = n/10;
}
BigInteger[0] = n;
}
public int[] getBigInteger() {
return BigInteger;
}
public BigInteger(BigInteger n) {
for(int i = 0; i < 50; i++) {
BigInteger[i] = n.getBigInteger()[i];
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//x print(): prints out each element of the BigInteger array x
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
public void print() {
int index = 0;
for (int i = 0; i < BigInteger.length; i++) {
if (BigInteger[i] == 0) { index = 0; }
else { index = i; break; }
}
for(int i = index; i < BigInteger.length; i++) {
System.out.print(BigInteger[i] + " ");
}
}
public void decrement() {
int last = BigInteger.length;
for(int i = last; i < 50; i++) {
if (i == 0) { }
else last = BigInteger[last] - 1;
}
}
public static void main(String args[]) {
BigInteger big = new BigInteger(50);
BigInteger big2 = new BigInteger();
BigInteger big3 = new BigInteger(602345812);
}
The functions of these methods are:
• void increment( ) --- increase the value of the invoking object by 1
• void decrement( ) --- decrement the value of the invoking object by 1
I've spent numerous hours trying to figure out these, what seem to be, easy methods. Any help or advice?
Thanks I.
If I understand your question well, you should try this (with remarks from #Andy Turner and #Yang Li) as a starting point:
public void increment() {
for (int i = BigInteger.length - 1; i; i--)
if (BigInteger[i] < 9) {
BigInteger[i]++;
for (int j = i + 1; j < BigInteger.length; j++)
BigInteger[j] = 0;
break;
}
else if (i == 0)
// cannot increment 9
}
public void decrement() {
for (int i = BigInteger.length - 1; i; i--)
if (BigInteger[i] > 0) {
BigInteger[i]--;
for (int j = i + 1; j < BigInteger.length; j++)
BigInteger[j] = 9;
break;
}
else if (i == 0)
// cannot decrement 0
}
This will increment / decrement the last int element of your BigInteger array, where BigInteger.length - 1 is the index of the last element in your array.
There are already some answers by this post, but you need to be careful because some of these answers don't deal with overflow. If the last digit is 9 and you increment it by 1, it will overflow, if the last digit is 0 and you subtract, it will also be problematic.
You should also consider the case where all the digits in your BigInteger array are '9'. In this case if you increment it by one, no more rooms would be allowed in your array. Same thing may happen if all the digits in BigInteger are '0' and you want to subtract it by 1. For those cases you should probably throw an error.
Update
I have implemented the recursive way to increment the big integer.
Please note that I have handled the case where all digits in BigInteger are '9'. You should check if this input is expected, otherwise you should remove this check.
public void increment() {
increment(BigInteger.length-1);
}
private void increment(int index) {
if (index < 0) {
throw new RuntimeException("BigInteger maximum capacity reached!");
}
if (BigInteger[index] < 9) {
BigInteger[index]++;
} else {
BigInteger[index] = 0;
increment(--index);
}
}
Basically this will keep looking for leading digits until it is less than 9 and then increment that digit, during the process it will set any '9' it encounters to '0'.
I didn't implement the "decrease" method because I think it would be good that you can come up with your own solution.

How to calculate the alternating sum of two arrays in Java?

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;
}

issues with codingbat maxMirror exercise

So basically, I've been going through these codingBat problems, and when I get really stuck, I usually check out the solution and trace the logic and that has helped me not get stuck on later problems which used similar ideas.
This max mirror problem is not like the others for me personally; I have no idea how to actually write the code to solve it, even forming the algorithm is kind of tricky for me
We'll say that a "mirror" section in an array is a group of contiguous elements such that somewhere in the array, the same group appears in reverse order. For example, the largest mirror section in {1, 2, 3, 8, 9, 3, 2, 1} is length 3 (the {1, 2, 3} part). Return the size of the largest mirror section found in the given array.
maxMirror({1, 2, 3, 8, 9, 3, 2, 1}) → 3
maxMirror({1, 2, 1, 4}) → 3
maxMirror({7, 1, 2, 9, 7, 2, 1}) → 2
Now, in terms of the algorithm, I sort of want to say something like, if we start by checking if the whole array is a mirror and then decrease the checked area size by 1 if it's not. But in terms of the pseudocode and the real code I have no idea.
My go to solution in cases like this where what your code should be doing is always doing it manually, then figuring out the essence of how it is that I am tackling the solution.
For this problem I found myself looking at possible subsets of the original array, then looking backwards through the original array to see if I can find that same subset again.
Next, I translated that into pseudocode,
for each segment in nums
check if nums contains segment backwards
Repeated, but this time with more implementation details worked out.
for each segment in nums, starting with the largest
reverse the segment
check if nums contains reversed segment
if it does, return the size of that segment
Next, find some likely candidates for methods in the pseudocode and write them. I chose to do this for "reverse" and "contains":
private int[] reverse(int[] nums) {
int[] rtn = new int[nums.length];
for (int pos = 0; pos < nums.length; pos++) {
rtn[nums.length - pos - 1] = nums[pos];
}
return rtn;
}
private boolean contains(int[] nums, int[] segment) {
for (int i = 0; i <= nums.length - segment.length; i++) {
boolean matches = true;
for (int j = 0; j < segment.length; j++) {
if (nums[i + j] != segment[j]) {
matches = false;
break;
}
}
if (matches) return true;
}
return false;
}
Finally, implement the rest:
public int maxMirror(int[] nums) {
for (int window = nums.length; window > 0; window--) {
for (int pos = 0; pos <= nums.length - window; pos++) {
int[] segment = new int[window];
for (int innerpos = 0; innerpos < window; innerpos++) {
segment[innerpos] = nums[pos + innerpos];
}
segment = reverse(segment);
if (contains(nums, segment)) {
return window;
}
}
}
return 0;
}
My irrelevant two cents....
public int maxMirror(int[] nums) {
// maximum mirror length found so far
int maxlen= 0;
// iterate through all possible mirror start indexes
for (int front = 0; front < nums.length; front++) {
// iterate through all possible mirror end indexes
for (int back = nums.length - 1; back >= front; back--) {
// this inner for-loop determines the mirror length given a fixed
// start and end index
int matchlen = 0;
Boolean match = (nums[front] == nums[back]);
// while there is a match
// 1. increment matchlen
// 2. keep on checking the proceeding indexes
while (match) {
matchlen++;
int front_index = front + matchlen;
int back_index = back - matchlen;
// A match requires
// 1. Thee indexes are in bounds
// 2. The values in num at the specified indexes are equal
match =
(front_index < nums.length) &&
(back_index >= 0) &&
(nums[front_index] == nums[back_index]);
}
// Replace the max mirror length with the new max if needed
if (matchlen > maxlen) maxlen = matchlen;
}
}
return maxlen;
}
Alternative solution designed to confuse you
public int maxMirror(int[] nums) {
return maxlen_all_f(nums, 0);
}
int maxlen_all_f(int [] nums, int f) {
return (f >= nums.length)
? 0
: max(
maxlen_for_start_f(nums, f, nums.length - 1),
maxlen_all_f(nums, f + 1)
);
}
int max(int a, int b){
return (a > b)
? a
: b;
}
int maxlen_for_start_f(int [] nums, int f, int b) {
return (b < f)
? 0
: max(
matchlen_f(nums, f, b),
maxlen_for_start_f(nums, f, b - 1)
);
}
int matchlen_f(int[] nums, int f, int b) {
return match_f(nums, f, b)
? 1 + matchlen_f(nums, f + 1, b - 1)
: 0;
}
Boolean match_f(int [] nums, int a, int b) {
return (a < nums.length && b >= 0) && (nums[a] == nums[b]);
}
The solution is simple rather than making it complex:
public static int maxMirror(int[] nums) {
final int len=nums.length;
int max=0;
if(len==0)
return max;
for(int i=0;i<len;i++)
{
int counter=0;
for(int j=(len-1);j>i;j--)
{
if(nums[i+counter]!=nums[j])
{
break;
}
counter++;
}
max=Math.max(max, counter);
}
if(max==1)
max=0;
return max;
}
This is definitely not the best solution in terms of performance. Any further improvements are invited.
public int maxMirror(int[] nums) {
int maxMirror=0;
for(int i=0;i<nums.length;i++)
{
int mirror=0;
int index=lastIndexOf(nums,nums[i]);
if(index!=-1){
mirror++;
for(int j=i+1;j<nums.length;j++)
{
if(index>=0&&existsInReverse(nums,index,nums[j]))
{
mirror++;
index--;
continue;
}
else
break;
}
if(mirror>maxMirror)
maxMirror=mirror;
}
}
return maxMirror;
}
int lastIndexOf(int[] nums,int num){
for(int i=nums.length-1;i>=0;i--)
{
if(nums[i]==num)
return i;
}
return -1;
}
boolean existsInReverse(int nums[],int startIndex,int num){
if(startIndex!=0&&(nums[startIndex-1]==num))
return true;
return false;
}
Here is my answer , Hope the comments explain it well :)
public int maxMirror(int[] nums) {
int max = 0;
// our largest mirror section found stored in max
//iterating array
for(int i=0;i<nums.length;i++){
int iterator = i; // iterator pointing at one element of array
int counter = 0;//counter to count the mirror elements
//Looping through for the iterator element
for(int j=nums.length-1;j>=i;j--){
//found match i.e mirror element
if(nums[iterator] == nums[j]){
iterator++; // match them until the match ends
counter++; // counting the matched ones
}
else{
//matching ended
if(counter >= max){//checking if previous count was lower than we got now
max = counter; // store the count of matched elements
}
counter = 0; // reset the counter
iterator = i; // reset the iterator for matching again
}
}
if(counter >= max){//checking if previous count was lower than we got now
max = counter;// store the count of matched elements at end of iteration
}
}
return max;//return count
}

Implementing a binary insertion sort using binary search in Java

I'm having trouble combining these two algorithms together. I've been asked to modify Binary Search to return the index that an element should be inserted into an array. I've been then asked to implement a Binary Insertion Sort that uses my Binary Search to sort an array of randomly generated ints.
My Binary Search works the way it's supposed to, returning the correct index whenever I test it alone. I wrote out Binary Insertion Sort to get a feel for how it works, and got that to work as well. As soon as I combine the two together, it breaks. I know I'm implementing them incorrectly together, but I'm not sure where my problem lays.
Here's what I've got:
public class Assignment3
{
public static void main(String[] args)
{
int[] binary = { 1, 7, 4, 9, 10, 2, 6, 12, 3, 8, 5 };
ModifiedBinaryInsertionSort(binary);
}
static int ModifiedBinarySearch(int[] theArray, int theElement)
{
int leftIndex = 0;
int rightIndex = theArray.length - 1;
int middleIndex = 0;
while(leftIndex <= rightIndex)
{
middleIndex = (leftIndex + rightIndex) / 2;
if (theElement == theArray[middleIndex])
return middleIndex;
else if (theElement < theArray[middleIndex])
rightIndex = middleIndex - 1;
else
leftIndex = middleIndex + 1;
}
return middleIndex - 1;
}
static void ModifiedBinaryInsertionSort(int[] theArray)
{
int i = 0;
int[] returnArray = new int[theArray.length + 1];
for(i = 0; i < theArray.length; i++)
{
returnArray[ModifiedBinarySearch(theArray, theArray[i])] = theArray[i];
}
for(i = 0; i < theArray.length; i++)
{
System.out.print(returnArray[i] + " ");
}
}
}
The return value I get for this when I run it is 1 0 0 0 0 2 0 0 3 5 12. Any suggestions?
UPDATE: updated ModifiedBinaryInsertionSort
static void ModifiedBinaryInsertionSort(int[] theArray)
{
int index = 0;
int element = 0;
int[] returnArray = new int[theArray.length];
for (int i = 1; i < theArray.lenght - 1; i++)
{
element = theArray[i];
index = ModifiedBinarySearch(theArray, 0, i, element);
returnArray[i] = element;
while (index >= 0 && theArray[index] > element)
{
theArray[index + 1] = theArray[index];
index = index - 1;
}
returnArray[index + 1] = element;
}
}
Here is my method to sort an array of integers using binary search.
It modifies the array that is passed as argument.
public static void binaryInsertionSort(int[] a) {
if (a.length < 2)
return;
for (int i = 1; i < a.length; i++) {
int lowIndex = 0;
int highIndex = i;
int b = a[i];
//while loop for binary search
while(lowIndex < highIndex) {
int middle = lowIndex + (highIndex - lowIndex)/2; //avoid int overflow
if (b >= a[middle]) {
lowIndex = middle+1;
}
else {
highIndex = middle;
}
}
//replace elements of array
System.arraycopy(a, lowIndex, a, lowIndex+1, i-lowIndex);
a[lowIndex] = b;
}
}
How an insertion sort works is, it creates a new empty array B and, for each element in the unsorted array A, it binary searches into the section of B that has been built so far (From left to right), shifts all elements to the right of the location in B it choose one right and inserts the element in. So you are building up an at-all-times sorted array in B until it is the full size of B and contains everything in A.
Two things:
One, the binary search should be able to take an int startOfArray and an int endOfArray, and it will only binary search between those two points. This allows you to make it consider only the part of array B that is actually the sorted array.
Two, before inserting, you must move all elements one to the right before inserting into the gap you've made.
I realize this is old, but the answer to the question is that, perhaps a little unintuitively, "Middleindex - 1" will not be your insertion index in all cases.
If you run through a few cases on paper the problem should become apparent.
I have an extension method that solves this problem. To apply it to your situation, you would iterate through the existing list, inserting into an empty starting list.
public static void BinaryInsert<TItem, TKey>(this IList<TItem> list, TItem item, Func<TItem, TKey> sortfFunc)
where TKey : IComparable
{
if (list == null)
throw new ArgumentNullException("list");
int min = 0;
int max = list.Count - 1;
int index = 0;
TKey insertKey = sortfFunc(item);
while (min <= max)
{
index = (max + min) >> 1;
TItem value = list[index];
TKey compKey = sortfFunc(value);
int result = compKey.CompareTo(insertKey);
if (result == 0)
break;
if (result > 0)
max = index - 1;
else
min = index + 1;
}
if (index <= 0)
index = 0;
else if (index >= list.Count)
index = list.Count;
else
if (sortfFunc(list[index]).CompareTo(insertKey) < 0)
++index;
list.Insert(index, item);
}
Dude, I think you have some serious problem with your code. Unfortunately, you are missing the fruit (logic) of this algorithm. Your divine goal here is to get the index first, insertion is a cake walk, but index needs some sweat. Please don't see this algorithm unless you gave your best and desperate for it. Never give up, you already know the logic, your goal is to find it in you. Please let me know for any mistakes, discrepancies etc. Happy coding!!
public class Insertion {
private int[] a;
int n;
int c;
public Insertion()
{
a = new int[10];
n=0;
}
int find(int key)
{
int lowerbound = 0;
int upperbound = n-1;
while(true)
{
c = (lowerbound + upperbound)/2;
if(n==0)
return 0;
if(lowerbound>=upperbound)
{
if(a[c]<key)
return c++;
else
return c;
}
if(a[c]>key && a[c-1]<key)
return c;
else if (a[c]<key && a[c+1]>key)
return c++;
else
{
if(a[c]>key)
upperbound = c-1;
else
lowerbound = c+1;
}
}
}
void insert(int key)
{
find(key);
for(int k=n;k>c;k--)
{
a[k]=a[k-1];
}
a[c]=key;
n++;
}
void display()
{
for(int i=0;i<10;i++)
{
System.out.println(a[i]);
}
}
public static void main(String[] args)
{
Insertion i=new Insertion();
i.insert(56);
i.insert(1);
i.insert(78);
i.insert(3);
i.insert(4);
i.insert(200);
i.insert(6);
i.insert(7);
i.insert(1000);
i.insert(9);
i.display();
}
}

Cycle through an int array and the use of modulo within it

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;
}

Categories

Resources