×

How to Reverse a String in C++ using For Loop

For Loop:

We may loop through a certain section of C++ code repeatedly using the for loop.

A for loop is carried out if the test expression yields a true result. The loop comes to an end when the test expression returns false. This suggests that each time when the loop is iterated, the condition must be verified before the execution of body. If the evaluation returns a true result, the body of the loop is executed. If the evaluation yields a false result, the loop's body will not run.

The syntax of for loop:

In C++, a for loop is written as:

for (initialize; condition; increment) 
 {
 statement(x);
}

Strings:

In C++, a string is an object that represents a group (or sequence) of various characters. Strings are part of the standard string class in C++ (std::string).

The characters of a string are stored as a collection of bytes in contiguous memory regions by the string class. Strings are most typically employed in programs that need text manipulation. In C++, we may operate a variety of operations on strings. For instance, reversing, concatenating, or sending a function as an argument.

Syntax:

The syntax for generating a string in C++ is simple. In C++, the string keyword is used to generate a string. Before we can use this keyword, we must first include the standard string class in our program.

string str_ name = "this is C++ string";

Example of Declare and Initialize string:

string str_ name = "hello";

                 (or)

string str_ name("hello");
  • C++ also supports C-style strings.

Syntax:

Char str_name[  ];

String reverse using for loop:

The reverse of a string can be done using different ways:

Method 1:

C++ string reverse using reverse ()

  • reverse () is a function in the algorithm header file that reverses a sequence within a defined range. We use the reverse () function and include the <algorithm> header file.

Program to print reverse of string using REVERSE ()

#include <iostream> 
#include <algorithm>  
using namespace std;
 int main()
 {
   string str = "Java-TPoint";
   reverse(str.begin(), str.end());
   cout << str << endl;
}

The output of the program:

tnioPT-avaJ

Method 2: C++ String Reverse by Swapping Characters:

Algorithm:

Step 1: Start.

Step 2: Take a string and store it in the variable str.

Step 3: Initialize variable index with 0.

Step 4: Check to see if the index is less than half of the str's length. If its not true, go to step 7.

Step 5: Str[index] should be swapped by str[str length - 1 - index].

Step 6: Increment index, go to step 4.

Step 7: Stop.

Program to print the reverse of a string by swapping characters:

#include <iostream> 
using namespace std;
 int main() 
{
   string str = "Java-TPoint";
   char ch;
   for (int index = 0, lenth= str.length(); index< lenth/2; index++)  
   {
      ch = str[index];
      str[index] = str[lenth-1-index];
      str[lenth-1-index] = ch;
   }
  cout << str << endl;
}

The output of the program:

tnioPT-avaJ

Method 3:

This method includes the two pointers, one at the beginning and the other at the end of the sequence. The characters are reversed one by one with the help of these pointers.

Program to print reverse of string:

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    char str[] = "javatpoint";
    cout << "Original string: " << str;
     cout << endl << "String after reverse: ";
     for(int i = (strlen(str) - 1); i >= 0; i--)
         {
           cout << str[i];
        }
         return 0;
}

The output of the program:

tnioptavaj

Method 4: Using a first-to-last approach ‘for’ loop

#include <iostream >
using namespace std;
 // Function to reverse a string //
void reverseStr(string& str)
{
    int n = str.length();
    // Swap character starting from two corners //
    for (int i=0, j=n-1; i<j; i++,j--) 
    {
        swap(str[i], str[j]); 
     }
}
 // main program //
int main()
{
    string str = "javatpoint";
    reverseStr(str);
    cout << str;
    return 0;
}

Output:

tnioptavaj

Method 5: C++ String Reverse using Recursion:

Recursion: In C++, recursion is a method that calls itself, either directly or indirectly, until a certain condition is met. This technique has a base case and a recursive condition. It continuously calls the function within the same function. The recursive condition aids in the repeated execution of code, whereas the base case aids in the condition's termination.

If the recursive function does not have a base case, the recursive function will continue to repeat itself indefinitely.

Program:

#include <iostream>
using namespace std;
 void strreverse(string& str, int n, int i)
{
   if (n <= i)
   {
      return;
   }
   swap(str[i], str[n]);
   strreverse(str, n - 1, i + 1);
}
  int main()
 {
   string str = "javatpoint";
   strreverse(str, str.length() - 1, 0);
   cout << str << endl;
}

Output:

tnioptavaj

Related Topics

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

Print Table Using For-loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

3 minutes read.

C++ Output Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

4 minutes read.

Reverse a Number in C++

In this tutorial, you'll learn how to utilize a C++ program to reverse a number entered by a user at runtime. Because there are various ways to write a C++...

3 minutes read.

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

4 minutes read.

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.

C++ User Defined Exceptions

Overriding and inheriting exception class capabilities may be used to define the new exception. Exception handling can also be used with classes. We may also make an exception for user-defined...

4 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

C++ operator

In this article, we will discuss about the operators in C++ with their types and examples. An operator is specially a symbol that tells compiler to perform specific manipulation. C++ contains...

5 minutes read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.