Forum Discussion
c# How to loop and count back in another loop?
Hi,
var Quodown = new List<int>() {9,7,6,9,7,6,4,3,0};
double sumi = 0;
double avg = 0;
for (int i = 8; i < Quodown.Count; i--)
{
sumi += Quodown[i];
Print("sumi: "+ sumi);
//Print(i);
for (int y = i; y < 8; y++)
{
for (int z = Quodown.Count; z > 0; z--)
{
avg = sumi / z;
//Print("avg: "+ avg);
Print(z);
}
}
}
I want to create a movering average of numbers calculated backward.
For exemple, in the first part of the code i calculate the sum of numbers backward 0+3 = 0, 0+3+4= 7 etc.
I am trying to get the moving average of the sum of those numbers like average of 0 = 0 than 3+0 = 3/2 = 1.5
4 +3 +0 = 7/3 = 2.333
etc
but using this loop it is dividing by its last position 8, 7 , 6 when it should be 3,2,1
Any help?
Thank you
- ArabidopsisCopper Contributor
Hi,
Let's take a look at what you've done.
You want to loop from the back of the list to the front, but i<Quoodown Count was used as a constraint for the for statement, so this loop obviously doesn't work properly. I have fixed the first loop for you, and it seems to work properly now.
var Quodown = new List<int>() { 9, 7, 6, 9, 7, 6, 4, 3, 0 }; double sumi = 0; double avg = 0; for (int i = 8; i > 0; i--) { sumi += Quodown[i]; Console.WriteLine("sumi: "+ sumi); for (int y = i; y < 8; y++) { for (int z = Quodown.Count; z > 0; z--) { avg = sumi / z; Console.WriteLine(z); } } }
Wishing you a pleasant programming experience!