









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
STATEMENT: Simple and Compound Statements, The if Statement, The switch Statement, The while Statement, The do Statement, The for Statement, The continue Statement, The break Statement, The goto Statement, The return Statement & An Exercises.
Typology: Study notes
1 / 16
This page cannot be seen from the preview
Don't miss anything!
Statement, The do Statement, The for Statement, The continue Statement, The break Statement, The goto Statement, The return Statement & An Exercises.
This chapter introduces the various forms of C++ statements for composing programs. Statements represent the lowest- level building blocks of a program. Roughly speaking, each statement represents a computational step which has a certain side-effect. (A side-effect can be thought of as a change in the program state, such as the value of a variable changing because of an assignment.) Statements are useful because of the side-effects they cause, the combination of which enables the program to serve a specific purpose (e.g., sort a list of names). A running program spends all of its time executing statements. The order in which statements are executed is called flow control (or control flow). This term reflect the fact that the currently executing statement has the control of the CPU, which when completed will be handed over ( flow ) to another statement. Flow control in a program is typically sequential, from one statement to the next, but may be diverted to other paths by branch statements. Flow control is an important consideration because it determines what is executed during a run and what is not, therefore affecting the overall outcome of the program. Like many other procedural languages, C++ provides different forms of statements for different purposes. Declaration statements are used for defining variables. Assignment-like statements are used for simple, algebraic computations. Branching statements are used for specifying alternate paths of execution, depending on the outcome of a logical condition. Loop statements are used for specifying computations which need to be repeated until a certain logical condition is satisfied. Flow control statements are used to divert the execution path to another part of the program. We will discuss these in turn.
A simple statement is a computation terminated by a semicolon. Variable definitions and semicolon-terminated expressions are examples: int i; // declaration statement ++i; // this has a side-effect double d = 10.5; // declaration statement d + 5; // useless statement!
Statement, The do Statement, The for Statement, The continue Statement, The break Statement, The goto Statement, The return Statement & An Exercises. The last example represents a useless statement, because it has no side-effect (d is added to 5 and the result is just discarded). The simplest statement is the null statement which consists of just a semicolon: ; // null statement Although the null statement has no side-effect, as we will see later in the chapter, it has some genuine uses. Multiple statements can be combined into a compound statement by enclosing them within braces. For example: { int min, i = 10, j = 20; min = (i < j? i : j); cout << min << '
n'; } Compound statements are useful in two ways: (i) they allow us to put multiple statements in places where otherwise only single statements are allowed, and (ii) they allow us to introduce a new scope in the program. A scope is a part of the program text within which a variable remains defined. For example, the scope of min, i, and j in the above example is from where they are defined till the closing brace of the compound statement. Outside the compound statement, these variables are not defined. Because a compound statement may contain variable definitions and defines a scope for them, it is also called a block. The scope of a C++ variable is limited to the block immediately enclosing it. Blocks and scope rules will be described in more detail when we discuss functions in the next chapter.
It is sometimes desirable to make the execution of a statement dependent upon a condition being satisfied. The if statement provides a way of expressing this, the general form of which is: if ( expression ) statement ; First expression is evaluated. If the outcome is nonzero then statement is executed. Otherwise, nothing happens. For example, when dividing two values, we may want to check that the denominator is nonzero: if (count != 0) average = sum / count; To make multiple statements dependent on the same condition, we can use a compound statement: if (balance > 0) { interest = balance * creditRate; balance += interest;
Statement, The do Statement, The for Statement, The continue Statement, The break Statement, The goto Statement, The return Statement & An Exercises. First expression is evaluated. If the outcome is nonzero then statement 1 is executed. Otherwise, statement 2 is executed. For example: if (balance > 0) { interest = balance * creditRate; balance += interest; } else { interest = balance * debitRate; balance += interest; } Given the similarity between the two alternative parts, the whole statement can be simplified to: if (balance > 0) else interest = balance * creditRate; interest = balance * debitRate; balance += interest; Or simplified even further using a conditional expression: interest = balance * (balance > 0? creditRate : debitRate); balance += interest; Or just: balance += balance * (balance > 0? creditRate : debitRate); If statements may be nested by having an if statement appear inside another if statement. For example: if (callHour > 6) {
Statement, The do Statement, The for Statement, The continue Statement, The break Statement, The goto Statement, The return Statement & An Exercises. if (callDuration <= 5) charge = callDuration * tarrif1; else } else charge = 5 * tarrif1 + (callDuration - 5) * tarrif2; charge = flatFee; A frequently-used form of nested if statements involves the else part consisting of another if-else statement. For example: if (ch >= '0' && ch <= '9') kind = digit; else { if (ch >= 'A' && ch <= 'Z') kind = upperLetter; else { if (ch >= 'a' && ch <= 'z') kind = lowerLetter; else } } kind = special;
Statement, The do Statement, The for Statement, The continue Statement, The break Statement, The goto Statement, The return Statement & An Exercises. result in result. switch (operator) { case '+': result = operand1 + operand2; break; case '-': result = operand1 - operand2; break; case '': result = operand1 * operand2; break; case '/': result = operand1 / operand2; break; default:cout << "unknown operator: " << ch << '\n'; break; } As illustrated by this example, it is usually necessary to include a break statement at the end of each case. The break terminates the switch statement by jumping to the very end of it. There are, however, situations in which it makes sense to have a case without a break. For example, if we extend the above statement to also allow x to be used as a multiplication operator, we will have: switch (operator) { case '+': result = operand1 + operand2; break; case '-': result = operand1 - operand2; break; case 'x': case '': result = operand1 * operand2; break; case '/': result = operand1 / operand2; break; default:cout << "unknown operator: " << ch << '\n'; break; } Because case 'x' has no break statement (in fact no statement at all!), when this case is satisfied, execution proceeds to the statements of the next case and the multiplication is performed. It should be obvious that any switch statement can also be written as multiple if-else statements. The above statement, for example, may be written as: if (operator == '+') result = operand1 + operand2; else if (operator == '-')
Statement, The do Statement, The for Statement, The continue Statement, The break Statement, The goto Statement, The return Statement & An Exercises. result = operand1 - operand2; else if (operator == 'x' || operator == '*') result = operand1 * operand2; else if (operator == '/') result = operand1 / operand2; else cout << "unknown operator: " << ch << '\n'; However, the switch version is arguably neater in this case. In general, preference should be given to the switch version when possible. The if-else approach should be reserved for situation where a switch cannot do the job (e.g., when the conditions involved are not simple equality expressions, or when the case labels are not numeric constants).
The while statement (also called while loop ) provides a way of repeating an statement while a condition holds. It is one of the three flavors of iteration in C+ +. The general form of the while statement is: while ( expression ) statement ; First expression (called the loop condition ) is evaluated. If the outcome is nonzero then statement (called the loop body ) is executed and the whole process is repeated. Otherwise, the loop is terminated. For example, suppose we wish to calculate the sum of all numbers from 1 to some integer denoted by n. This can be expressed as: i = 1; sum = 0; while (i <= n) sum += i++; For n set to 5, Table 3.1 provides a trace of the loop by listing the values of the variables involved and the loop condition. Table 3.1 While loop trace. Iteration i n i <= n sum += i+ + First 1 5 1 1 Second 2 5 1 3 Third 3 5 1 6
Statement, The do Statement, The for Statement, The continue Statement, The break Statement, The goto Statement, The return Statement & An Exercises. has two additional components: an expression which is evaluated only once before everything else, and an expression which is evaluated once at the end of each iteration. The general form of the for statement is: for ( expression 1 ; expression 2 ; expression 3 ) statement ; First expression 1 is evaluated. Each time round the loop, expression 2 is evaluated. If the outcome is nonzero then statement is executed and expression 3 is evaluated. Otherwise, the loop is terminated. The general for loop is equivalent to the following while loop: expression 1 ; while ( expression 2 ) { statement ; expression 3 ; } The most common use of for loops is for situations where a variable is incremented or decremented with every iteration of the loop. The following for loop, for example, calculates the sum of all integers from 1 to n. sum = 0; for (i = 1; i <= n; ++i) sum += i; This is preferred to the while-loop version we saw earlier. In this example, i is usually called the loop variable. C++ allows the first expression in a for loop to be a variable definition. In the above loop, for example, i can be defined inside the loop itself: for (int i = 1; i <= n; ++i) sum += i; Contrary to what may appear, the scope for i is not the body of the loop, but the loop itself. Scope-wise, the above is equivalent to: int i; for (i = 1; i <= n; ++i) sum += i; Any of the three expressions in a for loop may be empty. For example, removing the first and the third expression gives us something identical to a while
Statement, The do Statement, The for Statement, The continue Statement, The break Statement, The goto Statement, The return Statement & An Exercises. loop: for (; i != 0;) // is equivalent to: while (i != 0) something; // something; Removing all the expressions gives us an infinite loop. This loop's condition is assumed to be always true: for (;;) // infinite loop something; For loops with multiple loop variables are not unusual. In such cases, the comma operator is used to separate their expressions: for (i = 0, j = 0; i + j < n; ++i, + +j) something; Because loops are statements, they can appear inside other loops. In other words, loops can be nested. For example, for (int i = 1; i <= 3; ++i) for (int j = 1; j <= 3; ++j) cout << '(' << i << ',' << j << ")\n"; produces the product of the set {1,2,3} with itself, giving the output: (1,1) (1,2) (1,3) (2,1) (2,2) (2,3) (3,1) (3,2) (3,3)
The continue statement terminates the current iteration of a loop and instead jumps to the next iteration. It applies to the loop immediately enclosing the continue statement. It is an error to use the continue statement outside a loop. In while and do loops, the next iteration commences from the loop condition. In a for loop, the next iteration commences from the loop’s third expression. For example, a loop which repeatedly reads in a number, processes it but ignores
Statement, The do Statement, The for Statement, The continue Statement, The break Statement, The goto Statement, The return Statement & An Exercises. A break statement may appear inside a loop (while, do, or for) or a switch statement. It causes a jump out of these constructs, and hence terminates them. Like the continue statement, a break statement only applies to the loop or switch immediately enclosing it. It is an error to use the break statement outside a loop or a switch. For example, suppose we wish to read in a user password, but would like to allow the user a limited number of attempts: for (i = 0; i < attempts; ++i) { cout << "Please enter your password: "; cin >> password; if (Verify(password)) // check password for correctness break; // drop out of the loop cout << "Incorrect!\n"; } Here we have assumed that there is a function called Verify which checks a password and returns true if it is correct, and false otherwise. Rewriting the loop without a break statement is always possible by using an additional logical variable (verified) and adding it to the loop condition: verified = 0; for (i = 0; i < attempts && !verified; ++i) { cout << "Please enter your password: "; cin
password; verified = Verify(password)); if (!verified) cout << "Incorrect!\n"; } The break version is arguably simpler and therefore preferred.
The goto statement provides the lowest-level of jumping. It has the general form: goto label ; where label is an identifier which marks the jump destination of goto. The label should be followed by a colon and appear before a statement within the same function as the goto statement itself. For example, the role of the break statement in the for loop in the previous section can be emulated by a goto:
Statement, The do Statement, The for Statement, The continue Statement, The break Statement, The goto Statement, The return Statement & An Exercises. for (i = 0; i < attempts; ++i) { cout << "Please enter your password: "; cin >> password; if (Verify(password)) // check password for correctness goto out; // drop out of the loop cout << "Incorrect!\n"; } out: //etc... Because goto provides a free and unstructured form of jumping (unlike break and continue), it can be easily misused. Most programmers these days avoid using it altogether in favor of clear programming. Nevertheless, goto does have some legitimate (though rare) uses. Because of the potential complexity of such cases, furnishing of examples is postponed to the later parts of the book.
The return statement enables a function to return a value to its caller. It has the general form: return expression ; where expression denotes the value returned by the function. The type of this value should match the return type of the function. For a function whose return type is void, expression should be empty: return; The only function we have discussed so far is main, whose return type is always int. The return value of main is what the program returns to the operating system when it completes its execution. Under UNIX, for example, it its conventional to return 0 from main when the program executes without errors. Otherwise, a non-zero error code is returned. For example: int main (void) { cout << "Hello World\n"; return 0; } When a function has a non-void return value (as in the above example), failing to return a value will result in a compiler warning. The actual return value will be undefined in this case (i.e., it will be whatever value which happens to be
Statement, The do Statement, The for Statement, The continue Statement, The break Statement, The goto Statement, The return Statement & An Exercises. ... 9 x 9 = 81