viktor80 viktor80 - 3 months ago 7
C# Question

incremented and decremented loop with starting number condition

Can you help me figure out, how to create upstream and downstream number in fixed diapason, when the number reaches 10 go in minus, when the number reaches 0 go to plus until reaches 10 again, in infinite or limited loop, but I also want get condition on starting number for example random value in same range:

Random rand = new Random();
int randrange = rand.Next(0, 11);


and if random starting number is less then 5 start from plus, else, minus. For example if random starting number is 7, go to minus until 0, then go to plus until 10, then again minus etc.,:

7
6
5
4
3
2
1
0
1
2
3
4
5
6
7
8
9
10
9
8
7
6
5
4
3
2
1
0
1
2
.
.
.


if less, with plus for example from 4:

4
5
6
7
8
9
10
9
8
7
6
5
4
3
2
1
0
1
2
.
.
.

Answer

Somthing like this?

void Main()
{
    var rand = new Random();
    var start = rand.Next(0,11);
    var incrementor = start > 5 ? -1 : 1;
    var currentValue = start;

    for (var i = 0; i < 100; i++)
    {
        if (currentValue == 10) incrementor=-1;
        if (currentValue == 0) incrementor=1;

        currentValue+=incrementor;
        Console.WriteLine(currentValue);
    }   
}
Comments