To reverse any string in C language, first take the length of the string using strlen() or use For loop to get string length and than start For loop from (string length -1) to 0 and reverse string.
Note: Don't use strlen() function in For loop because the order of strlen() is O(n) already and when we use 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("\nEnter String= ");
gets(p);
//take the length of the string
length=strlen(p);
printf("Reverse string\n");
for(i=length-1;i>=0;i--)
printf("%c",p[i]);
getch();
return 0;
}
Output of the above Program:
Note: Don't use strlen() function in For loop because the order of strlen() is O(n) already and when we use 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("\nEnter String= ");
gets(p);
//take the length of the string
length=strlen(p);
printf("Reverse string\n");
for(i=length-1;i>=0;i--)
printf("%c",p[i]);
getch();
return 0;
}
Output of the above Program:
Reverse string in c |
No comments:
Post a Comment