Reputation: 455
I am trying to write a simple logic. Based on this logic I should implement my actual logic in project.
so far I have tried the below code.
int[] num = new int[11];
for (int i = 1; i < 6; i++)
{
num[2 * (i - 1) + 1] = i;
}
foreach (var item in num)
{
Console.Write(item + " ");
}
The output is - 0 1 0 2 0 3 0 4 0 5 0
But I want the output as in this 0 1 2 3 0 4 5 6 0 7 8 9 0 format.
What should be write in this code - num[2 * (i - 1) + 1]
Upvotes: 0
Views: 2016
Reputation: 22955
To get the return you want, try this:
var num = new int[12];
for (int i = 1; i < 10; i++) {
num[i + ((i - 1) / 3)] = i;
}
This yields: 0 1 2 3 0 4 5 6 0 7 8 9
.
The logic behind it is that you need to add an extra 1 to the calculated index for every set of 3. The - 1
is to shift the set-of-three to the required position.
To remove the first 0 you have to subtract 1 from the calculated index.
var num = new int[11];
for (int i = 1; i < 10; i++) {
num[i - 1 + ((i - 1) / 3)] = i;
}
This yields: 1 2 3 0 4 5 6 0 7 8 9
Upvotes: 3
Reputation: 1196
int[] num = new int[11];
int j = 0;
for (int i = 1; i < 10; i++)
{
if (i%4 != 0)
{
num[i] = i - j;
}
else
{
j= j + 1;
}
}
foreach (var item in num)
{
Console.Write(item + " ");
}
Console.Read();
Upvotes: 0
Reputation: 1446
I don't quite follow how skipping every 3rd element is going to yield the result you mentioned. But you need to figure out a way to identify each "3rd element" by looking at the index; this is commonly done using the MOD operator (%
for C#, check the internet for "modulo operation") and then checking the result, index % 2 == 0
would be true
for every even value of index
or "every 2nd value" if the index values are continouous.
The rest should be easy to figure out I guess.
Upvotes: 0