Write a function that takes a C string as an input parameter and reverses the st
ID: 3769812 • Letter: W
Question
Write a function that takes a C string as an input parameter and reverses the string. The function should use two pointers, front and rear. The front pointer should initially reference the first character in the string, and the rear pointer should initially reference the last character in the string. Reverse the string by swapping the characters referenced by front and rear, then increment front to point to the next characters and decrement rear to point to the preceding character, and and so on, until the entire string is reversed. Write a main program to test your function on various strings of both even and odd length.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
void reverse(char *front, char *rear)
{
char c;
while(front!=rear) //to handle odd length cases
{
//swapping
c = *rear;
*rear = *front;
*front = c;
if(front+1==rear) //to handle even length cases
return;
//incrementing and decrementing
front++;
rear--;
}
return;
}
int main()
{
char test[100] = "abc"; //odd length
int i,size = 0;
for(i=0;test[i]!='';i++)
size++;
printf("Original string is %s ", test);
reverse(test,test+size-1);
printf("Reversed string is %s ",test);
char test2[100] = "ab"; //even length
size = 0;
for(i=0;test2[i]!='';i++)
size++;
printf("Original string is %s ", test2);
reverse(test2,test2+size-1);
printf("Reversed string is %s ",test2);
return 1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.