String Reversing without using Predefined Function in C++


This is a C++ program that demonstrates how to reverse a string using the std::swap function. The program works as follows:

  • The input string str is defined and initialized with the value "TutorJoes".
  • The length of the string n is calculated using the length method.
  • A for loop is used to iterate over the first half of the string (up to the n/2-th character).
  • For each character in the first half of the string, the swap function is used to exchange it with the corresponding character in the second half of the string (i.e., the n-i-1-th character).
  • After the loop completes, the resulting value of the string is printed to the console using the cout object.
  • The program exits with a return value of 0.

Overall, this program demonstrates how to reverse a string in C++ by iterating over the first half of the string and swapping each character with its corresponding character in the second half of the string.

Source Code

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    int i,n;
    string str = "TutorJoes";
    n=str.length();
    for (i=0;i<n/2;i++)
    {
        swap(str[i],str[n-i-1]);
    }
    cout<<"\nAfter reversing string"<<str;
    return 0;
}
To download raw file Click Here

Output

After reversing string seoJrotuT


Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples