Click here to Skip to main content
15,894,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to swap numbers of four digits number that enter users. And I wrote that codes
C#
private void btnSwap_Click(object sender, EventArgs e)
       {
           int number, digit1, digit2, digit3, digit4;
           number = Convert.ToInt32(txtNumber.Text);
           digit1 = number % 10;
           digit2 = (number / 10) % 10;
           digit3 = (number / 100) % 10;
           digit4 = (number / 1000) % 10;
           digit4 = digit1;
           digit1 = digit3;
           digit3 = digit2;
           digit2 = digit1;
           lbReserved.Text = number.ToString();

       }

But that codes return same number ? How to do it?
Posted
Comments
/\jmot 5-Feb-15 2:56am    
what output you want??
1234 to 4321????
or what??
goksurahsan 5-Feb-15 2:57am    
Yes, I want to that you showed.
Tomas Takac 5-Feb-15 2:58am    
It's text so why to convert it to integer? It only makes your task harder.
goksurahsan 5-Feb-15 2:59am    
I want to write number to textbox. Therefor I wrote that

refer : Best way to reverse a string[^]
C#
lbReserved.Text = new String(Array.Reverse(txtNumber.Text.ToCharArray()));
 
Share this answer
 
v2
Of course,the best answer is DamithSL's (fived btw). But I think you should understand what you are doing in your code.

The first part is OK:

C#
int number, digit1, digit2, digit3, digit4;
number = Convert.ToInt32(txtNumber.Text);
digit1 = number % 10;
digit2 = (number / 10) % 10;
digit3 = (number / 100) % 10;
digit4 = (number / 1000) % 10;


If you just had debugged this, you'd see that after this,you already have the numbers in reverse order (if number is 1234, you've got after this 4 in digit1,3 in digit 2...)
So simply adding:
C#
lblReserved.Text=string.Concat(digit1,digit2,digit3,digit4);

would have given you the right answer.

Instead of that, you start assigning the values in no specific order, and you must understand that after you give a variable a value,the previous one is lost. It's a nonsense.

Finally, you give the lbReserved the original value (lbReserved.Text=number.ToString()), so of course what you see is the original value.

Sorry for the long answer,but seeing the code it seems you are a newbie and have some wrong concepts that deserved an explanation. :)
 
Share this answer
 
Comments
goksurahsan 5-Feb-15 3:20am    
thank you
Because you are using, in assignments, already changed values.
The correct logic to swap two numbers, say d1 and d2 is:
C#
int tmp;
tmp = d1;
d1 = d2;
d2 = tmp; // this assigns the old (correct) value of d1 to d2
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900