Getting Started

(lily) #1

Chapter 5: C Control Flow


for (i = 0, j = strLen(s)-1; i < j; i++, j--){

raightforward. Put the first char from the array in a box, then put
the last character in the array in the position of the first character, then take the
he array. Mover your index in


//NOTE: stolen from K&R p. 64 itoa function
char s[])

gn = n) < 0) // record sign
// make n positive

se order
0'; // get next digit
while ((n /= 10) > 0); // delete it
if (sign < 0)

ring

rself. Don’t be tempted to succumb to boredom and blow

c = s[i];
s[i] = s[j];
s[j] = c;
}
}

This is pretty st


stored character and put it in the last position in t
one position on both ends and repeat.


Now try to develop an algorithm for converting an integer to an ASCII string.
Mine worked, but wasn’t even close in the quality of the actual function in K&R.
Oh, well.


void itoa(int n,
{
int i, sign;

if ((si
n = -n;
i = 0;
do { // generate digits in rever
s[i++] = n % 10 + '
}

s[i++] = '-';
s[i] = '\0'; // add null terminator for st
reverse(s);
}

In my attempt at this, I never thought to do it backwards then reverse the string.
First store the integer in the ‘sign’ variable and we get the sign of the integer by
using the ‘if’ statement to see if the integer is less than 0, if so, we multiple it by –
1 to make it positive. Then we use do while, because we want to have at least one
digit. Now get out your paper and pencil computer and run the number 1234
through the do while loop, since no amount of explaining will be as effective as
running the numbers you

Free download pdf