-2
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s="PIZZA";
    int le=s.length();
    for(int i=le-1;i=0;i--){
        cout<<s[i];
    }

}

What is the error here? I am not getting any output.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78

3 Answers3

1

You 'd mean i >= 0 in the for loop. Otherwise you never enter it. i = 0 results to 0 which results to false.

Please do learn how to use the debugger, you will solve most of your problems with it. Unrelated: Don't use using namespace std globally, avoid reverse-iterating for loops.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
0

the condition of the loop is wrong,we want loop from last index of string into first the whole range so you should use i>=0 instead of i=0

worked code :

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    string str = "PIZZA";
    for(int i=str.length()-1;i>=0;i--)
    cout<<str[i];
}

but you'd better know that with this code we only print string from end not Reverse IT !! to reverse we use this code :

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    string str = "PIZZA";
    string rev="";
    for(int i=str.length()-1;i>=0;i--)
    rev+=str[i];
    cout<<"Reverse = "<<rev;
}

concat items from last of the string into new one !

Salar Ashgi
  • 128
  • 2
  • 13
  • Another option to reverse any container, even `std::string`, is to use [`std::reverse()`](https://en.cppreference.com/w/cpp/algorithm/reverse) instead. – Remy Lebeau Jul 18 '21 at 13:41
-2

You would have gotten your answer without asking us if you had turned on compiler warnings:

Why should I always enable compiler warnings?

That would have given you:

<source>: In function 'int main()':
<source>:9:21: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
    9 |     for(int i=le-1;i=0;i--){
      |                    ~^~
Compiler returned: 0

So the compiler is saying: "You are performing an assignment, then using the result as a boolean value/condition. Are you sure that's what you want to do?"

Now, other answers told you what to replace i=0 with (it's i>=0, or possibly i != -1). But - with the warning above, I'm pretty sure you could have reached this conclusion yourself.

einpoklum
  • 118,144
  • 57
  • 340
  • 684