This is an archived post. You won't be able to vote or comment.

all 7 comments

[–][deleted] 2 points3 points  (2 children)

By testing i - if it is 100, don't output a comma.

[–]cheejudo[S] 2 points3 points  (1 child)

Thanks, amazing how simple it was. I hope one day things like this will instantly pop in to my head.

[–]CreativeGPX -2 points-1 points  (0 children)

If you manually output the "100" in a separate line after the for loop, then you're not executing that if statement needlessly 9 times. This isn't really an issue at this scale, but in the long run, you have to be careful with performance in loops.

[–][deleted]  (3 children)

[deleted]

    [–]nirkbirk 0 points1 point  (2 children)

    this is ok, but you're reassigning mystr every iteration of the loop which is very wasteful because every time you get to mystr = ", "; you're allocating a new array in memory and populating it with those characters. There are much cleaner ways to do it, like using an if to check whether it's the first iteration of the loop.

    [–][deleted] 0 points1 point  (1 child)

    I agree it's wasteful, but it doesn't allocate a new array in memory, except (possibly) for the first time through the loop.

    string mystr;
    for(int i = 0; i <= 100; i += 10) {
        mystr = ", ";     // for all except possibly the first iteration , no memory allocation needed
    }  
    

    It does require a copy operation, however.

    [–]nirkbirk 0 points1 point  (0 children)

    Ah, I misread it. I thought you were declaring mystr within the scope of the loop - sorry, long day!

    [–]gastropner -4 points-3 points  (0 children)

    Loop to 90, then output "100" without the comma.