/* This program demonstrates * 1. variable scope * 2. Looping on a sentinel * 3. Nested Loops * * Variable Scope * The scope of a variable is the amount of time (or the number of lines) where a * variable is considered to be "active" or "alive". A variable's scope extends from * the line in which it is declared, until the next enclosing '}' * * WE CAN HAVE MANY VARIABLES OF THE SAME NAME AS LONG AS THEY ARE IN DIFFERENT SCOPES * * When we make a reference to a variable name, as a part of a cout statement, expression, * assignment, condition, etc, C++ will always resolve this to the most recent varianle * of that name that is still "alive" * * Scope with respect to for loops * We can declare variables in the initialization part of the for loop, and * these variables are only available or "alive" inside the loop * * Looping on a sentinel * There are several instances where we have to do some processing several * times, but we no not always know how many entries we have. So, the programmer * and the user can agree on a pre-determined "sentinel" value. We read in the first * entry, and as long as the entry is not the sentinel, we do the processing and * grab the next entry. * * Nested loops * We can place loops inside loops. If we do so, the inner loop runs several times * for EVERY iteration of the outer loop. We can also use nested loops in conjunction with selection statements in any * combination. */ #include using namespace std; int i = 45; // global - don't do this int main() { /* Scope of variables * When we open a set of {}, we open a new scope. A variable declared in a scope * is only available in that scope. * When a scope is closed, all the variables declared in that scope are destroyed. * In a for loop,, the variables declared in the parentheses are considered to be * declared in the scope of the for loop, and so, are only available for the * duration of the loop. * Whenever we refer to a variable, c++ will look at the most recent valid declaration * of that variable. * In the following example, the first "i" is declared outside the loop. The second "i" * is in the loop. So, the loop would use the second "i" and the lines before and * after the loop would refer to the first "i". */ int i = 60; cout<<"Before the loop: i= "<0; i--) { cout<>inBank; cout<<"Enter transaction amount: "; cin>>amount; while(amount !=0) // 0 is sentinel { inBank += amount; // add amount to current balance // a negative amoutn for a withdrawal will auto-subtract cout<<"Enter next transaction: "; cin>> amount; } cout<<"Current balance is now $ "<