This blog is under construction

Monday 24 June 2013

C program to reverse a string without using library functions

Write a c program to reverse a string without using built-in functions.


  #include <stdio.h>
  #include <string.h>
  int main() {
        char str[100], rev[100];
        int len, i = 0;

        /* get the input string from the user */
        printf("Enter your input:");
        fgets(str, 100, stdin);
        str[strlen(str)-1] = '\0';

        /* find the length of the string  */
        len = strlen(str) - 1;

        /* reverse the given string */
        while (len >= 0) {
                rev[i++] = str[len--];
        }
        rev[i] = '\0';

        /* print the reversed string */
        printf("Reverse of \"%s\" is \"%s\"\n", str, rev);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input:string reverse
  Reverse of "string reverse" is "esrever gnirts"



No comments:

Post a Comment