C
C#•2y ago
Aksword

How can I modify array values in a for loop ? [Answered]

Hello, I wanted to do a piece of code that replaces half of the words inserted by the user (in a random order) into "train", for example. So I did this : Random numbergen = new Random(); string answ = Console.ReadLine(); string[] words = answ.Split(' '); int length = words.Length; for (int i = 1; i < length/2; i ++) { determ : string target = words[numbergen.Next(0, length - 1)]; string replacer = "train"; if (target == replacer) { goto determ; } else { target = replacer; } } for (int i = 0; i<= length - 1; i ++) { Console.Write(words[i] + " "); } But when I check what the console print, I see that the words aren't replaced, and then I discovered that when you modify an array in a for loop, it's only modified IN the for loop. So does anyone has a clue to change arrays INSIDE of a for loop and be able to access them OUTSIDE of the loop ? (Thx 😄 )
3 Replies
ero
ero•2y ago
You will need to change the value in the array. You're not doing that You're taking the value from the array, and changing that copy Think about how you would change the value in the actual array
Auger
Auger•2y ago
You need to store the result of numbergen.Next(0, length - 1) Because that's the index for the element that you update the value for
Aksword
Aksword•2y ago
Yes I was doing it when I recieved you message, I finaly figured out what sait @Ero Thanks to you two (and ero it's good to not directly give the answer, thanks) !
Want results from more Discord servers?
Add your server
More Posts