A
arnuld
This is a typical interview questions. I have browsed archives and came
across solutions, both iterative and recursive. They work fine, posting
them here if there is some problem in code that I can't see:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void using_recursion(char* p, char* q);
void using_iteration(char* p);
int main(void)
{
/* can not reverse next commented array as it consists of const
characters */
/* char arr = "123" */
char arr[10] = {'1', '2', '3', '4', '5', '\0'};
char* p = arr;
printf("%s\n", arr);
printf("------------------------------\n");
using_recursion(p, (p + (strlen(p) - 1)));
printf("%s\n", arr);
using_iteration(p);
printf("%s\n", arr);
return 0;
}
void using_recursion(char* p, char* q)
{
char c;
if(NULL == p || NULL == q)
{
printf("Error: Invalid Args!\n");
}
else if( p < q)
{
c = *p;
*p = *q;
*q = c;
using_recursion(p + 1, q - 1);
}
}
void using_iteration(char* p)
{
size_t len = strlen(p);
if(NULL == p)
{
printf("Error: Invalid Args!\n");
}
else if(1 < len)
{
char* end = p + len;
char tmp = '\0';
while(end > p)
{
tmp = *p;
*p++ = *--end;
*end = tmp;
}
}
}
across solutions, both iterative and recursive. They work fine, posting
them here if there is some problem in code that I can't see:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void using_recursion(char* p, char* q);
void using_iteration(char* p);
int main(void)
{
/* can not reverse next commented array as it consists of const
characters */
/* char arr = "123" */
char arr[10] = {'1', '2', '3', '4', '5', '\0'};
char* p = arr;
printf("%s\n", arr);
printf("------------------------------\n");
using_recursion(p, (p + (strlen(p) - 1)));
printf("%s\n", arr);
using_iteration(p);
printf("%s\n", arr);
return 0;
}
void using_recursion(char* p, char* q)
{
char c;
if(NULL == p || NULL == q)
{
printf("Error: Invalid Args!\n");
}
else if( p < q)
{
c = *p;
*p = *q;
*q = c;
using_recursion(p + 1, q - 1);
}
}
void using_iteration(char* p)
{
size_t len = strlen(p);
if(NULL == p)
{
printf("Error: Invalid Args!\n");
}
else if(1 < len)
{
char* end = p + len;
char tmp = '\0';
while(end > p)
{
tmp = *p;
*p++ = *--end;
*end = tmp;
}
}
}