Home > Mobile >  Can I change the for loop -- value in C ?
Can I change the for loop -- value in C ?

Time:06-30

Consider this code:

# include <iostream>
using namespace std;

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

Understand that this code will print 43210.

My question is: 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?


Update

What if it is not i? How do I do it?

# include <iostream>
using namespace std;
int main()
{
    float day = 1.2;
    for(int i = 0; i > 5; i  )
    {
        day--; // I want to minus by 0.2
        cout<<day;
    }
    return 0;
}

CodePudding user response:

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.

CodePudding user response:

You can change the loop variable both inside the for and the body any way you like. For example:

for (double d = 4; d > 0; d = cos(d)   1 / d) {
    d = sin(d);
    std::cout << d << " ";
}

C does not have a fixed count loop like other languages for i = 0 to 10 do ... done where the i can not be changed. Do whatever you like.

Note: I change the type to double since you asked about decrementing by 0.2. The type int doesn't allow that.

  • Related