how to reverse a string in c without using library function

reverse a string in c using for loop

 There are many ways to reverse a string in c. i.e using while loop, using string library function strrev(), using for loop etc.

in this article, we clearly discussed with an easy example how to reverse a string without using the inbuilt function with examples.


Reverse a string using For loop

#include <stdio.h>
int len(char str[])
{
  int length=0;
  for(int i=0;str[i]!='\0';i++)
    {
      length++;
    }
    return length-1;
}
int main() {
    char str[]="Hello";
    int StringLength=len(str);
    char new_str[50];
    for(int i=0;i<=len(str);i++)
    {
      new_str[i]=str[StringLength];
      StringLength--;
    }
 
    printf("Reversed String is %s",new_str);
    return 0;
}

output:

Reversed String is olleH
in the above example, we created a function named len() to get the length of the string then we use for loop to read characters one by one from the given String in reverse order and write them into a new character array to create the reverse string

Post a Comment

0 Comments