Chapter : 9 Control Statements Control Flow: A control flow Statement regulates the order in which...

Post on 29-Jan-2016

239 views 1 download

Tags:

Transcript of Chapter : 9 Control Statements Control Flow: A control flow Statement regulates the order in which...

Chapter : 9

Control StatementsControl Flow: A control flow Statement regulates

the order in which statements get executed. Flow-order in which the computer executes the

lines of code in our program 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 STATEMENTo 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

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.

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

SEQUENCE The sequence means the statements are

being executed sequentially. This represents default flow of statement.

Statement 1

Statement 3

Statement 2

#include<iostream.h>

#include<conio.h>

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 falseCondition ?

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

Statement 1

false

Statement 1

false

Statement 1

false

Statement 1

false

Body of else

falseCondition ?

Statement 2

Statement 1

Statement 2

C++ provides two types of selection statement: IF SWITCH.

Selection One-way selection(if) Two-way selection(if…else) Compound (block of) statements Multiple selections (nested if) Conditional operator switch structures

One-Way Selection Syntax:if (expression) statement

Expression referred to as decision maker. Statement referred to as action statement. if given condition is TRUE, statement will get

executed.

//Determine the age is eligible for vote.#include<iostream.h>

#include<conio.h>

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

if (booleanExpression/condition) { statement1(s)-for-the-true-case;}else { statement2(s)-for-the-false-case;} 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<iostream.h>#include<conio.h>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.";}

Nested if statement

if (<cond. expr.>) if (<cond. expr.>) // . . . <statement>

if (<cond. expr.1>) <statement 1> else if (<cond. expr.2>) < statement 2> … else if (<cond. expr. n>) < statement n> else < statement>

Multiple Selection: Nested if

Syntax:if (expression1){

statement1;

if (expression2) statement2;else statement3;

}Else {…..}

Else is associated with the most recent incomplete if.

Multiple if statements can be used in place of if…else statements.

May take longer to evaluate.

Conditional (? :) Operator

Ternary operatorSyntax:expression1 ? expression2 : expression3 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 = 1else y = -1;is equivalent toy = (x > 0) ? 1 : -1;

22

THE switch STATEMENT 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.

This SwitchExpression must evaluate to a value of type int, short, byte, or char.

This expression must have a constant value. It may involve named constants and/or literals of the types specified above. It cannot include variables.

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.

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

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 optionalstatement(s)break;

}

Remember a block is a

group of statements enclosed in {}. This is the switch

block.

switch Structures

26

THE switch STATEMENT

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

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

int x = 1; int y = 2; if (SOME_INT == x) { //DO SOMETHING } else if (SOME_INT == y) { //DO SOMETHING ELSE } else { //DEFAULT CONDITION }

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:

int x = 1; int y = 2; switch (SOME_INT) { case x: method1(SOME_INT); break; case y: method2(SOME_INT); break; default: method3(); break; }

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.

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

Differences between the If-else and Switch ST: Switch can only test for equality whereas if can evaluate a

relational or logical expression that is multiple condition. 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. The if-else is more versatile of the two statements. 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.

The switch case label value must be a constant. so if two or more variables are to be compared ,use if-else.

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

In for loop contains three parts separated by semicolons(;).

1. Initialization Executed only once, in the beginning of the loop. i.e, i=0.

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.

4.After executing the loop-body, the update expression .e.i., ++i is Executed which increments the value of i.

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

Initialization Executed only once, in the beginning of the loop.

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

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.

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.

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

Combines the three fundamental parts of every loop– Initialization

– Iteration control

– Condition update 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++;

initialization

control

update

control

updateinitialization

Click to view animation stepsAnimation Complete

Repeat Statement - for Statement

Infinite Loop using for statement

– To stop the loop : break statement, return statement– Nested for statement– Multi dimensional array

for ( ; ; ) <statement>

for (i=0; i<N; ++i) for (j=0; j<M; ++j) matrix[i][j] = 0;

Application: Sequences

Find the sum of the first 20 terms of the Fibonacci sequence– 1+1+2+3+5+…

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 sequenceint fib_n, fib_a=1, fib_b=1;int sum=2; //includes first 2 termsfor (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 Loopswhile (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 ChartSTART

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

First, the loop body is executed. 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.

equivalent while statement– Statement(s)_S1– while (Boolean_Condition)– Statement(s)_S1

do Loop Flow Chart

int count = 0; do { cout<<count; count++; } while (count < 10); 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

Comparison of for statement and while statement

for (i = 0; i < N; ++i) s += i;

i = 0; while (i < N) { s += i; ++i; }

Jump

C++ supports FOUR jump statements: break, continue, and return. GOTO

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:

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

In C++, the break statement has three uses. 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 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

To move control to the out of the block From of break statement

break [label] ;

int i = 1; while (true) { if (i = = 3) break; cout<<"This is a " << I << " iteration”; ++i; }

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

In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop.

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

To move control to the start of next repeatation From of continue statement

continue [Label] ;

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

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

Label continue statement

[LabeledContinue.java]

labelName:labelName: Rep. St. 1 { Rep. St. 2 { // ... continue; // ... continue labelName;continue labelName; } }

continue

// Demonstrate continue.for(int i=0; i<10; i++) {

cout<<i ;if (i%2 == 0) continue;cout<<“ “;

}}

}

Nested Loops 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;

}

6554321

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

To terminate the execution of method, then pass the method of caller that control

Forms of return statement – return; return;

– return <expr.>;return <expr.>;

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

return

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.

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