Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Reverse string

In this example, we will show you how to reverse the string

#include <iostream>
using namespace std;

void reverseString(string str){
    int n  = str.length();

    for(int i = n-1; i >= 0; i--){
        cout <<str[i];
    }
}

int main(){
    string str = "oceanLabz";
    reverseString(str);
    // cout<<str;
    return 0;
}

Output:

zbaLnaeco

Explanation:

Step1: reverseString Function

void reverseString(string str){
    int n = str.length();

    for(int i = n-1; i >= 0; i--){
        cout << str[i];
    }
}

Function Breakdown:

  • Input: It takes a string str as an argument.
  • String Length: The length of the string is stored in the variable n using the length() method.
  • Reversing the String: The for loop is intended to print the string characters in reverse order, starting from the last index. However, the loop starts from n, which is out of bounds because the indices of a string go from 0 to n-1. This will result in unexpected behavior (sometimes printing garbage values or causing errors).

Loop Fix:

  • The last character of the string is at index n - 1. So, the loop should start from n - 1 and run until i >= 0.

Step2: main() Function

int main(){
    string str = "oceanLabz";
    reverseString(str);
    return 0;
}

In the main() function:

  • A string str is initialized with "oceanLabz".
  • The reverseString(str) function is called to print the reverse of the string.
  • The cout<<str; line is commented out, which would print the original string if uncommented.

    Leave a Reply

    Your email address will not be published.

    Need Help?