Reputation: 825
Hi, I have an array : int [] num = new int[6]{1,2,2,1,1,2};
I want to multiply the value at element 0 with every other value, I then want to multiply the value at element 1 with the values at elements 2 through to the last element. Then multiply the value at element 2 with the values from 3 through to the end, and so on until I have iterated through the whole array.
My efforts thus far seem clumsy and verbose, so I was wondering if anyone could show me an elegant way of achieving my aim.
Many thanks.
Upvotes: 3
Views: 6984
Reputation: 3439
int[] num = new int[6] { 1, 2, 2, 1, 1, 2 };
int i = 0;
while (i < num.Length)
{
for (int j = i; j < num.Length;j++)
{
if((j+1)<num.Length)
num[i] = num[i] + num[j + 1];
}
Console.WriteLine(num[i]);
i++;
}
Upvotes: 0
Reputation: 46555
You can go through the array backwards and do it in one pass and not repeat operations.
for (int i = num.Length - 2; i >= 0; i--)
{
num[i] *= num[i + 1];
}
Gives 8,8,4,2,2,2
Upvotes: 8
Reputation: 120380
Enumerable.Range(0,num.Length)
.Select(i => num.Skip(i).Aggregate(1, (a, b) => a * b))
Gives a sequence 8, 8, 4, 2, 2, 2. Is this what you meant?
Upvotes: 2
Reputation: 33139
This should do the job:
for (int i = 0; i < num.Length; i++)
{
// Multiply element i
for (int j = i+1; j < num.Length; j++)
{
num[i] *= num[j];
}
}
Upvotes: 1