Contents

Performing different operations on the length of an array (with.Java)

   Nov 2, 2023     2 min read

In this article, we learned about different operations based on the length of an array.

We’ll do this by solving coding test problems, reflecting on the problems we solved, and exploring other ways to solve them.

Let’s start with the problem

Problem

An array of integers arr and an integer n are given as parameters.

Write a solution function that returns an array of all even-indexed positions in arr plus n if the length of arr is odd, or an array of all odd-indexed positions in arr plus n if the length of arr is even.

Example input and output
arrnresult
[49, 12, 100, 276, 33]27[76, 12, 127, 276, 60]
[444, 555, 666, 777]100[444, 655, 666, 877]

My solution to the problem

class Solution {
    public int[] solution(int[] arr, int n) {
        if(arr.length % 2 != 0){
            for(int i = 0; i < arr.length; i++){
                if(i % 2 == 0){
                    arr[i] += n;
                }
            }
        } else {
            for(int i = 0; i < arr.length; i++){
                if(i % 2 != 0){
                    arr[i] += n;
                }
            }
        }
        } return arr;
    }
}
Solution Explained

First, check whether the length of the array arr is odd or even.

Check if the length is odd with the condition arr.length % 2 != 0, and if it is even, execute the else block.

If the length is odd:

Use a for loop to traverse the array arr. The i variable represents the index in the array.

The if(i % 2 == 0) condition checks to see if the current index i is an even position. If it is an even position, it adds the value of n to that element.

If the length is even:

In this case, we enter the else block, which traverses the array arr.

The if(i % 2 != 0) condition checks to see if the current index i is in an odd position. If it is an odd position, it adds the value of n to that element.

Return the changed array arr.

This function performs a simple operation that adds n to the elements in odd or even positions of the given array arr.

The distinction between elements in odd and even positions is based on whether the array is odd or even in length, and the operation is performed accordingly.