✅ I can't understand
int[] array1 = new int[4];
array1[0] = 1;
array1[1] = 4;
array1[2] = 8;
array1[3] = 3;
int[] array2 = new int[4];
array2[0] = 4;
array2[1] = 12;
array2[2] = 7;
array2[3] = 4;
int[] array3 = new int[3];
for (int i = 0; i < array1.Length; i++)
{
array3[i] = array1[i] + array2[array2.Length - 1 - i];
Console.WriteLine(array3[i]);
}
i was given assignment and this for function is basically the answer that i couldnt do and made chatgpt make it, can someone explain to me how does the code inside for function work? (i was assigned to make for function sum up the first and last, second and third, etc element of array1 and array2)
24 Replies
what's the first part that confuses you?
array2[array2.Length - 1 - i];
what happens here
try to break it down, what would
array2.Length - 1
be?it would be array2[2] in this case?
array2.Length is 4
int[] array2 = new int[4];
but in general, array.Length - 1
will give you the index of the last element in the arrayi thought it was giving you the element before the last one
look at this part
there are 4 elements, but the index only goes up to 3
because the first one is 0
I do understand it now, because I thought that array2.Length would be 3 so 3-1 was getting me confused
thanks sir
If you have no further questions, please use /close to mark the forum thread as answered
is there any reason why this code does not work?
it just does not work
it just gives me this output which does not make sense, its like the output of the code i typed before
@Jimmacle
you have compilation errors in your code, which means the code that's running isn't the code you have
it looks like you tried to add another file to your project with a different program in it, which doesn't work
how can i fix it
you should only have Program.cs
i started whole new paper and now i get this error
Have you Googled that error ?
you created the project incorrectly, the error says what you did wrong
damn i finally fixed everything
it took me like 20 minutes to fix such a simple code that i had errors not connected to the code at all
thanks jimacle
https://learn.microsoft.com/en-us/shows/csharp-fundamentals-for-absolute-beginners/ <--- should check this out
C# Fundamentals for Absolute Beginners
Learn C# programming from an expert in the industry. Get the tools, see how to write code, debug features, explore customizations, and more. For newer videos head over to dot.net/videos
alright
thanks
If you're taking things straight from ChatGPT I really recommend trying to understand every line that it's spitting out.
You can ask ChatGPT to explain everything line by line
And if you still don't understand it try to reference C# documents
okay thanks for the tips