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.

Slides:



Advertisements
Similar presentations
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Advertisements

Control Structures Corresponds with Chapters 3 and 4.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
UNIT II Decision Making And Branching Decision Making And Looping
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
OBJECTIVES  Illustration of the Concept of Control Flow  Types of Control Flow  Knowledge about conditional and repetitive statements.  Make more.
Expressions An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Lecture 4 Control Structures MIT – AITI What are Control Structures? Control structures are a way to alter the natural sequence of execution in.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
We have to discuss following:-  Statements  Statement flow control  Selection statement  Iteration statement.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Lecture 4b Repeating With Loops
‘C’ Programming Khalid Jamal.
REPETITION CONTROL STRUCTURE
The switch Statement, and Introduction to Looping
Statements (6 of 6) A statement causes an action to be performed by the program. It translates directly into one or more executable computer instructions.
Chapter 5: Control Statements
JavaScript: Control Statements.
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Chapter 4: Control Structures I (Selection)
Chapter8: Statement-Level Control Structures April 9, 2019
Control Statements Paritosh Srivastava.
CSC215 Lecture Control Flow.
Presentation transcript:

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.

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

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

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

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

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

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

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

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

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.

//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

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.

Two-Way Selection

//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(); }

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

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."; }

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

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.

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.

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

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.

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 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.

switch Structures

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; }

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 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; }

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 }

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 }

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).

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).

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

Repetitions  while Loops  do Loops  for Loops

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

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

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

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

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.

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.

for Loop Flow Chart

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

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

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;

Application: Sequences F Find the sum of the first 20 terms of the Fibonacci sequence – … 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;

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.

while Loop Flow Chart START

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

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).

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

do Loop Flow Chart

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

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

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; }

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.

=>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:

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

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.

The break Keyword

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.”; }

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.”; }

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.”; }

 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

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; }

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

The continue Keyword

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"; }

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; }

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

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

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; }

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<< “” ; }

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]

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 in reverse sequence. 5. Write a for loop that outputs all numbers that are divisible by 3 between char, byte, short, int semicolons continue

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( ).

END