Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function called reverse that accepts a c-string as an argument and rever

ID: 3662729 • 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 "!yadhtriB 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:

Explanation / Answer

/*C program that demonstrates the reverse function*/
#include<stdio.h>
#include<conio.h>
//function prototype
char* reverse(char word[]);
int main(int argc, char *argv[])
{

   //c -string
   char word[]="Happy Birthday!";

   printf("%s ",word);
  
   //calling reverse
   reverse(word);
   printf("%s ",word);
   //calling reverse
   printf("%s ",reverse(word));
   printf("%s ",word);

   getch();
}

/**The function reverse that takes word as input c string argument
and reverse the string and returns the pointer to the reverse string*/
char* reverse(char word[])
{

   //set i =0
   int i=0;
   //find the size of the word
   while (word[i]!='')
   {
       i++;
   }  

   int size=i;
   int j=i-1;
   i=0;
   //Reverse the letters of the word
   while (i<=j)
   {
       char temp = word[i];
       word[i] = word[j];
       word[j] = temp;
       i++;
       j--;
   }

   //Terminate with null
   word[size]='';
   //return word
   return word;
}

--------------------------------------------------------------------------------------------------------------------

Sample Output:

Happy Birthday!
!yadhtriB yppaH
Happy Birthday!
Happy Birthday!

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote