-2

So, I know that with a code snippet such as:

int x = 0; //class field variable

private void button1_Click(object sender, EventArgs e)
{
    Label1.Text += (x++)%4 + 1;
}

a sequence of 12341234 is displayed on the form if the button is clicked 8 times.

My goal is to get 43214321 to display.

I'm able to get 32103210 with:

int x = 0; //class field variable

private void button1_Click(object sender, EventArgs e)
{
    Label1.Text += 3-(x++)%4;
}

I'm also able to get 32143214 with:

int x = 1; //class field variable

private void button1_Click(object sender, EventArgs e)
{
    Label1.Text += 4-(x++)%4 + ;
}

What am I doing wrong? And is there a general formula for this?

Note: My x DOES have to be initialized to 1.

FH-Inway
  • 4,432
  • 1
  • 20
  • 37
ewong18
  • 144
  • 1
  • 2
  • 10

3 Answers3

0

Try using this formula: 5-(1+(x+++3)%4)

That is:

Label1.Text += (5-(1+(x+++3)%4)).ToString();
mshsayem
  • 17,557
  • 11
  • 61
  • 69
0

Just change the formula to: Label1.Text += 4-((x-1)++)%4;

Dror Moyal
  • 398
  • 3
  • 11
0

The first line of code that you've written is basically cycling between 3 to 1.

 x=0;      
 Label1.Text += 3-(x++)%4;

x=0 || Output=3.
Label1.Text= 0+3-(0%4)=3
x=1 || Output=2.
Label1.Text= 0+3-(1%4)=2
x=2 || Output=1.
(Dry run as done above)
x=3 || Output=0.
(dry run as done above)
x=4 and the cycle repeats.

You could dry run your second line of code to understand why your answer comes the way it does, but to answer your question in concise:

 int x = 0; //class field variable
 private void button1_Click(object sender, EventArgs e)
     {
            Label1.Text += 4-(x++)%4;
     }
mr_mohapatra
  • 17
  • 1
  • 9