Explore
ProGrad Programs
Placement Prep
TCS Codevita
Live Placement Training
Webinars
About Us

Edit
Reply




Edit

Program to reverse a string in C, C++, Java and Python | FACE Prep

Published on 11 Mar 2020

In this article, we will discuss different methods to reverse a string in C/C++/Java/Python. A string can be reversed using the following approaches.


  • Method 1: By swapping the characters of the string
  • Method 2: By using recursion
  • Method 3: By using standard library functions


Consider the below I/O samples before you program to reverse a string.


SAMPLE INPUT 1: faceprep

SAMPLE OUTPUT 1: perpecaf


SAMPLE INPUT 2: welcome

SAMPLE OUTPUT 2: emoclew


Method 1: Reverse a string by swapping the characters


The algorithm used in this method to reverse a given string is:


  • Input the string from the user
  • Find the length of the string. The actual length of the string is one less than the number of characters in the string. Let actual length be j.
  • Repeat the below steps from i = 0 to the entire length of the string.
  • rev[i] = str[j]
  • Print the reversed string.


Program to reverse a string by swapping the characters using the iterative approach


C
C++
Java
Python 3

Output
INPUT - programs OUTPUT - smargorp


Method 2: Program to reverse a string using recursion


C
C++
Java

Output
INPUT - programs OUTPUT - smargorp


Method 3: Program to reverse a string using the standard library function


C++
Java
Python 3

Output
INPUT - programs OUTPUT - smargorp


Recommended Programs





If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in