The variable(s) declared in the initialization part of the for loop exists only for the duration of the loop. The variable is out of scope, when the loop is over.
The variable in the function scope exists to the end of the function.
Good question. Your textbook technically ISN'T wrong believe it or not. Try compiling that program in your lab and you will realize that it works.
But most textbooks will declare all variables at the beginning. Which you have not done and which is giving you your confusion.
You're probably using Turbo C++ right? Or some old compiler.
These compilers most likely will NOT have block specific scopes (I learnt from testing). They only have function specific variables and global variables.
This means that EVERY SINGLE variable that is declared inside the main function, and that includes variables inside for-loops, are local to the function. So if you declare a variable inside a for-loop then you can use it outside the for-loop, but within the same function.
Meaning that for Turbo C++'s standard, your program is correct.
~to answer your question~
But in modern C++ there are block specific variables that means identifiers cannot be reached outside their block.
for-loop variables cannot be accessed outside the for-loop.
So how to combat this? Declare the variable outside the for-loop like dutch did.
Otherwise you would declare a variable both outside and inside the for-loop and assign the variable declared outside the value of inside variable through every iteration.
Yes it might be confusing because what we're taught. I share your sorrows when it comes to our education system.
Don't download turbo c++. Why on earth would you? Not like we get homework that you need to have a compiler at home.. After these one/two years you will never see that compiler again.