 C++ Program to Find the Reverse of String or Number (5 different ways) – Programming Code Examples
C++

C++ Program to Find the Reverse of String or Number (5 different ways)3 min read

In this program, we will learn how to find the reverse a number or string in C++ programming language.

We will be discussing a total of 5 ways.

• Finding reverse of a number
1. Using While loop
2. Using recursion
• Finding reverse of a string
1. Using inbuilt function
2. Using iterative method (for loop)
3. And by using recursion

Let’s discuss these ways one by one.

Find the Reverse of a Number

Using while loop

Firstly,  you have to ask the user to enter a number and store it in num variable. Now, start reversing that number to find its reverse and then display its reverse in the output.

To reverse a number, first make a variable say rev and place 0 to rev initially, and make one more variable say rem. Now place the modulus of the number to rem and place rev*10+rem to rev, now divide the number with 10 and continue until number will become 0.

Code:

Output:

Using recursion

In this, we will use recursion. The recursive method reverseNumber() is used.

Code:

Output:

Find the Reverse of a String

Using the for loop

In this program the user is asked to enter a string and it is stored in the variable str. The length of str is stored in the variable j and i is initialized as 0. Using a for loop, the string is reversed. The ith character of str is swapped with jth character using a temporary variable temp. The loop terminates when i is less than jstr is then printed which is the reversed string.

Code:

Output:

Using the inbuilt function

In this code, we will use the reverse() inbuild function.

Using the recursion

In this, we will use recursion. The recursive method recursiveReverse() is used.

1 Comment

• L.V.NAGARAJAN says: