Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter : 9 Control Statements Control Flow: A control flow Statement regulates the order in which statements get executed. F Flow-order in which the computer.

Similar presentations


Presentation on theme: "Chapter : 9 Control Statements Control Flow: A control flow Statement regulates the order in which statements get executed. F Flow-order in which the computer."— Presentation transcript:

1 Chapter : 9 Control Statements Control Flow: A control flow Statement regulates the order in which statements get executed. F Flow-order in which the computer executes the lines of code in our program F Control flow blocks are basically blocks of code that control the way data flows, or else which statements are executed when. This can be useful if you only want certain areas of your code to be executed under a given condition.

2 Statements : A statement represents an action or a sequence of actions. The statement cout<<"Welcome toC++!”; is a statement to display the "Welcome to C++!" Every statement in C++ ends with a semicolon (;). Blocks: pair of braces in a program forms a block that groups components of a program. that is Block is a group of zero or more statement between balanced braces{} and can be used any where a single statement is allowed

3 Void main() { cout<<"Welcome to C++”; } NULL STATEMENT o A null statement is useful in those instance where the syntax of the language requires the presence of a statement but where the logic of the program does not. It takes the following form: ;  it is a null statement

4 F The default flow of control in a program is TOP to BOTTOM, i.e. all the statements of a program are executed one by one in the sequence from top to Bottom. This execution order can be altered with the help of control instructions. F C++ supports three types of control instructions - 1. Sequence Statement 2.Decision Making / Conditional / Selection Statements 3..Looping / Iterative Statements

5 Program Structure Void main() {}{} // comments about the header file // comments about the body body

6 F SEQUENCE F The sequence means the statements are being executed sequentially. This represents default flow of statement. Statement 1 Statement 3 Statement 2

7 #include void main() { clrscr(); cout<<“welcome to C++\n”; cout<<“welcome to XI class students”; getch(); }

8 Statement 1 Statement 2 SELECTION The selection Statements means the execution of statement(s) depending upon a given condition. Statement 1 Statement 2 Condition ? true false Condition ? Statement 1 Condition ? Statement 2 Statement 1 Condition ? Statement 1 Statement 2 Statement 1 Condition ? Statement 2 Statement 1 Statement 2 Statement 1 Condition ? Statement 1 Statement 2 Statement 1 Condition ? Statement 1 Statement 2 Statement 1 Condition ? Statement 2 Statement 1 Condition ? Statement 2 Statement 1 Condition ? Statement 2 Statement 1 Condition ? Statement 2 Statement 1 Condition ? true Statement 2 Statement 1 Condition ? true Statement 2 Body of IF Condition ? false Statement 1 false Statement 1 false Statement 1 false Statement 1 false Body of else false Condition ? Statement 2 Statement 1 Statement 2

9 F C++ provides two types of selection statement: F IF F SWITCH. F Selection F One-way selection(if) F Two-way selection(if…else) F Compound (block of) statements F Multiple selections (nested if) F Conditional operator  switch structures

10 F One-Way Selection F Syntax: if (expression) statement F Expression referred to as decision maker. F Statement referred to as action statement.  if given condition is TRUE, statement will get executed.

11 //Determine the age is eligible for vote. #include void main() { clrscr(); int age; cout<<“ please enter the age \n”; cin>>age; If(age>=18) { cout<<“eligible for vote”; } getch(); } One-Way Selection

12 Two-Way Selection F Syntax: if (booleanExpression/condition) { statement1(s)-for-the-true-case; } else { statement2(s)-for-the-false-case; } F else statement must be paired with an if.  if given condition is TRUE, expr_set1 will get executed. If given condition is FALSE (not TRUE), expr_set2 will get executed.

13 Two-Way Selection

14 //Determine the age is eligible for vote. #include void main() { clrscr(); Ing age; cout<<“ please enter the age \n”; cin>>age; If(age>=18) { cout<<“eligible for vote”; } else { cout<<“Not eligible for vote”; } getch(); }

15 Compound (Block of) Statements Syntax: { statement1 statement2. statementn }

16 Compound (Block of) Statements if (age > 18) { cout<<"Eligible to vote."; cout<<"No longer a minor.”; } else { cout<< "Not eligible to vote.”; cout<< "Still a minor."; }

17 F Nested if statement if ( ) //... if ( ) else if ( ) … else if ( ) else

18 Multiple Selection: Nested if F Syntax: if (expression1){ statement1; if (expression2) statement2; else statement3; } Else {…..} F Else is associated with the most recent incomplete if. F Multiple if statements can be used in place of if…else statements. F May take longer to evaluate.

19 Conditional (? :) Operator F Ternary operator F Syntax: expression1 ? expression2 : expression3 F if expression1 = true, then the result of the condition is expression2. Otherwise, the result of the condition is expression3.

20 Conditional Operator if (x > 0) y = 1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1;

21

22 22 THE switch STATEMENT F The switch statement is a decision structure that allows you to specify a branch to a segment of code based upon matching the value of the SwitchExpression with the value of CaseExpression following the key word case at the beginning of a segment. F This SwitchExpression must evaluate to a value of type int, short, byte, or char. F This expression must have a constant value. It may involve named constants and/or literals of the types specified above. It cannot include variables.

23 F Each of the case statements begins with the key word case and is followed by a CaseExpression and a colon. This is often called the case label. F When a switch statement is executed the parenthesized SwitchExpression is evaluated, the value of this expression is compared with the value of the CaseExpressions in the cases, if an expression with an equivalent value is found, execution branches to the statement(s) following the label in the matching case. The expression of switch must not be long, float, double, or boolean, it must be either byte, short, char, or int. (assignment compatible with int) Default clause can be placed any where in the block. FALL -THROUGH: The fall of control to the following cases of matching case, is called Fall-through.

24 24 THE switch STATEMENT F The break statement causes a break/exit from the block of the switch statement to the first statement following the switch block. switch (SwitchExpression) { case CaseExpression: optional statement(s) break; case CaseExpression: optional statement(s) break; case CaseExpression: optional statement(s) break; default: // The default case is optional statement(s) break; } Remember a block is a group of statements enclosed in {}. This is the switch block.

25 switch Structures

26 26 THE switch STATEMENT F An optional default case is given the label default. This case is branched to if none of the case expressions match the parenthesized SwitchExpression. switch (SwitchExpression) { case CaseExpression: optional statement(s) break; case CaseExpression: optional statement(s) break; case CaseExpression: optional statement(s) break; default: // The default case is optional statement(s) break; }

27 cin>>grade; switch (grade) { case 'A': cout<<"The grade is A."; break; case 'B': cout<<" "The grade is B."; break; case 'C': cout<<" "The grade is C."; break; case 'D': cout<<" "The grade is D."; break; case 'F': cout<<" "The grade is F."; break; default: cout<<" "The grade is invalid."; }

28 28 THE switch STATEMENT Example: How would you/or could you convert the following if/else if statement to a switch statement? If x is some integer type? If x is some floating-point type? if (x < 5) { y = x; } else if (x <= 100) { y = x + 10; } else { y = 0; }

29 F Switch F There are times in which you wish to check for a number of conditions, and to execute different code depending on the condition. One way to do this is with if/else logic, such as the example below: F int x = 1; int y = 2; F if (SOME_INT == x) F { //DO SOMETHING } F else if (SOME_INT == y) F { //DO SOMETHING ELSE } F else F { //DEFAULT CONDITION }

30 F This works, however another structure exists which allows us to do the same thing. Switch statements allow the programmer to execute certain blocks of code depending on exclusive conditions. The example below shows how a switch statement can be used: F int x = 1; int y = 2; F switch (SOME_INT) F { F case x: F method1(SOME_INT); F break; F case y: F method2(SOME_INT); F break; F default: F method3(); F break; F }

31 F Switch takes a single parameter, which can be either an integer or a char. In this case the switch statement is evaluating SOME_INT, which is presumably an integer. When the switch statement is encountered SOME_INT is evaluated, and when it is equal to x or y, method1 and method2 are executed, respectively. The default case executes if SOME_INT does not equal x or y, in this case method3 is executed. You may have as many case statements as you wish within a switch statement. F Notice in the example above that "break" is listed after each case. This keyword ensures that execution of the switch statement stops immediately, rather than continuing to the next case. Were the break statement were not included "fall-through" would occur and the next case would be evaluated (and possibly executed if it meets the conditions).

32 F Differences between the If-else and Switch ST: F Switch can only test for equality whereas if can evaluate a relational or logical expression that is multiple condition. F The switch statement select its branches by testing the value of same variable whereas the if-else construction allow you use a series of expression that may involve unrelated variables and complex expressions. F The if-else is more versatile of the two statements. F The if-else statement can handle floating-point tests also apart from handling integer and character test whereas a switch cannot handle floating-point test. the case labels of switch must be an integer byte,short,int or a char. F The switch case label value must be a constant. so if two or more variables are to be compared,use if-else. F The switch statement is more efficient choice in terms of code used in a situation that supports the nature of switch operation( testing a value against a set of constant).

33 Boolean Operators  The Effect of the Boolean Operators && (and), || (or), and ! (not) on Boolean values

34 Repetitions  while Loops  do Loops  for Loops

35 Looping / Repetitive Statement Some time some portion of the program (one or more statement) needs to be executed repeatedly for fixed no. of time or till a particular condition is being satisfied. This repetitive operation is done through a looping statement. A loop is repetition of one or more instructions, which continues till certain condition is met. Definition

36 Statement 1 Statement 2 Statement n ITERATION / LOOP Looping structures are the statements that execute instructions repeatedly until a certain condition is fulfilled(true). Condition ? true false True

37 for Loops for (initialization; Test-condition; update-statement) { //loop body; } Example: int i; for (i = 0; i<=10; ++i) { cout<<i<<“\n”; }

38 F In for loop contains three parts separated by semicolons(;). F 1. Initialization  Executed only once, in the beginning of the loop. i.e, i=0. F 2.Then the Test Expression(<=10) is evaluated.i.e i<=10 which result into true  3 Since Test Expression(<=10) is true, the body of the loop,i.e., cout<<i<<“\n”; is executed.which prints the current value of I on the same line. F 4.After executing the loop-body, the update expression.e.i., ++i is Executed which increments the value of i. F 5.After the update expression is executed, the test- executed is again evaluated. If it is true, the sequence is repeated from step no. 3.otherwise the loop terminated

39 F Initialization  Executed only once, in the beginning of the loop. F Test Expression  It decides whether the loop- body will be executed or not. if the test expression evaluates to true the loop-body gets executed, otherwise the loop is terminated. that is F Update Expressions)  The update expressions change the values of loop variables. The update expression is executed; at the end of the loop after the loop-body is executed. F The body of the loop  The statements that are executed repeatedly (as long as the test- expression is nonzero) from the body of the loop.

40 F In an Entry-Controlled loop/Top-Tested/Pre-Tested loop  the test expression is evaluated before entering into a loop.  for Examples: For loop and While loop. F In an Exit-Controlled loop/Bottom-Tested/Post- Tested loop  the test expression is evaluated before exiting from the loop.  for Examples: do-While loop. F Do not put a semicolon after the right parenthesis. If you do, the for loop would think that there no statements to execute. it would continue looping, doing nothing each time until the test expression becomes false.

41 for Loop Flow Chart

42 For Loop F Combines the three fundamental parts of every loop –Initialization –Iteration control –Condition update F Most commonly used for count-controlled loops

43 For Syntax for (exp1; exp2; exp3) statement; for (exp1; exp2; exp3) { Statement list } count<=5? total+=dice.roll(); true branch (iterate) false branch (exit) Roll the dice 5 times int total=0; int count=1; count++; initializationcontrolupdatecontrol update initialization Click to view animation stepsAnimation Complete

44 Repeat Statement - for Statement F Infinite Loop using for statement – To stop the loop : break statement, return statement –Nested for statement –Multi dimensional array for ( ; ; ) for (i=0; i<N; ++i) for (j=0; j<M; ++j) matrix[i][j] = 0;

45 Application: Sequences F Find the sum of the first 20 terms of the Fibonacci sequence –1+1+2+3+5+… F This is a common example of a counting loop –Notice that term is declared and initialized in the loop structure and is only defined for the life of the loop // Fibonacci series // fib_a and fib_b are the previous // two terms of the sequence int fib_n, fib_a=1, fib_b=1; int sum=2; //includes first 2 terms for (int term=3; term<=20; term++) { fib_n = fib_a+fib_b; sum += fib_n; fib_a = fib_b; //keep only fib_b fib_b = fib_n; // and fib_n } Cout<<“\n”<<sum;

46 while Loops while (condition) { // loop-body; } First check the conditional expression then executing the repeating statements; Note: A while loop is pre-test loop. It first tests a specified conditional expression and as long as the conditional expression is evaluated to non zero (true), action taken (i.e. statements or block after the loop is executed). A variable scope is the part of program within which you can access the variable. A variable scope is the block of code( that is the part of code enclosed within{}) where the variable has been declared.

47 while Loop Flow Chart START

48 Example: int i = 0; while (i < 100) { cout<<i; i++; }

49 do Loops do { // Loop body; } while (continue-condition); –don’t forget the semicolon! The Do-while loop is an POST-TEST or bottom test loop.that is, First executes its body at least once without testing specified conditional expression and then makes test. the do-while loop terminates when the text expression is evaluated to be False(0).

50 F First, the loop body is executed. F Then the boolean expression is checked. –As long as it is true, the loop is executed again. –If it is false, the loop is exited. F equivalent while statement –Statement(s)_S1 –while (Boolean_Condition) – Statement(s)_S1

51 do Loop Flow Chart

52 F int count = 0; F do F { F cout<<count; F count++; F } while (count < 10); F cout<< count;

53 do-while // Demonstrate the do-while loop. public class DoWhile { public static void main(String args[]) { int n = 10; do { System.out.println("tick " + n); n--; } while(n > 0); } // main } // class

54 Repeat Statement - while Statement F Comparison of for statement and while statement for (i = 0; i < N; ++i) s += i; i = 0; while (i < N) { s += i; ++i; }

55 Jump F C++ supports FOUR jump statements: u break, u continue, and u return. u GOTO F These statements transfer control to another part of your program.

56 =>The GOTO Statement: A goto statement can transfer the control anywhere in the program. the target destination of a goto is marked by a LABEL. The target LABEL and GOTO must appear in the same function. Syntax: goto label: Label:

57 a=0; start: cout<<“\n”<<++a; if(a<50) goto start; { goto last: last:

58 break The Break statement enables a program to skip over part of the code. A break statement terminates the smallest enclosing while,do- while, for or switch statement. Execution resumes at the statement immediately follow the body of the terminated statement. F In C++, the break statement has three uses. F 1.First, as you have seen, it terminates a statement sequence in a switch statement. 2.Second, it can be used to exit innermost loop. 3.Third, it can be used as a "civilized" form of goto.

59 The break Keyword

60 break // Using break to exit a loop. { for(int i=0; i<100; i++) { if(i == 10) break; // terminate loop if i is 10 cout<< i<<“\n”; } cout<<"Loop complete.”; }

61 break // Using break to exit a while loop. int i = 0; while(i < 100) { if(i = = 10) break; // terminate loop if i is 10 cout<<i; i++; } cout<<“Loop complete.”; }

62 break // Using break to exit a while loop. int i = 0; do { if(i = = 10) break; // terminate loop if i is 10 cout<<i; i++; } while(i < 100); cout<<“Loop complete.”; }

63  Labeled break and continue Statements F Labeled block –Set of statements enclosed by {} –Preceded by a label  Labeled break statement –Exit from nested control structures –Proceeds to end of specified labeled block  Labeled continue statement –Skips remaining statements in nested-loop body –Proceeds to beginning of specified labeled block

64 Branch Statement - break Statement F To move control to the out of the block F From of break statement break [label] ; int i = 1; while (true) { if (i = = 3) break; cout<<"This is a " << I << " iteration”; ++i; }

65 continue F you might want to continue running the loop, but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop's end. F In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. F In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression.  continue statement –Skips remaining statements in loop body –Proceeds to next iteration  Used in while, for or do…while statements

66 The continue Keyword

67 Branch Statement – continue Statement F To move control to the start of next repeatation F From of continue statement continue [Label] ; F When used in for statement for (i=0; i<=5; ++i) { if (i % 2 == 0) continue; cout<<"This is a “ << i << " iteration"; }

68 Branch Statement – continue Statement F When used in while statement i = 0; while (i <= 5) { ++i; if (i % 2) == 0) continue; cout<<"This is a odd iteration - “ << i; }

69 Branch Statement – continue Statement F Label continue statement  [LabeledContinue.java] labelName: Rep. St. 1 { Rep. St. 2 { //... continue; //... continue labelName; }

70 continue // Demonstrate continue. for(int i=0; i<10; i++) { cout<<i ; if (i%2 == 0) continue; cout<<“ “; }

71 Nested Loops F You can nest loops of any kind one inside another to any depth. What does this print? for(int i = 10; i > 0; i--) { if (i > 7) { continue; } while (i > 3) { if(i == 5) { break; } cout<<--i; } cout<<i; } 65543216554321

72 continue // Using continue with a label. outer: for (int i=0; i<10; i++) { for(int j=0; j<10; j++) { if(j > i) { cout<<“\n” ; continue outer; } cout<< i * j; } cout<< “” ; }

73 Branch Statement – return Statement F To terminate the execution of method, then pass the method of caller that control F Forms of return statement return; – return; –return ;   [ReturnSt.java]

74 POP QUIZ 1. In the switch statement, which types can expression evaluate to? 2. What must be used to separate each section of a for statement. 3. Which statement causes a program to skip to the next iteration of a loop. 4. Write a for loop that outputs 100-1 in reverse sequence. 5. Write a for loop that outputs all numbers that are divisible by 3 between 0-50. char, byte, short, int semicolons continue

75 return F The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. F The following example illustrates this point. Here, return causes execution to return to the Java run- time system, since it is the run-time system that calls main( ).

76 END


Download ppt "Chapter : 9 Control Statements Control Flow: A control flow Statement regulates the order in which statements get executed. F Flow-order in which the computer."

Similar presentations


Ads by Google