Change i++ in a for loop

I am currently writing a program that must use a for loop that will determine the log of two numbers loga, logb. The only way that i know to create a for loop is by for example
 
  for (int i = 0; i < size; i++)

What i would like to know is if you can change the i++ (i+1) to for example
( i + 0.01 )
I believe you can change i++ to anything you like. i+=0.01, foo(), int c=3, etc.

I don't think the compiler cares what you put there, it will just do whatever's there until the loop condition is met.
closed account (EwCjE3v7)
Well if you wanted to do i + 1, that would have no effect, as it would add 1 to i and than do nothing with it, it isn`t going to do anything, You would rather do i += 1

This is the same as i + 1 = i;

So for sure you can do for (int i = 0; i < 10; i+=1)

But as if for i + 0.01, same thing applies as above that it does not really do anything so you would need to write it as i += 0.01

But now we have a different error, i is an int and it does not have a decimal point so what 0.01 will be turned into will be , Which means the loop will never end. You will need to write a floating point number such as a double if you would like to do i += 0.01.
Example


1
2
for (double d = 0; d < 10; d += 0.01)
        std::cout << d << std::endl;



And just a few more facts when you did your for (int i = 0; i < size; i++)

Well there is no error in this, well the i++

For example

1
2
3
    int i = 1;
    std::cout << i++ << std::endl; // This will print 1, not 2
    std::cout << i << std::endl;   // This will print 2 


Now what this does is, that it prints the current value of i and then increments it, in you loop you could have written ++i as we are not doing anything with the value before incrementing, so now look at this
1
2
3
    int i = 1;
    std::cout << ++i << std::endl; // This will print 2, it will increment first then print
    std::cout << i << std::endl;   // This will print 2 also 


Here is more about the prefix and postifx ++ operator: http://www.hotscripts.com/forums/c-c/57931-c-tip-what-difference-between-postfix-prefix-operators.html
Last edited on
Topic archived. No new replies allowed.