Suppose you have an array nums and your task is to increment every number in that array by one.
The first idea that might come to your mind is to write a for loop like this:
int[] nums = {1, 2, 3};
// Increment items:
foreach (int num in nums) {
num++;
}
// Print the array after:
foreach (int num in nums) {
Console.WriteLine(num);
}
but this code doesn't even compile. The compiler reports: Cannot assign to 'num' because it is a 'foreach iteration variable'.
Even if we could change num, no element in nums would change its value. Why is that, since we clearly do num++ for every num in nums?
Let's talk about copies:
Take a look at this code:
int number = 100;
int numberCopy = number;
numberCopy++;
Console.WriteLine(numberCopy); // Output: 101
Console.WriteLine(number); // Output: 100
Although we wrote int numberCopy = number;, this doesn't mean that number and numberCopy are one and the same.
numberCopy is a completely different entity (stored at a different memory address) than number.
What we did is initialize this new numberCopy entity with the value of number. That's why we say the numberCopy is a copy of number.
And so numberCopy++ will only increment numberCopy and won't have any effect on number.
The loop variable is just a copy:
This is what also happens with a foreach loop.
Whenever you write a foreach loop, the loop variable (in our case num) is just a copy of the current item of the array, not the item itself.
This code
int[] nums = {1, 2, 3};
foreach (int num in nums) {
// ...
}
works exactly like this code:
int[] nums = {1, 2, 3};
int num = nums[0];
// ...
num = nums[1];
// ...
num = nums[2];
// ...
Notice that only the variable num is involved, and it has nothing to do with the actual entries of the array nums. C# even forbids assigning to it.
You'll see this better if we change a copy of num and print it on each iteration.
int[] nums = {1, 2, 3};
foreach (int num in nums) {
int copy = num;
copy++;
Console.WriteLine(copy);
}
// Print the array after:
foreach (int num in nums) {
Console.WriteLine(num);
}
The output of this code is:
2
3
4
1
2
3
Looping over the indices:
In order to manipulate the entries of some array we have to loop over the items' indices:
int[] nums = {1, 2, 3};
for (int index = 0; index < nums.Length; index++) {
nums[index]++;
}
This code works exactly like this one:
int[] nums = {1, 2, 3};
int index = 0;
nums[index]++;
index++;
nums[index]++;
index++;
nums[index]++;
In this way we directly manipulate the actual entries of the array (nums[0], nums[1], etc.)
Assignment:
Fix our code such that it correctly increments (adds one to) the even numbers of nums and decrements (subtracts one from) the odd ones.
Free plan: 30 tutor messages. PRO is unlimited.
