-3

I want to know how to add a value to an element of an array. This is not a duplicate as i don't want to add a new elemnt or assign an entirely new value but want to edit an existing value in the array. I'd imagine it would look something like this:

textArray[i] = currentElement + variable;

The example above does for some reason not work though

Thanks in advance! :)

3
  • 3
    You can try it yourself, do you face some problem? Commented Nov 11, 2016 at 11:41
  • textArray[i] = textArray[i] + variable; Commented Nov 11, 2016 at 11:42
  • The example I gave does not work. Commented Nov 11, 2016 at 12:25

2 Answers 2

0

You can use the SetValue method as below. textArray.SetValue(1,1); where first parameter is the element and second element is the index.

Sign up to request clarification or add additional context in comments.

1 Comment

but I want to add to an existing element not replace it with another value. For example: if the value of the array at index 1 is 2, I'd want to add 3 to it so that the value of the element is now 5
0

You can use textArray[i] += variable; or the more verbose textArray[i] = textArray[i] + variable;. In the second version note that the right hand side of = is fully evaluated before the assignment is made to textArray[i].

In this sense textArray[i] can be used both to "get" and "set" a value of an element in the array.

Just make sure that i is a valid array index in advance.

3 Comments

Thank you. This does work but is there another way? My profs don't seem to like "+=" method at all.
Well they should! I've put in the verbose alternative.
Alright. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.