Computer Science, asked by SIRGENE, 2 months ago

Write a C programming to swapped digits between 2 digits number ? Explain your answer.

(example: input :23. output:32)​

Answers

Answered by pranavarun19
0

Answer

Lets assume that your 2 digits are actually stored in a string. This makes things easier. In fact, if they’re not stored in a string it’s easy enough to get them into a string.

In C, strings can be referenced as arrays even though they’re defined as pointers to characters. It’s a neat little trick that C allows you to do. In fact C allows any point to a type to be treated as an array , no matter what the pointed-to type is. Of course you need to be careful not to stroll outside the bounds of the array!

So if you have a string defined as follows:

char * myString = “53”  

Then reversing it would simply be a matter of indexing the two digits of this string back to front. Lets also assume that you wish to keep the digits stored in the same string but simply swap them around. To do this without loosing information we’ll have to temporarily hold one digit in a safe place whilst we swap things.

char * twoDigitString = “53”  

char safePlace = twoDigitString[0];  

twoDigitString[0] = twoDigitString[1];  

twoDigitString[1] = safePlace;  

With a loop you could expand this to swap any number of digits but it’s much better for you to learn how to do this from scratch rather than simply downloading someone else’s code without understanding it.

Also note that we’re relying on the hidden null termination to exist at twoDigitString[2] so that the resulting string is still valid.

Now….if on the other hand you wanted a mathematical solution then you would have to go about separating the value of the 10s column from the 1s column using modular arthimetic. For instance:

int twoDigitNumber  = 53;  

/**  

The % operator performs modular arithmetic, returning  

the remainder after division  

**/  

int tens = (twoDigitNumber / 10) % 10;  

int ones = twoDigitNumber % 10;  

int twoDigitNumber = (ones*10) + tens

HOPE IT HELLPS

Similar questions