Write a function called reverse that accepts a c-string as an argument and rever
ID: 3882579 • Letter: W
Question
Write a function called reverse that accepts a c-string as an argument and reverses that argument in place returning the address of the first element of the c-string as a character pointer when you are finished. For example, if your c-string contains the string "Happy Birthday!" then after a call to the function your string would contain "lyadhtriB yppaH". For this assignment you may not use the string.h library or any other library except stdio.h. You may assume the following main program which would print the string forward, backward, and then forward again twice: int main(int argc, char * argv[]) { char word[] = "Happy Birthday!": printf("%s ", word): reverse(word): printf("%s ", word): printf("%s ", reverse(word)): printf("%s ", word): return theta: } Place the code for your function in a file called reverse.c and submit only this file to me on blackboard. The file should contain the definition for your function reverse and nothing else. I will use my own header file and main program to test your code.Explanation / Answer
Given below is the complete program showing the use of the implmented reverse function. But while submitting, you only need to copy the reverse() function into a file named reverse.c and submit. Hope the answer helped. If it did, please don't forget to rate it . Thank you very much.
#include <stdio.h>
char *reverse(char *str)
{
int i = 0, j = 0;
char temp;
//first find the end of the string
while(str[i] != '')
i++;
//now i is pointing to '', go back one location
i--;
//from backward, till we reach first character , interchange the front charactrer with
//the one in back. We oly as long as i > j, i.e only half teh length of the string.
//because each time 2 characters are interchanging their places
while(i > j)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
i--; //move i 1 position back
j++; //move j one position front
}
return str;
}
int main(int argc, char *argv[])
{
char word[] = "Happy Birthday!";
printf("%s ", word);
reverse(word);
printf("%s ", word);
printf("%s ", reverse(word));
printf("%s ", word);
return 0;
}
output
Happy Birthday!
!yadhtriB yppaH
Happy Birthday!
Happy Birthday!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.