<<

ProgrammingProgramming inin ++C++ 11.11. ControlControl structurestructure IIII

! Iteration statements - while statement - for statement - do statement ! break and continue statements ! goto statement ! Comma operator ! Null statement ! Conditional expression operator ! Summary

1 Introduction to programming in C++ for engineers: 11. Control structure II IterationIteration statements:statements: whilewhile statementstatement The while statement takes the general form: while (control) statement The control expression which is of arithmetic type is evaluated before each execution of what is in a statement. This statement is executed if the expression is not zero and then the test is repeated. There is no do associated with the while!!! int n =5; double gamma = 1.0; while (n > 0) { gamma *= n-- } If the test never fails then the iteration never terminates.

2 Introduction to programming in C++ for engineers: 11. Control structure II IterationIteration statements:statements: forfor statementstatement The for statement has the general form: for (initialize; control; change) statement The initialize expression is evaluated first. If control is non-zero statement is executed. The change expression is then evaluated and if control is still non-zero statement is executed again. Control continues to cycle between control, statement and change until the control expression is zero. long unsigned int factorial = 1; for(inti=1;i<=n; ++i) { factorial *= i; } Initialize is evaluated only once!

3 Introduction to programming in C++ for engineers: 11. Control structure II IterationIteration statements:statements: forfor statementstatement It is also possible for any (or even all) of the expressions (but not the ) to be missing: int factorial = 1,i=1; for (; i<= n; ) { factorial *= i++; { If the loop variable is defined in the initialize expression the of it is the same as if the definition occurred before the . Unlike some other languages there is nothing special about the variable that controls the iteration in a for statement. for (double x = 0.0; x != 10.0; ++x) // VERY RISKY!!! for(doublex=0.0;x<9.999;++x)//SAFER!!!

4 Introduction to programming in C++ for engineers: 11. Control structure II IterationIteration statements:statements: dodo statementstatement The do statement has the form: do statement while (control); The is a necessary part of the do statement. The statement is executed and then if the control expression evaluates to zero control passes to the next statement. If the control expression is non-zero control passes back to the do statement. It is worth including the pair of braces in a do statement even if a compound statement is not required. If it is not done then the code may look like a while loop with an empty statement.

5 Introduction to programming in C++ for engineers: 11. Control structure II IterationIteration statementsstatements It is possible to interchangeably use any of the three iteration statements. Which one is the most appropriate depends on the particular circumstances. In C++ programming the for loop seems to be the most common iteration statement. This is probably because the syntax conveniently collects the initialization, loop control and increment all in one place. The while statement is often appropriate when initializations have been performed by the preceding statements. The iteration counter is often changed by using an increment or decrement operator resulting in very compact code. The do iteration appears rarely in C++ programs. However if there is a requirement for a statement to be executed at least once (like in menu) this statement is a very appropriate construct, since neither for nor while loops have this property.

6 Introduction to programming in C++ for engineers: 11. Control structure II breakbreak andand continuecontinue statementsstatements The break statement can only occur inside a switch or any from the three iteration statements. In the case of iteration break causes control to pass to the first statement after the end of the loop. Since we can only break from a single enclosing loop the break statement does not provide a way of exiting from inside deeply nested loops.

The continue can only occur inside an iteration statement and causes control to pass directly to the next iteration.

7 Introduction to programming in C++ for engineers: 11. Control structure II gotogoto statementstatement goto statement is an unconditional jump or transfer of control to a labelled statement. goto convergence; // some code convergence: cout << “OK\n”; Any valid identifier is acceptable as a statement label, but the same label can only be used once in the same function. The label is the only identifier whose scope is not local to the block in which it was declared. Use of the goto is strongly discouraged in current programming practice, since it makes the flow of control very difficult to follow.

8 Introduction to programming in C++ for engineers: 11. Control structure II CommaComma operatoroperator The comma operator can be used to separate a sequence of two or more expressions. The expressions are evaluated from left to right, when the result of each evaluation being discarded before the next expression is evaluated. The main use of the comma operator is in for statement. for (i=0, j=0, x=0.0; i<10 && j<10; ++i, ++j) x=x*i*j; It is a good idea to restrict the comma operator only to expressions closely related to loop control. Spurious comma operators can give rise to errors which are hard to find. x = y, + 10; // valid but should be rather x=y+10 Most commas appearing in C++ programs are separators rather than operators.

9 Introduction to programming in C++ for engineers: 11. Control structure II NullNull statementstatement A statement that does nothing is occasionally useful, often redundant and sometimes disastrous. The null statement is useful when the syntax requires a statement but there is nothing to do. while (cin >> x,x>0) ; Sometimes the result of null statement is a disaster. while (i < 10); // this loop never ends!!! sum += i++ A similar mistake can occur with the if statement. if (i == 0); // this statement does nothing x = y; // this statement is always executed

10 Introduction to programming in C++ for engineers: 11. Control structure II ConditionalConditional expressionexpression operatoroperator The conditional expression operator ?:is the only ternary operator defined in C++ and takes the form: control ? result_1 : result_2 control is evaluated and then if non-zero the whole expression evaluates to result_1, otherwise it evaluates to result_2. max=(i>j)?i:j; is equivalent to if (i > j) max=i; else max=j; Conditional expression operator produces terse code and often avoids introducing temporary variable. cout << “Max=“<<(p1>p2 ? p1 : p2);

11 Introduction to programming in C++ for engineers: 11. Control structure II SummarySummary

! There are three iteration statements: while, for and do. Use whichever is most natural for a particular problem. ! The break statement is used to exit from an iteration, whereas a continue statement causes control to pass to the next iteration. ! The comma operator separates a sequence of expressions and is mainly used in for statements. ! The conditional expression operator ?:is the only ternary operator and is useful for writing compact code.

12 Introduction to programming in C++ for engineers: 11. Control structure II