+ 1

Why it doesn't work

static void Main(string[] args) { int[] x = new int[100]; for (int k=0 ; k < x.Length; k++) { x[k] = k; } Console.WriteLine(x.Sum()); } In this code I want to find the sum of 1 to 100 But it's not matter to write k = 0 or k = 1 It will find the sum of 1 to 99 What is wrong

1st Jan 2020, 2:56 PM
Sami Jabin
Sami Jabin - avatar
6 Respostas
+ 3
Sami Jabin Because of the condition k < x.Lenght 1) The lenght is 100, so k will always stop at 99, so you could make it to k < x.Lenght + 1, and get the correct result 2) either k starts with 0 or 1, it will be the same result. 1 + 2 + 3 + .. is the same as 0 + 1 + 2 + 3+ ..
1st Jan 2020, 3:08 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 3
x[k] = k+1;
1st Jan 2020, 3:04 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 3
Because your array containing values from 0 to 99 static void Main(string[] args) { int[] x = new int[100]; for (int k=1 ; k <= x.Length; k++) { x[k-1] = k; } Console.WriteLine(x.Sum()); }
1st Jan 2020, 3:06 PM
id001x
id001x - avatar
+ 3
Sami Jabin again, because of the condition k < x.Lenght Since the lenght is 100, then k must be 99. In other words, strictly less than 100. If you want it to go from 1 to 100 included also, just change it to k <= x.Lenght. This will let your loop know that k can also be equal to 100, and you'll get the result you want
1st Jan 2020, 3:12 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 1
Aymane Boukrouh Thank you I get it ❤️
1st Jan 2020, 3:13 PM
Sami Jabin
Sami Jabin - avatar
0
My question is why k=0 and k=1 are same
1st Jan 2020, 3:06 PM
Sami Jabin
Sami Jabin - avatar