C++ Reverse Array
Solution 1:
Despite this looking quite homeworky, may I suggest:
void reverse(char word[])
{
int len=strlen(word);
char temp;
for (int i=0;i<len/2;i++)
{
temp=word[i];
word[i]=word[len-i-1];
word[len-i-1]=temp;
}
}
or, better yet, the classic XOR implementation:
void reverse(char word[])
{
int len=strlen(word);
for (int i=0;i<len/2;i++)
{
word[i]^=word[len-i-1];
word[len-i-1]^=word[i];
word[i]^=word[len-i-1];
}
}
Solution 2:
Since this is homework, I'll point you toward a solution without just giving you the answer.
Your reverse
function can modify the word
that is passed in. One thing you'll need to know is how long the word is (so you'll know how many letters to reverse), you can get this from the strlen()
function. If you're not permitted to use pointers, then you can use a local int
index variable.