flow of control by deepak lakhlan

59
Flow Of Control Sanjay Jhaveri, PGT(Comp. Sci.)

Upload: deepak-lakhlan

Post on 08-Jan-2017

106 views

Category:

Education


0 download

TRANSCRIPT

Flow Of ControlSanjay Jhaveri, PGT(Comp. Sci.)

Contents

1. Introduction 2. Explanation Of Important Points 3. Classwork 4. Homework 5. A Special Note 6. Author

Introduction

Generally a program executes its statements from beginning to end. But not many programs execute all their statements in strict order from beginning to end. Most programs decide what to do in response to changing circumstances. These programs not only stores data but they also manipulate data in terms of consolidating, rearranging, modifying data. To perform their manipulative miracles, programs need tools for performing repetitive actions and for making decisions. Java of course provides such tools by providing statements to attain so. Such statements are called program flow control statements.

This PPT is going to discuss various program flow control statements viz. selection statements, iteration statements and jump statements.

Every programming language provides some constructs which are necessary for it to be called as programming language.

Programming Constructs

In a program, statements may be executed sequentially, selectively or iteratively.

Every programming language provides constructs support sequence, selection or iteration.

Construct Types:- 1. Sequence 2. Selection, & 3. Iteration

Sequence Construct

The sequence construct means the statements are being executed sequentially. This represents the default flow of statement. (See Fig.)

Statement 1

Statement 2

Statement 3

Sequence Construct Contd..

Every Java function execution begins with its first statement. Each statement in turn is executed(sequence construct). When the final statement of the function is executed, the function is done. This construct specifies the normal flow of control in a program and is the simplest one.

Selection Construct

The selection construct means the execution of statement(s) depending upon a condition-test. If a condition evaluates to true, a course-of-action (a set of statements) is followed otherwise another course-of-action (a different set of statements) is followed. This construct (selection construct) is also called decision construct because it helps in making decision about which set-of-statements is to be executed. (See Fig.)

ExecutionTypes

Selection Construct Contd.. The execution of selection construct is as follow:-

Condition ? Statement 1 Statement 2

Statement 1

Statement 2

Iteration Construct

Iteration construct means repetition of set of statements depending upon a condition test. Till the time of condition is true. ( or false depending upon the loop). A set of statements are repeated again and again. As soon as the condition become false (or true), the repetition stops. The iteration condition is also called ”Looping Construct”. (See Fig.)

ExecutionTypes

Iteration Construct Contd..Execution:-

Condition ? False

The Loop BodyStatement 1

Statement 2

True

Types of Selection Statement

1. if Statement 2. if-else Statement 3. ?: Statement 4. Switch Statement

if Statement

An if statement test a particular condition, if the condition evaluated to true, a course of action is followed, i.e. a statement or a set of statement is executed. Otherwise if the condition evaluated to false then the course of action is ignored.

Syntax:- if (Boolean-expression/condition)

statement 1; The statement may consist of single or compound statements. If the condition evaluates non zero that is true then the statement 1 is executed otherwise if the condition evaluates zero i.e. false then the statement 1 is ignored.Example

Example of if Statement

Q. Write code to test whether a number stored in variable Num is positive or not. Make use of if statement only. You don’t need to write class/method for it.

Solution:-: if (Num > 0) label1.setText(“Number Is Positive”) ;:

NOTE:- If this condition evaluates to false then no message will be shown.

Flow Chart

Flow chart of if statementTest

Expression ?

true

Body of if

false

If-else Statement

Syntax:-if (expression)

statement 1 ;else

statement 2 ; If the expression evaluates to true i.e., a nonzero value, the statement 1 is executed, otherwise, statement 2 is executed. The statement 1 & statement 2 can be a single statement, or a compound statement, or a null statement.

Flow Chart

Flow chart of if-else statement

True

Test Expression

?

Body of if

False Body of else

Example

Example of if-else statement

Q. Code to test whether a number given in text field NumTF is positive or not.

