Search code examples
c++for-loopdecrement

Change for loop increment/decrement value


Consider this code:

# include <iostream>
using namespace std;

int main()
{
    for(int i = 5; i>0;)
    {
        i--;
        cout <<i<<" ";
    }
    return 0;
}

The output of this code would be 4 3 2 1 0.

Can I change the decrement/increment value?

In detail, this means that the default decrement/increment value is 1. So you either minus 1 or add 1.

Can I change it to minus 0.2 or add 1.3?


If so, is there a way to tell the compiler that I want to change the -- value from 1 to 0.2 and still using the -- operator instead of changing it to -= 0.2?


Solution

  • d-- is shorthand for d -= 1, which is shorthand for d = d - 1. You should not read this as a mathematical equation, but as "calculate d - 1 and assign the result as the new value of d".

    #include <iostream>
    
    int main()
    {
        float day = 1.2;
        for(int i = 0; i < 5; i++)
        {
            day -= 0.2;
            std::cout << day;
        }
        return 0;
    }
    

    (I also removed using namespace std as it is bad practice).

    Note the second part of the for loop is a condition that keeps the loop going as long as it is true. In your case, i > 5 is false from the beginning (because 0 < 5) so the loop will never run. I assumed you meant i < 5 instead.