Practice Program







  • Program to Reverse a string.
  • Solution:
    void main()
    {   char ch,s[20];
       //storing length of string in variable l.
        int i;
    
    printf("Enter the string: ");
    gets(s);
    
     int l = strlen(s);
    
    
        for(i=0; i<(l/2); i++)
        {
            ch = s[i];  //at every iteration we swapping character at i index
            s[i] = s[(l-1)-i]; //with character at index ((l-1)-i)
            s[(l-1)-i] = ch;
        }
    
        printf("Reverse string is: ");
        puts(s);
    }
    

    Output1
    Enter the string: programmerdouts

    Reverse string is: stuodremmargorp

    Output2
    Enter the string: programmer

    Reverse string is: remmargorp

    Output3
    Enter the string: Hello

    Reverse string is: olleH








    defining a function 'reverse' which will reverse a  string. 

    void reverse(char s[])
    {   int l = strlen(s);//storing length of string in variable l.
     int i;
    
     char ch;
        for(i=0; i<(l/2); i++)
        {
            ch = s[i];  //at every iteration we swapping character at i index
            s[i] = s[(l-1)-i]; //with character at index ((l-1)-i)
            s[(l-1)-i] = ch;
        }
    }
    

    Using above define function 'reverse()':
    void main()
    {
        char s[20] = "programmerdoutsa";
    
        reverse(s);
        printf("Reverse string is: ");
        puts(s);
    
    }
    

    Output1
    Reverse string is: stuodremmargorp

    Using above define function 'reverse()':
    void main()
    {
        char s[20] = "programmer";
    
       reverse(s);
    
        puts(s);
    
    }
    

    Output2
    Reverse string is: remmargorp

    Using above define function 'reverse()':
    void main()
    {
        char s[20] = "Hello";
    
        reverse(s);
    
        puts(s);
    
    }
    

    Output3
    Reverse string is: olleH