Presentation is loading. Please wait.

Presentation is loading. Please wait.

4 Control Statements.

Similar presentations


Presentation on theme: "4 Control Statements."— Presentation transcript:

1 4 Control Statements

2 RECAP We have learnt: Variables and Data Types Relational Operators
Declaration and initialization int, char, double, float, long, short, strings Size and ranges of data types Scope of variables, global and local variables Limited to the block where they are declared Constants using #define and const Relational Operators AND, OR, NOT, &&, ||,!

3 RECAP We have learnt: Compound assignment Increase / Decrease ++ --
+=, -=, *=, /=, %= Value += increase Value = Value + increase Value -= increase Value = Value - increase Increase / Decrease ++ -- C++; C+=1; C=C+1 Can be used both as prefix or suffix

4 RECAP We have learnt: Creating functions Calling functions
Passing arguments Functions have prototypes (or signatures) that indicate to both the compiler and the programmer how to use the function

5 RECAP We have learnt: Decision Making using if and if…else selection statements to choose among alternative actions Compound statements or blocks A block can be placed anywhere a single statement can be placed Nested If else Dangling else, else is associated with the last if

6 OBJECTIVES In this class you will learn:
Basic problem-solving techniques. To use the while repetition statement to execute statements in a program repeatedly To use the for repetition statement To use Do-While statements More functions

7 Introduction Before writing a program
Have a thorough understanding of problem Carefully plan your approach for solving it While writing a program Know what “building blocks” are available Uptill now we have been focusing on the building blocks Use good programming principles

8 Algorithms Any solvable computing problem can be solved by the execution of a series of actions in a specific order Algorithms are the procedure for solving a problem in terms of The actions to execute The order in which these actions execute Program control Specifies the order in which actions execute in a program This is performed in C++ through control statements

9 Pseudocode Pseudocode
Artificial, informal language used to develop algorithms Used to think out program before coding Easy to convert into C++ program Similar to everyday English Only executable statements No need to declare variables Not executed on computers

10 Control Structures Normal statements in a program Transfer of control
Sequential execution Statements executed in sequential order Transfer of control some statements allow a programmer to specify that the next statement executed is not the next one in sequence Structured programming Eliminated goto statements Clearer, easier to debug Only three control structures in C++ Sequence structure Programs executed sequentially by default Selection structures if, if…else, switch Repetition structures while, do…while, for

11 Selection statements Three types of selection statements if if…else
Single selection statement if…else Double selection statement Selects between two different actions Switch statement Multiple selection statement Selects between many different actions

12 Conditional Operator ?:
Closely related to if…else statements Three operands First operand is a condition Second operand is the value of the entire expression if the condition is true Third operand is the value of the entire expression if the condition is false cout << ( grade >= 60 ? "Passed" : "Failed" ); Values in the conditional expression can also be actions to execute grade >= 60 ? cout << "Passed" : cout << "Failed"; Meaning: If grade is greater than or equal to 60, then cout << "Passed"; otherwise, cout << "Failed"

13 4.6 if…else Double-Selection Statement (Cont.)
Ternary conditional operator (?:) Three arguments (condition, value if true, value if false) Code could be written: cout << ( grade >= 60 ? “Passed” : “Failed” ); Condition Value if true Value if false

14 Repetition statements
Three types of repetition statements in C++ Enable programs to perform an operation repeatedly as long as a condition is true While Loop Performs the actions zero or more times For Loop Performs the actions in the body zero or more times Do…While Loop Performs the actions in the body at least once

15 Repetition statements
Counter-controlled repetition requires: Name of a control variable (loop counter) Initial value of the control variable Loop-continuation condition that tests for the final value of the control variable Increment/decrement of control variable at each iteration

16 Shopping trip example While there are more items on my shopping list
Purchase next item and cross it off my list Condition: While there are more on my list It can be either true or false

17 Shopping trip example While there are more items on my shopping list
Purchase next item and cross it off my list Condition: While there are more on my list It can be either true or false If it is true

18 Shopping trip example While there are more items on my shopping list
Purchase next item and cross it off my list Condition: While there are more on my list It can be either true or false If it is true The action will be performed repeatedly while the condition is true This action constitutes the body of the while loop It can be a single statement or a block {}

19 Shopping trip example While there are more items on my shopping list
Purchase next item and cross it off my list Condition: While there are more on my list It can be either true or false If it is true The action will be performed repeatedly while the condition is true This action constitutes the body of the while loop It can be a single statement or a block {} Once the condition is false, the loop would no longer be executed and execution will start from the next statement

20 While statements

21 Outline Control-variable name is counter with variable initial value 1 fig05_01.cpp (1 of 1) Condition tests for counter’s final value Increment the value in counter While the while loop beings execution, counter is 1 Each repetition of the loop, counter is incremented The loop executes till the counter <= 10 Loop executes 10 times What if we do not increase the counter by 1?

22 Common Programming Error
Floating-point values are approximate, so controlling counting loops with floating-point variables can result in imprecise counter values and inaccurate tests for termination.

