Reverse a string without using temporary string using C language !

This is one of the very famous interview question asked in almost all technical interviews. Let me repeat the question once again here.

Question: Write a program to reverse a string without using temporary string.

Answer:

#include <stdio.h>

int main( )

{

char str[ ] = “Subhash Embedded Classes”;

reverse(str);

printf( “%s”, str );

}

void reverse( char s[ ] )

{

int c, i, j;

for( i = 0, j = strlen(s) – 1; i < j; i++, j– )

{

c = s[i];

s[i] = s[j];

s[j] = c;

}

}

Output:

sessalC deddebmE hsahbuS

To improve yourself in C programming, I would suggest you to read “The C Programming Language” by Dennis.M.Ritchie.

Author Information:

Subhash.K.U, Principal Mentor, Subhash Embedded Classes,Bangalore.

VIEW SUBHASH’s PROFILE

SUBHASH LOVES TO TEACH ! CLICK HERE !

2 Response Comments

  • Srilekha K.N  March 16, 2016 at 12:20 pm

    super

    Reply
  • Sai Kumar  April 2, 2016 at 4:51 pm

    We can do this reversal even without using the temporary variable ‘c’ in the reverse function.

    s[i] = s[i] ^ s[j];
    s[j] = s[i] ^ s[j];
    s[i] = s[i] ^ s[j];

    Reply

Leave A Comment

Please enter your name. Please enter an valid email address. Please enter a message.