C program example to reverse a number

Hello,

I was reading on the topic Reversing a number using C program and I am wondering whether to use the Modulo or the division operator for implementing the algorithm to reverse a number in C.

Can someone explain to me under what conditions or when should each of these operators should be used? Not quite able to get this.

5 posts were split to a new topic: Change New Users Links Setting to Zero

Hi @IYELLALOT,

the point is to use number and not string operations, because strings are not available in C as a built-in data type, but only as a pointer to a memory area. If you assign an integer number to a variable, the program at runtime does not (automatically) know how many decimal places that number has, since a computer internally represents numbers as a sequence/register (usually 32 or 64 in length for integers) of binary digits that can only have the value 0 or 1. These can be interpreted as power on/power off on hardware side. Btw. floating point numbers are handled in another way than integers, but are still binary sequences internally.

C was created at the end of the 1960s for the development of UNIX, at that time there was no (elementary) need for a built-in data type of string, everything was a number (it still is, but that remains hidden from the normal user).

In order to be able to work with a kind of dynamic, i.e. variable in length, string in C, you first have to reserve (allocate) space, i.e. a number of bytes, in the memory (RAM) and release (free) that space later on so that it can be used for other data. If this does not happen, memory could eventually fill up. So the reversing-method 'alloc() -> int2str() -> reverse_str() -> str2int() -> free()' becomes quite cumbersome compared to the pure use of number operations.

One way to reverse a string is:

/* this is a *static* string, so it haven't to be freed
   before program ends, cause the compiler already allocated
   its memory space in the (binary) program file. */
char s[] = "foo2bar";
int i, j;
char t;
/* index i starts at the 1st char of s, j at the last one */
for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
    /* swap s[i] <-> s[j] */
    t = s[i];
    s[i] = s[j];
    s[j] = t; 
}

See also Binary-coded decimal - Wikipedia.