I have an sorted array having values like below: I need to calculate total as below:
Scenario 1 - Array values 12,15,17
12+15 = 27
27+17 = 44
44+27 = 71
Total = 71
Scenario 2 Array values 12,15,17,19
12+15 = 27
27+17 = 44
44+19 = 63
27+44+63 = 134
Total = 134
Scenario 3 Array values 12,15,17,19,23
12+15 = 27
27+17 = 44
44+19 = 63
63+23 = 86
27+44+63+86 = 220
Total = 220
Scenario 4 till N Array values 12,15,17,19,23.....N
I have to bring the above logic to C# code
I have written as below :
int[] myNumbers = new int[] { 100,250,1000};
Array.Sort(myNumbers);
int sum = 0;
int temp = 0;
foreach (int y in myNumbers)
{
sum = sum + y;
}
for(int i=0;i<myNumbers.Length-1;i++)
{
temp = temp + myNumbers[i];
}
sum = sum + temp;
Console.Write(sum);
The above code works fine for array values 100,250,1000
But it fails for any other array values
Need help!
See Question&Answers more detail:os