Sunday, 13 July 2014

Arrays and Strings : Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)

As the question itself explains what a C-Style string is "C-String means that “abcd” is represented as five characters, including the null character."


lets start the code :-

#include<iostream.h>
#include<conio.h>
void swap(char &a, char &b)
 {

    a = a^b;
    b = a^b;
    a = a^b;
 }
void reverse(char *s)
 {
   char *p = s , *q = s ;
 while(*q)
  q++ ;
q-- ;
while(p<q)
swap(*p++ , *q--) ;
 }
int main ()
 {
   char s[] = "abcdefghijkl" ;
   reverse(s) ;
 cout<<s<<endl ;
 }

Here i did nothing but used pointers ,  reverse function receives a character pointer and assign its value to two other pointers . pointer q iterates till the end and after that q has the address of the last character and  p contains the address of the first .
nothing much important left after that all you have to do is swap first character with the last one .  Increment p's value and decrement q's value at the same time
 

No comments:

Post a Comment