#include // This example demonstrates that the loop variable // in a for loop can be modified both by the update // expression and within the body of the loop. // // It also demonstrates why the scope of a variable // can matter after a loop has terminated. // Function declarations int main(); // Function definitions int main() { int k{}; // In this for loop, 'k' is incremented by the // update expression ++k at the end of each // iteration. However, the user may also change // 'k' within the body of the loop. // // Because 'k' was declared before the for loop, // it remains in scope after the loop terminates. // We can therefore print the value of 'k' that // caused the condition k < 20 to become false. // // Notice that 'k' may increase by more than one // during an iteration: // // 1. the user enters a value that is added // to 'k', and // 2. ++k is then executed before the loop // condition is tested again. for ( k = 0; k < 20; ++k ) { std::cout << "k = " << k << std::endl; int value{}; std::cout << "Add what to 'k'? "; std::cin >> value; k += value; std::cout << "The value of 'k' is now " << k << "." << std::endl << std::endl; } std::cout << "The final value of 'k' is " << k << "." << std::endl; return 0; } // Exercises: // // 1. Suppose the user always enters 0. What values // of 'k' are printed, and what is the final value // of 'k' after the loop terminates? // // 2. Remember that ++k is still executed after the // statements in the loop body. If the user enters // 5 when k == 10, what will the value of 'k' be // when the condition k < 20 is next tested? // // 3. What happens if you replace // // for ( k = 0; k < 20; ++k ) { // // with // // for ( int k{ 0 }; k < 20; ++k ) { // // Before compiling the program, predict what will // happen. Will it compile? If it does, what value // will the final std::cout statement print? // // Remember that there is already a variable named // 'k' declared before the for loop. // Explanation: // // If you write // // for ( int k{ 0 }; k < 20; ++k ) { // // the program still compiles. // // The declaration creates a new variable named 'k' // whose scope is the for loop. This new variable // shadows the 'k' declared at the beginning of // main(). // // Thus, inside the loop, 'k' refers to the variable // declared by the for loop. After the loop ends, // that variable no longer exists, and 'k' once again // refers to the variable declared at the beginning // of main(). // // Because that outer variable was initialized to 0 // and was never changed, the final statement prints // // The final value of 'k' is 0. // // This is one reason to pay careful attention to // where variables are declared and to the scope of // each variable.