23 While Example code: down-counter.cpp
1: int main() 2: { 3: int counter = 10; // Initialize variable 4: 5: while ( counter > 0 ) // loop continuation condition 6: { 7: cout << counter << " "; 8: counter = counter - 1; // decrease control counter by 1 9: } 10: return 0; 11: } While the while loop beings execution, counter is 10 Each repetition of the loop, the value of counter is reduced by 1 The loop executes till the counter > 0 Loop executes 10 times while ( ++counter <= 10 ) cout << counter << " ";

24 for Repetition Statement
Specifies counter-controlled repetition details in a single line of code

25 Outline The the condition counter <=10 is checked
Increment for counter Condition tests for counter’s final value Control-variable name is counter with initial value 1 Variable counter is declared and initialized on line 11 The the condition counter <=10 is checked Condition is true so goes onto line 12 Then counter ++ is executed, incrementing the counter Loop begins again from line 11 If condition is false, program continues to line 14

26 for statement header components.

27 Good Programming Practice
Using the final value in the condition of a while or for statement and using the <= relational operator will help avoid off-by-one errors. For a loop used to print the values 1 to 10, for example, the loop-continuation condition should be counter <= 10 rather than counter < 10 (which is an off-by-one error) or counter < 11 (which is nevertheless correct). Many programmers prefer so-called zero-based counting, in which, to count 10 times through the loop, counter would be initialized to zero and the loop-continuation test would be counter < 10.

28 for Repetition Statement (Cont.)
General form of the for statement for ( initialization; loopContinuationCondition; increment ) statement; Can usually be rewritten as: initialization; while ( loopContinuationCondition ) { statement; increment; } If the control variable is declared in the initialization expression It will be unknown outside the for statement

29 Common Programming Error
When the control variable of a for statement is declared in the initialization section of the for statement header, using the control variable after the body of the statement is a compilation error.

30 Good Programming Practice
Place only expressions involving the control variables in the initialization and increment sections of a for statement. Manipulations of other variables should appear either before the loop (if they should execute only once, like initialization statements) or in the loop body (if they should execute once per repetition, like incrementing or decrementing statements).

31 for Repetition Statement (Cont.)
The initialization and increment expressions can be comma-separated lists of expressions These commas are comma operators Comma operator has the lowest precedence of all operators Expressions are evaluated from left to right Value and type of entire list are value and type of the rightmost expressions

32 Common Programming Error
Using commas instead of the two required semicolons in a for header is a syntax error.

33 Common Programming Error
Placing a semicolon immediately to the right of the right parenthesis of a for header makes the body of that for statement an empty statement. This is usually a logic error.

34 Software Engineering Observation
Placing a semicolon immediately after a for header is sometimes used to create a so-called delay loop. Such a for loop with an empty body still loops the indicated number of times, doing nothing other than the counting. For example, you might use a delay loop to slow down a program that is producing outputs on the screen too quickly for you to read them. Be careful though, because such a time delay will vary among systems with different processor speeds.

35 Error-Prevention Tip Although the value of the control variable can be changed in the body of a for statement, avoid doing so, because this practice can lead to subtle logic errors.

36 Examples Using the for Statement
for statement examples Vary control variable from 1 to 100 in increments of 1 for ( int i = 1; i <= 100; i++ ) Vary control variable from 100 to 1 in increments of -1 for ( int i = 100; i >= 1; i-- ) Vary control variable from 7 to 77 in steps of 7 for ( int i = 7; i <= 77; i += 7 ) Vary control variable from 20 to 2 in steps of -2 for ( int i = 20; i >= 2; i -= 2 ) Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20 for ( int i = 2; i <= 20; i += 3 ) Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0 for ( int i = 99; i >= 0; i -= 11 )

37 Common Programming Error 5.6
Not using the proper relational operator in the loop-continuation condition of a loop that counts downward (such as incorrectly using i <= 1 instead of i >= 1 in a loop counting down to 1) is usually a logic error that yields incorrect results when the program runs.

38 Outline Vary number from 2 to 20 in steps of 2
Add the current value of number to total

39 do…while Repetition Statement
do…while statement Similar to while statement Tests loop-continuation after performing body of loop Loop body always executes at least once

40 Good Programming Practice
Always including braces in a do...while statement helps eliminate ambiguity between the while statement and the do...while statement containing one statement.

41 Outline Declare and initialize control variable counter
do…while loop displays counter’s value before testing for counter’s final value

42 break and continue Statements
break/continue statements Alter flow of control break statement Causes immediate exit from control structure Used in while, for, do…while or switch statements continue statement Skips remaining statements in loop body Proceeds to increment and condition test in for loops Proceeds to condition test in while/do…while loops Then performs next iteration (if not terminating) Used in while, for or do…while statements

43 Exit for statement (with a break) when count equals 5
Outline Loop 10 times Exit for statement (with a break) when count equals 5

44 Skip line 14 and proceed to line 9 when count equals 5
Outline Loop 10 times Skip line 14 and proceed to line 9 when count equals 5

45 Good Programming Practice
Some programmers feel that break and continue violate structured programming. The effects of these statements can be achieved by structured programming techniques we soon will learn, so these programmers do not use break and continue. Most programmers consider the use of break in switch statements acceptable.

46 Performance Tip The break and continue statements, when used properly, perform faster than do the corresponding structured techniques.

47 Factorial Program #include <iostream> using namespace std;
int Factorial (int); int main() { int maximum; // Maximum number int counter = 0; // initialize counter cout << " Enter max number for factorial "<< endl; cin >> maximum; while (counter <= maximum) cout << "Factorial of "<< counter cout << " = " << Factorial(counter)<<endl; counter++; } return 0;

48 Factorial Program int Factorial(int number) { int temp = 1;
int count = 0; while (count<number) count = count + 1; temp = temp * count; } return temp;

49 Factorial Program Enter max number for factorial 18 Factorial of 0 = 1

50 Nested Loops int main() { int j,k,limit;
cout << “Number for multiply table:”<<endl; cin >> limit; for(j=1; j <= limit; j++) { for(k=1; k <= j; k++) { cout << k*j << " "; } cout << endl; return 0; Number for multiply table: 6 1 2 4


Download ppt "4 Control Statements."

Similar presentations


Ads by Google