+ 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
6 Respuestas
+ 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+ ..
+ 3
x[k] = k+1;
+ 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());
}
+ 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
+ 1
Aymane Boukrouh
Thank you I get it ❤️
0
My question is why k=0 and k=1 are same