Senin, 31 Maret 2014

C code to reverse a string without strrev

To reverse any string in c, first take the length of the string using strlen() or use For loop to get string length and start For loop from the (string length -1) to 0 and reverse string.

Note: Dont use strlen() function in For loop because the order of strlen() is O(n) and when we used it in For loop than order becomes O(n2).

//C program to reverse a given string without using strrev() function//

#include<stdio.h>
#include<string.h>
#include<malloc.h>

int main()
{
int i=0,length;
char *p;
p=(char*)malloc(sizeof(25));
printf("
Enter String= ");
gets(p);

//take the length of the string
length=strlen(p);
printf("Reverse string
");

for(i=length-1;i>=0;i--)
printf("%c",p[i]);

return 0;
}

Related Post:

0 komentar:

Posting Komentar