0

I can't use i/10 in **FOR LOOP, C++. Can you please find why I can't use that!! when I write the code below;

#include <iostream>
using namespace std;
int main()
{
    int sum=0,i;
    cout<<"enter a no.";
    cin>>i;
    for(i;i!=0;i=i/10)
    {
        sum=sum+i%10;
    }
    cout<<"sum="<<sum;
}

After compiling it shows that:-

cpp_2.cpp:8:7: warning: statement has no effect [-Wunused-value]

for(i;i!=0;i=i/10)

Please help me!!

Community
  • 1
  • 1
  • 7
    That warning is about the first mention of `i`. The loop can be written `for ( ; i != 0; i = i / 10)`. Or, more commonly, `for ( ; i != 0; i /= 10)`. – Pete Becker Feb 25 '20 at 15:09
  • 2
    The warning is about `i` in `for(i;...)`, the first of the three parts. That's the one that has no effect. – Igor Tandetnik Feb 25 '20 at 15:09

1 Answers1

2

You can, although i = i / 10 can be abbreviated to the arguably clearer i /= 10.

Your helpful compiler is warning you about the initialisation expression of the for, which is just i, and that is a no-op.

Writing

for (; i; i /= 10)

is equivalent, and will keep the compiler happy. Note that I've replaced the tautologous i != 0 with, simply, i.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483