Reverse a String in C++2 min read

In this tutorial, we will write a C++ Program to Reverse a String. There are three different ways to reverse a string.

  • Using library function, reverse()
  • Using loops instead of reverse()
  • Using recursion

However, using recursion is discussed in the next tutorial, you will get the link down below. Before beginning, you must be familiar with the following topics in C++.


Reverse a String in C++

The program takes user input for the string and then reverses it using various ways.

1. C++ Program to Reverse a String using reverse() function

Question: reverse a string in c++ using library function.

The reverse() is a built-in function provided in C++ to reverse a string. This function is defined in an algorithm header file which needs to be included at the beginning of the program.

Output:

Enter the string: simple2code
Reversed String: edocp2elmis


2. How to Reverse a String in C++ using while loop

Here the program uses a while loop to iterate and reverse the string.

Output:

Enter the String: programs
Reversed string smargorp

You can use strlen() function to calculate the length of a string and use that to iterate using a while loop.


3. Reverse a String in C++ using for loops

Here the program uses a for loop. The program uses strlen() function to calculate the length of a string then uses that value to iterate through the string.

Since you are using one of the string built-in functions, make sure to include string.h header file in a program.

Output:

Enter the String: programs
Reversed string smargorp

You may go through the following program on a string.


MORE

Java Program to find the sum of the Largest Forward Diagonal

in this tutorial, we will write a java program to find the sum of the Largest Forward Diagonal in an Arraylist (matrix). Java Program to …

C Program to search an element in an array using Pointers

A separate function( search_function()) will be created where the array pointer will be declared and the searched element along with the size of an array …

C Program to find the sum of the digits of a number using recursion function

This C program calculates the sum of digits of a given number using recursion. Here’s a concise explanation: Function Definition: sumDigits(int n) This function calculates …

C program to find factorial of a numberĀ using Ternary operator with Recursion

Recursion refers to the function calling itself directly or in a cycle. Before we begin, you should have the knowledge of following in C Programming: …

C Program to Add Two Numbers Using Call by Reference

The program takes the two numbers from the user and passes the reference to the function where the sum is calculated. You may go through …

Find the output ab, cd, ef, g for the input a,b,c,d,e,f,g in Javascript and Python

In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will …