Solution:-int Num ;Num = Integer.parseInt(NumTF.getText()) ;if ( Num > 0)

label1.setText(“Number Is Positive”) ;else

label1.setText(“Number Is Negative Or Zero”) ;

Nested if A nested if is an if that has another if in its body or in its else body. Example:-

if (expression 1){

if (expression 1)statement 1

elsestatement 2

}else body of else

The Dangling Else Problem The nested if-else statement introduces a source of potential

ambiguity referred to as dangling-else problem. This problem arises when in a nested if statement, number of ifs is more than the number of else clauses.

Tip:- In nested if statement, a dangling else statement goes with the preceding unmatched if statement.

?: statement (Alternative to if)

Java has an operator that can be used as an alternative to if statement. You are familiar with this operator, the conditional operator ?: . This operator can be used to replace if-else statements of the general form:

if (expression1)expression2 ;else expression 3 ;

The above form of if can be alternatively written using ?: as follows :expression1 ? Expression2 : expression 3 ;

Example

Example of ?: statement

int c ; If (a > b)

C = a ;ElseC = b ;

Can be alternatively written as

Int c = a > b ?a : b ;

See how simple and compact your code has become

If v/s ?:

If v/s ?:

Compared to if-else sequence, ?: offers more concise, clean and compact code, but it is less obvious as compared to if.

Another difference is that the conditional operator ?: produces an expression, and hence a single value can be assigned or incorporated into a larger expression, whereas, if is more flexible. The if statement can have multiple statements, multiple assignments and expression(in form of a compound statement) in its body.

When ?: operator is used in its nested form, it becomes complex and difficult to understand. This form of ?: is generally used to conceal the purpose of code.

Switch Statement Java provides a multiple-branch selection statement known as switch.

This selection statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statement associated with that constant are executed.

Syntax:-switch (expression){ case constant1 : statement sequence 1 ;break ;case constant2 : statement sequence 2 ;break ;case constant n-1 : statement sequence n-1 ; break ;[ default : statement sequence n] ;} Example

Example of switch statement Q. Write code to translate to the equivalent name of the day(e.g. 1 to Sunday, 2 to Monday). //assuming day number is available in int variable dow

switch (dow) {case 1 : ans = “Sunday” ;break ;case 2 : ans = “Monday” ;break ;case 3 : ans = “Tuesday” ;break ;case 4 : ans = “Wednesday” ;break ;case 5 : ans = “Thursday” ;break ;case 6 : ans = “Friday” ;break ;case 7 : ans = “Saturday” ;break ;default : ans = “Invalid Day Number” ;}outputLabel.setText(“Weekday for the day number”+dow+”is:”+ans) ;

Switch Statement Contd..

The expression is evaluated and its values are matched against the values of the constants specified in the case statements. When the match is found, the statement sequence associated with that case is executed until the break statement or the end of switch statement is reached. If a case statement does not include break statement then the control continues right on the next case statement(s) until either a break is encountered or end of switch is reached this situation(missing break in case statement) is known as “fall through”.

The default statement gets executed when there is no match found. The default is optional, and if it is missing then no action takes place if all matches fail.

NOTE:- Always put break statement after the last case statement in switch.

Switch v/s if-else

The switch statement differs from the if statement in that switch can only test for equality where as if can evaluate a relational or logical expressions i.e multiple conditions.

The switch statement selects its branches by testing the value of same variable (against the set of constants) where as the if else construction lets you to use a series of expressions that may involve unrelated variables and complex expressions.

The if-else is more versatile of two statements where as switch cannot. Each switch case label must be a single value.

The if-else statement can handle floating point tests also apart from integer and character tests where as switch cannot handle floating point tests. The case labels of switch must be an integer or character.

Types of Iteration Statement

The iteration statements allow a set of instructions to be performed until a certain condition is fulfilled. The iteration statements are also called loops or looping statements.

Java provides three kinds of loops:-1. For loops2. While loops, &3. Do-while loops

Elements that control a loop

