-1

I want to reverse a string by only using a single loop. How can I do it? I tried one simple way but doesn't get the output I wish.

#include<iostream>
using namespace std;

int main()
{
    int i;
    char a[10];

    cout << " Enter String :";
    cin >> a;

    for(a[i] = '\0'; i > 0; i--)
    {   
        cout << "Reverse string is" << a[i];
    }

    return 0;
}
Ajit g
  • 1

1 Answers1

5

Note that you do not initialize your iterator variable i and that you could declare the index within the for-statement as you do not need this variable outside the scope of the for-loop. Furthermore, you can also use a std::string instead of a char array, this also allows for strings longer than the ten characters as you had specified.

EDIT: I assume that you can use C++17 or newer. From C++17 they finally added the non-member version std::size (which I prefer over the member related versions since I read the book effective modern c++ from Scott Meyers). If, for some reason, you cannot use this function, then you can just replace it by the string member function length, i.e., a.length().

If you only want to print the reverse of the string you could use something like the following

int main()
{
    string a;

    cout << "Enter String: ";
    cin >> a;

    for (int idx = size(a) - 1; idx >= 0; --idx)
      cout << a[idx];
    cout << endl;
}

You may also use the built-in reverse function (see description here). This function actually reverses the string itself.

int main()
{
    std::string a;

    std::cout << "Enter String: ";
    std::cin >> a;

    std::reverse(std::begin(a), std::end(a));

    std::cout << a << endl;
}

Another option is to manually reverse the string (which doesn't make sense since std::reverse is part of the standard library, but as a learning exercise it might be helpful). Note that we only iterate to half the size of the string as otherwise each element is swapped twice, resulting in the original string.

int main()
{
  string a;

  cout << "Enter String: ";
  cin >> a;

  for (size_t idx = 0, n = size(a); idx < n / 2; ++idx)
    swap(a[idx], a[n - idx - 1]);
  cout << a << endl;
}