Thread: reverse string

  1. #1
    Registered User
    Join Date
    Oct 2022
    Posts
    90

    reverse string

    I have written code to reverse string. I am stuck with my logic. I know string is null terminated in c language so array hold total 6 character including NULL terminator

    Code:
    #include <stdio.h>
    
    int main()
    {
        int i = 0;
        char array[6]= {"NEERG"};
    	char temp = array[0];
    	              
        for ( int i = 0; i < 5; i++)
        {
            for (int  j = 6; j >= 0; j--)
            {
                    temp =  array[i];
                    array[i] = array[j];
                    array[j] = temp;        
            }           
        }
       
        printf("%s", array);
       
        return 0;
    }
    Program output
    Code:
    REEN
    all the letters are getting reverse but G is missing in string

    How to reverse all letters

  2. #2
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    You don't need nested loops for this. A single loop is enough. Swap the first and last character, then swap the second character and second-to-last character, etc. That is, swap array[i] with array[len-i] (where len is the length of the string). Iterate while i is less than len-i.

  3. #3
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Code:
    #define swapch_(a,b) { char t; t = (a); (a) = (b); (b) = t; }
    
    char *strrev( char *s )
    {
      char *p, *q;
    
      p = s;
      q = s + strlen( s ) - 1;
    
      while ( p < q )
      {
        swapch_( *p, *q );
        p++; q--;
      }
    
      return s;
    }

  4. #4
    Registered User
    Join Date
    Jan 2023
    Posts
    5
    I assume, you are a beginner like me and thus I will provide an example, using an array.
    Code:
    #include <stdio.h>
    
    int main() {
        int j = 4;
        int tmp = 0;
        char array[6]= {"NEERG"};
        int i;
        for (i = 0; i < 3; i++) {   // swap only needs half of string
            tmp = array[j];
            array[j] = array[i];    // you can also use array[j--] = array[i];
            j--;                    // and drop this line
            array[i] = tmp;
        }
    
        printf("%s", array);
    
        return 0;
    }
    Today, I would use pointers and other stuff.

    I will strongly advice you to learn the use of a debugger, so you step by step, can follow the code.

  5. #5
    Registered User
    Join Date
    Feb 2022
    Location
    Canada, PEI
    Posts
    103
    You should also consider the case where the swapped characters are identical.

  6. #6
    Banned
    Join Date
    Oct 2022
    Posts
    5
    Code:
    #include <stdio.h>
    
    int main()
    {
        int i = 0;
        char array[6]= {"NEERG"};
    	char temp = array[0];
    	              
        for ( int i = 0; i < 6; i++)
        {
            for (int  j = 5; j >= 0; j--)
            {
                    temp =  array[i];
                    arrayI[i] = array[j];
                    array[j] = temp;        
            }           
        }
       
        printf("%s", array);
       
        return 0;
    }
    Program output
    Code:
    GREEN
    Last edited by Salem; 01-20-2023 at 06:22 AM. Reason: Removed spam link

  7. #7
    Registered User
    Join Date
    Feb 2022
    Location
    Canada, PEI
    Posts
    103
    [QUOTE=Vithika;1307660]
    Code:
    #include <stdio.h>
    
    int main()
    {
        int i = 0;
        char array[6]= {"NEERG"};
        char temp = array[0];
                      
        for ( int i = 0; i < 6; i++)
        {
            for (int  j = 5; j >= 0; j--)
            {
                    temp =  array[i];
                    arrayI[i] = array[j];
                    array[j] = temp;        
            }           
        }
       
        printf("%s", array);
       
        return 0;
    }
    Program output
    Code:
    GREEN

    Why loop through the entire array? Why not create a pointer for the start of the array and another for the end of the array and check that the start pointer is not greater or equal to the end pointer?
    Last edited by Salem; 01-20-2023 at 06:22 AM. Reason: removed spam link

  8. #8
    Banned
    Join Date
    Oct 2022
    Posts
    5
    In this code, the loop is necessary to iterate through the entire array. The goal is to reverse the elements in the array, which requires looping through the entire array and swapping the elements. A pointer for the start of the array and another for the end of the array would not accomplish this goal since the elements must be swapped in order to reverse the array.

  9. #9
    Registered User
    Join Date
    Feb 2022
    Location
    Canada, PEI
    Posts
    103
    Quote Originally Posted by Vithika View Post
    In this code, the loop is necessary to iterate through the entire array. The goal is to reverse the elements in the array, which requires looping through the entire array and swapping the elements. A pointer for the start of the array and another for the end of the array would not accomplish this goal since the elements must be swapped in order to reverse the array.
    Yeah, you are right. This doesn't work!
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char ** argv) {
      char test_str[] = "G4143's test string";
      char * bgn_str = test_str;
      char * end_str = test_str + strlen(test_str) - 1;
      fprintf(stdout, "%s\n", test_str);
      while (bgn_str < end_str) {
        if (*bgn_str != *end_str) {
          char temp = *bgn_str;
          *bgn_str = *end_str;
          *end_str = temp;
        }
        ++bgn_str;
        --end_str;
      }
      fprintf(stdout, "%s\n", test_str);
      return 0;
    }

  10. #10
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    Quote Originally Posted by Vithika View Post
    Code:
    #include <stdio.h>
    
    int main()
    {
        int i = 0;
        char array[6]= {"NEERG"};
        char temp = array[0];
                      
        for ( int i = 0; i < 6; i++)
        {
            for (int  j = 5; j >= 0; j--)
            {
                    temp =  array[i];
                    arrayI[i] = array[j];
                    array[j] = temp;        
            }           
        }
       
        printf("%s", array);
       
        return 0;
    }
    Program output
    Code:
    GREEN
    Your code doesn't even compile (arrayI is undeclared), and it has the same flaw as OP's (it doesn't work correctly).

    If you actually built it (after fixing the arrayI issue) and ran it, you would see that it prints "EEN".

    It baffles me why people don't actually test their code before posting it (especially for such short and simple bits of code like this).

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Quote Originally Posted by christop View Post
    Your code doesn't even compile (arrayI is undeclared), and it has the same flaw as OP's (it doesn't work correctly).

    If you actually built it (after fixing the arrayI issue) and ran it, you would see that it prints "EEN".

    It baffles me why people don't actually test their code before posting it (especially for such short and simple bits of code like this).
    Probably because Vithika is only here to spam sites, and has no skill apart from copy/paste.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #12
    Banned
    Join Date
    Oct 2022
    Posts
    5
    Thanks to both of you for boosting up the self-esteem 😒

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reverse a string without string.h library
    By antros48 in forum C Programming
    Replies: 6
    Last Post: 09-10-2011, 06:01 PM
  2. reverse a string
    By jas_atwal in forum C Programming
    Replies: 5
    Last Post: 01-01-2008, 01:16 PM
  3. Reverse a string (without using any string functions?)
    By geetard in forum C Programming
    Replies: 2
    Last Post: 11-15-2006, 07:42 PM
  4. How do I reverse a string?
    By Cshot in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 08-06-2002, 05:35 AM
  5. How to reverse a string C
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 07-18-2002, 12:26 PM

Tags for this Thread