Java One Dimensional (1D) Arrays: Modifying Elements
Modify 1D Array Elements
So far we have learnt how to create and access array elements. Now let’s look at ways to manipulate elements.
Reassign a new value to an element
We know how to access an array element using the following syntax:
arrayName[x];
We can use this principle to assign a new value to any element using the assignment operator and the new value. Let’s change the last grade in our array, currently it is 55 and this student did very well on the latest assignment which increased the grade to 70.
To do this we will first need to access the appropriate element:
studentGrades[4]
Then we simply assign a new value to that element:
studentGrades[4] = 70;
Here the full program:
// The array: int [] studentGrades = {82, 76, 65, 92, 55}; // Change the value of index 4: studentGrades[4] = 70; // Output the new value of index 4: System.out.println(studentGrades[4]);
The output confirms that the last element value was changed from 55 to 70:
run: 70 BUILD SUCCESSFUL (total time: 0 seconds)
Perform a mathematical calculation on an array element
Since our studentGrades array is an integer array we can modify each element as if they are integer values using mathematical operators like multiplication or subtraction. So if we wanted to add a bonus 5 marks to the first student we could say:
// The array: int [] studentGrades = {82, 76, 65, 92, 55}; // Add 5 to the value of index 0: studentGrades[0] += 5; // Output the new value of index 0: System.out.println(studentGrades[0]);
Here we are adding 5 to the existing value of index 0 in the array and the output confirms that change:
run: 87 BUILD SUCCESSFUL (total time: 0 seconds)
Multiplication, division, subtraction are all easily applied using similar syntax:
int [] studentGrades = {82, 76, 65, 92, 55}; // Modify elements: studentGrades[1] *= 2; studentGrades[2] /= 2; studentGrades[3] -= 40; // Output the new element values: System.out.println(studentGrades[1]); System.out.println(studentGrades[2]); System.out.println(studentGrades[3]);
The output shows the element values have been altered but are they what you expected:
run: 152 32 52 BUILD SUCCESSFUL (total time: 0 seconds)
Take studentGrades[1] *= 2, that is equivalent to 76*2 = 152. That checks out!
What about studentGrades[2] /= 2, that is equivalent to 65/2 = 32.5. Our program output and even 32, that means there is a 0.5 difference. Can you think of why this might be?
The studentGrades array is an integer array, and this data type does not allow fractional parts so the additional 0.5 is simply lost.
For arrays of other data types similar modifications will be possible but data type rules must be observed. For example you cannot apply mathematical operations on a String array but you can concatenate or replace characters.
Exercise
In this exercise you will need to work out how to reduce all student grades by 10% and update the array with these changes. The grade reductions must be as accurate as possible by rounding them to the nearest integer. For example to reduce the first grade of 82 by 10% you will first need to find 10% of 82 and then subtract that from 82. The result of that calculation is 73.8 but since the array is an integer array you will need to ensure that the nearest whole number, 74, is inserted into the array, and not 73. Sounds only fair to the student, right?
You will need to recall what you have learnt about data type conversion, Math methods, loops and more to work out the most efficient code to solve this problem. Remember, getting it to work is a great start, but refining your code to produce elegant and efficient code is the goal.
As a reminder, here is your starting point, the studentGrades array:
int [] studentGrades = {82, 76, 65, 92, 55};
My solution follows but please do not take a peek until you have made a serious effort to solve the problem yourself, you will learn a lot by trying.
The first thing I like to do when faced with a problem like this is to make a list of the project requirements – what is the desired outcome and what do I need to ensure happens along the way to arrive at that outcome. From that exercise I will have a clear view on what my program needs to do and can construct an algorithm that I will use to write my code.
So, my program needs to subtract 10% from the current values of each element. It then needs to replace each value with the newly reduce value. That will modify the entire array with with new data.
Care needs to be taken to ensure any fractional parts are not discarded:
- if a fractional part is 5 or more the value should be rounded up
- if a fractional part is less than 5 the value should be rounded down
So what would my algorithm look like?
- Start
- Construct the student grades array with initial values
- Begin a for loop that will repeat for as many time as there are elements in the array
- For each element, calculate 10% of its value, rounding as required
- For each element, subtract the calculated 10% from the element value, ensuring the result is an integer
- Assign the reduced value to the appropriate element in the array
- Repeat the loop until all elements have been updated
- End
From this I can start to craft and refine my code, this is where I ended up after a number of iterations:
// The array: int [] studentGrades = {82, 76, 65, 92, 55}; // Decrease each element by 10%: for (int i = 0; i < studentGrades.length; i++) { studentGrades[i] = (int) (studentGrades[i]-(Math.round(studentGrades[i] *0.1))); System.out.println(studentGrades[i]); }
My output is what I expected, each element value is reduced by 10% and the new values are all rounded to the nearest whole number for fairness:
run: 74 68 58 83 49 BUILD SUCCESSFUL (total time: 0 seconds)
How did you get on? Post your comments below.
Array are one of the critical building blocks of many programming languages, including Java. Without arrays our programs would be less efficient, cumbersome, complex and difficult to debug. Arrays are very important, and as students of Java we all need to become experts in the use of arrays if we are to aspire to be good programmers.