Every loop has its elements that control and govern its execution. Generally a loop has four elements that have different purpose, they are:-

1. Initialization Expression:- Before entering in a loop, its control variable must be initialized. The initialization expression executed at only once.

2. Test Expression:- The test expression is an expression whose truth values decides whether the loop-body will be executed or bot. If the test expression evaluates to true i.e., the loop body gets executed, otherwise the loop gets terminated.

Elements that control a loop contd..

3. Update Expression(s):- The update expression change the value(s) of loop variable(s). The update expression(s) is executed, at the end of the loop after loop body is executed.

4. Body Of The Loop:- The Statement that are executed repeatedly as long as the value of expression is non zero. If it evaluates to zero then the loop is terminated.

The for Loop-Fixed Number of Iterations The for loop is the easiest to understand of Java loops. All its loop

control elements are gathered in one place(on the top of loop), while in the other loop construction of Java, they(Top-control elements) are scattered about the program.

The general form (Syntax) of the for loop statement is:-for (initialization expression(s) ; test expression ; update

expression(s))body-of-the-loop ;

ExampleFlow Chart

The for Loop’s Example

Q. Write code using for loop to print numbers from 1 to 10.

Solution:- int I = 0 ;for( I = 1 ; I <= 10 ; ++i) {

System.out.print( I + “”) ;}

Upon execution, the above will yield :1 2 3 4 5 6 7 8

9 10

The for Loop’s Flow Chart

Test Expression

?

InitializationExpression(s)

ExitFalse

Body of the loop

Update Expression(s)

True

The while Loop-Entry Controlled Loop The second loop available in Java is the while loop. The while loop is

an entry controlled loop. The syntax of a while loop is:-

while (expression)Loop-body

where loop body may contain the single statement or set of statements (compound statement) or an empty statement. The loop iterates while the expression evaluates to true, when expression becomes false, the loop terminates.

Example

The while loop’s Example

Q. Code to evaluate the factorial of an integer using a while loop. Solution:-

//assuming that number whose factorial is to be calculated is stored in variable num

long i = 0, fact = 1 ;i = num ;while(num != 0) {fact = fact*num ;--num ;}System.out.printIn(“The factorial of”+i+”is”+fact) ;

The do-while Loop-Exit Controlled Loop Unlike the for and while the do-while loop is an exit controlled loop

i.e., it evaluates its test expression at the bottom of the loop after executing its loop-body statements.

The syntax of the do-while loop is:-do { statement ;} while (text-expression) ;

Example

The do-while loop’s Example

Q. Code to display Count down from 10 to 0 and then display “HAPPY LOOPING”.

Solution:-int x = 10 ;do {

System.out.printIn(x) ;x-- ;

} while (x >= 0) ;System.out.printIn (“HAPPY LOOPING”) ;

Comparison Of Loops

The for loop is appropriate when you know in advance how many times the loop will be executed.

The other two loops while and do-while are more suitable in the situations where it is known before –hand when the loop will terminate. The while should be preferred when you may not want to execute the loop body even once (in case test condition is false), and the do-while loop should be preferred when you are sure you want to execute the loop body at least once.

Jump Statements

The jump statement unconditionally transfer program control within a function. Java has three statements that perform an unconditional branch : return, break and continue. Of these, you may use return anywhere in the program whereas break and continue are used inside smallest enclosings like loop etc. In addition to the above three, Java provides a standard library function System.exit () that helps you break out of a program.

Classwork

Q.

Homework

Q. Write a short program to input a digit and print it in words. Q. What are the three constructs that governs statement flow? Q. What is the significance of a default clause in switch statement? Q. What is the problem of dangling-else ? When does it arise? What is

the default dangling-else matching and how it can be overridden? Q. Design a GUI application that will help students to know their final

grade by accepting percentage marks?

A Special Note

Don’t worry about what people say behind your back. They are the people who are finding faults in your life instead of fixing their own faults.

A Project By Deepak Lakhlan

Thank you for giving your valuable time for watching this presentation.

Hope you liked it.