Reversing a string without using string primitives in C - UCS - Unleash-Coding-Skills

Saturday, 24 March 2018

Reversing a string without using string primitives in C - UCS






    String Reverse without string handling function or primitives:

In C language the end of the string is represented '\0' So first we must find the length of string using this logic by counting it from 0 th index until we reach '\0'

After finding the length of string we can start from (length-1) index and come in 
reverse manner from end of string to beginning until index is greater than or equal to zero.In this way we can print the string in reverse order or we can reverse a string without using string handling functions.

int main()
{
//here we are considering max length of string to be 100 for example
char s[100],s1[100];
int len,i,j;
scanf("%s",s);
 i=0;
//traverse the string until you encounter '\0' that is end of string
while(s[i]!='\0')
{
i++;
}
len=i;
j=0;
for(i=len-1;i>=0;i--)
{
s1[j]=s[i];
j++;
}
//Insert '\0' to indicate the end of the string
s1[j]='\0';
printf("%s",s1);
return 0;
}
input1:
        hello
output1:
        olleh
 input2:
        abc
output2:
        cba
Happy Coding..
Comment if you have any queries

No comments:

Post a comment