Hi, im new to C++ just started learning with C++ primer 5th edition and encountered a problem, in exercise 1.13 i am asked to write a range with a "for" loop, i have managed to get the range but it starts from " 0 " instead of the value i specified in "cin". here is my code check it out, thanks in advance.
I don't want to complicate things but just for future reference, it's common practice to put the usingnamespace std; line after declaring the headers (the headers are declared on the top two lines of the file).
Thanks alot for all your help, i wanted to ask about the correct line "for( ; v1 <= v2; ++v1),"
what does the " ; " before the condition means? isn't it supposed to be at an end of a statement? and why if i leave only the condition and the "++v1" inside the () all i am getting is infinitely running numbers?
when compiled the program infinitely runs numbers in a climbing order ,like it's not meeting the condition of stopping on " v2 " but when i add the empty statement it does meet the condition and everything is fine. btw did i miss an explanation on empty statements in the book?.
I think what is happening is that the for statement is structured like:
for ( initialization; tillCondition; finalExecutedStatement)
without the first ";" if there is no actual initialization, it sees
v1 <= v2; AS the initialization statement, which just is the same as saying true is true. Only 2 semicolons are necessary in a for's parenthetical set. The incrementor is not necesssary.
THEN, simply the next statement is evaluated as the tillCondition statement, but it physically changes the value of v1 when it executes. I THINK that basically if this statement evaluates to true (or a number greater than 0), the loop will execute again. So what you have is:
(true; ++v1; /*noIncrementor*/)
SO essentially nothing is happening at initialization, then v1 is added onto / evaluated as true, then the loop runs, thus running infinitely incrementing v1 for every iteration.
Hope I was helpful, and as always, anyone let me know if I am wrong on any point. Thanks.
You could also do it with a separate counter variable. I mention this because sometimes you don't want to change the variables holding the limits (v1 and v2 in your case):
1 2 3
for(int i = v1; i <= v2; ++i) {
cout << i << endl;
}
Some other comments:
- always use { and }, even when there is just one statement. Otherwise you will find that you actually needed two statements one day, add the second one (without adding braces), and spend 6 hours trying to figure out why the code doesn't work.
- It's a matter of taste, but I prefer "for" loops over "while" loops even when there is no initialization. With "for" loops, your code basically says
1 2
here is everything about a loop
here is what I'm doing at each iteration
with a while loop it's more like
1 2
here is a loop
here is what I'm doing during each iteration and buried in this code is the thing that changes during each iteration.