59
Algorithms and Algorithms and Control Flow Control Flow Structures Structures

3. control statements

Embed Size (px)

Citation preview

Page 1: 3. control statements

Algorithms and Algorithms and Control Flow StructuresControl Flow Structures

Page 2: 3. control statements

AlgorithmsAlgorithms

Page 3: 3. control statements

An algorithm is a sequential collection of actions which is used to solve a problem.

It is a segment of precise steps that describes exactly the tasks to be performed, and the order in which they are to be carried out.

AlgorithmAlgorithm

Page 4: 3. control statements

There Are two ways to outline the precise steps of solving a problem.

Algorithm Flowchart

Algorithm & FlowchartAlgorithm & Flowchart

Page 5: 3. control statements

It is a structured form of the sequential actions to be carried out, which is written in simple English language..

AlgorithmAlgorithm

1. Start2. Declare Variables A, B and C3. Input first number in A4. Input second number in B5. C = A + B6. Print the value of C7. Stop

1. Start2. Declare Variables R and A3. Input Radius in R4. A = 3.14 * R * R5. Print the value of A6. Stop

Algorithm for the program of addition of 2 numbers.

Algorithm for the program of Calculating area of circle.

Page 6: 3. control statements

FlowchartFlowchart A Flowchart is the

graphical representation of the flow of actions used in an algorithm.

Start

Input A

Input B

C = A + B

Declare A, B, C

Display C

Stop

Page 7: 3. control statements

Symbols Used in FlowchartSymbols Used in Flowchart

Start

Input Radius in R

A = 3.14 * R * R

Declare A, R

Display A

Stop

Terminal

Input/Output

Process

Flow Lines

ConditionTrue False

Entry

Decision Making

Page 8: 3. control statements

Control Flow Control Flow Structures/Control StatementsStructures/Control Statements

Page 9: 3. control statements

At a simplistic level a program executes its instructions sequentially in the order in which they are written,

It starts with the first line written in main() function and ends with the last line, always moving from top to bottom.

Control flow structures.Control flow structures.

Page 10: 3. control statements

But most real-time programs are more complex than a simple linear sequence.

Real programs contains numerous code blocks that must be executed only if certain conditions are met, or some code blocks must be executed repeatedly until certain conditions evaluates to false.

Control flow structures.Control flow structures.

Page 11: 3. control statements

Control flow statements are the tools programmers use to make decisions about which statement to execute from the available choices,

It also allows us to change the flow of execution in a program depending upon certain conditions.

Control flow structures.Control flow structures.

Page 12: 3. control statements

Control Flow StructureControl Flow Structure

4 Categories of Control Statements Are Sequential Control Structure Selection / Decision Control Structure Iterative / Repetitive / Loop Control Structure Jump Statements

Page 13: 3. control statements

Start

Input a number in A

B = A * A

Declare A, B

Display B

Stop

Sequential Control StructureSequential Control Structure

Step by Step Flow of Execution

Page 14: 3. control statements

Sequential Control StructureSequential Control Structure

void void mainmain()(){{int int aa, , bb;;

clrscrclrscr();();

printfprintf((“Enter a no : ““Enter a no : “););scanfscanf((“%d”“%d”,&,&aa););

b b = = a * aa * a;;

printfprintf((“\nSquare is“\nSquare is : %d”: %d”, , bb););

getchgetch();();}}

Page 15: 3. control statements

Control flow structuresControl flow structures

Start

Statement

Statement

Statement

Stop

Start

Stop

TestCondition

Some Statement

Sequential Control Structure Selection Control Structure / Decision Making

Some Statement

True False

Page 16: 3. control statements

Control flow structuresControl flow structures

Start

Stop

TestCondition

Some Statement

Selection Control Structure / Decision Making

Some Statement

Start

Stop

TestCondition

Loop Statements

Loop / Repetitive Control Structure

True False

True

False

Page 17: 3. control statements

Control flow structures.Control flow structures.

Sequential Selection/Decision Repetition/Loop Jump Statements

If

switch

? :

(Conditional Operator)

while

do…while

for

break

goto

continue

return

Page 18: 3. control statements

Selection / Decision control statements Selection / Decision control statements allow us to decide whether or not to allow us to decide whether or not to execute a particular statement or a block execute a particular statement or a block of statements enclosed in curly braces.of statements enclosed in curly braces.

It also allows to execute a particular It also allows to execute a particular statement or a block of statement within statement or a block of statement within the available two or more choices.the available two or more choices.

Selection/Decision Control StructureSelection/Decision Control Structure

Page 19: 3. control statements

Decision Control Structure consists ofDecision Control Structure consists of Some type of Condition (T/F Test).Some type of Condition (T/F Test).

One or more block of executable code.One or more block of executable code.

Which block of code will execute depends on Which block of code will execute depends on the result of the condition (true or false)the result of the condition (true or false)

Selection/Decision Control StructureSelection/Decision Control Structure

Page 20: 3. control statements

C supports 3 types of selection control C supports 3 types of selection control statements.statements. ifif

switchswitch

?: (Conditional (Ternary)Operator)?: (Conditional (Ternary)Operator)

Selection/Decision Control StructureSelection/Decision Control Structure

Page 21: 3. control statements

The if statement is used to execute a single statement or a set of statements based on the evaluation of a condition.

It is basically a two-way decision control structure.

The if...else Statement The if...else Statement

Page 22: 3. control statements

if(condition)if(condition){{statement 1;statement 1;

}}elseelse{{statement 2;statement 2;

}}

If…else… the Two-Way Branching If…else… the Two-Way Branching

Statement 1 Statement 2

Condition

Entry

Exit

True False

Page 23: 3. control statements

if(condition)if(condition){{statement 1;statement 1;

}}elseelse{{statement 2;statement 2;

}}

The if...else Statement The if...else Statement

True Part

False Part

Page 24: 3. control statements

The following examples demonstrates use of if...else construct in programs. Find greater number between two nos. Detect entered number is negative or

positive number. Detect entered number is even or odd.

The if...else Statement The if...else Statement

Page 25: 3. control statements

The if...else StatementThe if...else Statement

Start

Input a no in b

Declare a, b

Input a no in a

if a>b

print “a is Greater” print “b is Greater”

Stop

Yes No

Page 26: 3. control statements

void void mainmain()(){{

intint aa, , bb;;

clrscrclrscr();();

printfprintf((“Enter Two Nos\n”“Enter Two Nos\n”););scanfscanf((“%d%d”“%d%d”,&,&aa,&,&bb););

ifif((aa>>bb)){{printfprintf((“First No is greater”“First No is greater”););}}elseelse{{printfprintf((“Second No is greater”“Second No is greater”););}}

}}

The if...else Statement The if...else Statement

Page 27: 3. control statements

The if...else StatementThe if...else Statement

Start

Declare N

Input a number in N

if N>0

print “Negative Number”

Stop

Yes No

print “Positive Number”

Page 28: 3. control statements

The if...else Statement The if...else Statement void void mainmain()(){{

intint nn;;

clrscrclrscr();();

printfprintf((“Enter A No : ”“Enter A No : ”););scanfscanf((“%d”“%d”,&,&nn););

ifif((nn>>00)){{printfprintf((“It’s A Positive Number”“It’s A Positive Number”););}}elseelse{{printfprintf((“It’s A Negative Number”“It’s A Negative Number”););}}

}}

Page 29: 3. control statements

The if...else StatementThe if...else Statement

Start

Declare N

Input a number in N

if N%2==0

print “Even Number” print “Odd Number”

Stop

Yes No

Page 30: 3. control statements

The if...else Statement The if...else Statement void void mainmain()(){{

intint nn;;

clrscrclrscr();();

printfprintf((“Enter A No : ”“Enter A No : ”););scanfscanf((“%d”“%d”,&,&nn););

ifif((nn%%22====00)){{printfprintf((“It’s A Even Number”“It’s A Even Number”););}}elseelse{{printfprintf((“It’s A Odd Number”“It’s A Odd Number”););}}

}}

Page 31: 3. control statements

When the true or false part of an if statement contains another if-else statement, an extremely useful construction is got which is mostly used for multi way decision.

Nesting of if...else Statement Nesting of if...else Statement

Page 32: 3. control statements

if(condition_1)if(condition_1){{

if(condition_2)if(condition_2) {{

Statement-1;Statement-1; }} elseelse {{

Statement-2;Statement-2; }}

}}elseelse{{

Statement-3;Statement-3;}}

Nesting of if...else Statement Nesting of if...else Statement

Stop

Condition 1

Statement-3

Statement-2

False True

Start

Condition 2

Statement-1

False True

Page 33: 3. control statements

if(condition_1)if(condition_1){{

Statement-1;Statement-1;}}elseelse{{

if(condition_2)if(condition_2) {{

Statement-2;Statement-2; }} elseelse {{

Statement-3;Statement-3; }}

}}

Nesting of if...else Statement Nesting of if...else Statement

Stop

Condition 1

Statement-1

Statement-3

False True

Start

Condition 2

Statement-2

False True

Page 34: 3. control statements

if(condition_1)if(condition_1){{

if(condition_2)if(condition_2) {{

Statement1;Statement1; }} elseelse {{

Statement2;Statement2; }}

}}elseelse{{

if(condition_3)if(condition_3) {{

Statement3;Statement3; }} elseelse {{

Statement4;Statement4; }}

}}

Nesting of if...else Statement Nesting of if...else Statement

Condition 1

Stop

Statement-3

False True

Start

Condition 2

Statement-2

False True

Statement-3

Condition 2

Statement-2

Page 35: 3. control statements

Example to detect greater no between two numbers, The program should display appropriate message if both numbers are equal.

Nesting of if...else Statement Nesting of if...else Statement

Page 36: 3. control statements

Start

Declare a, b

Input 2 numbers in a and b

if a>b

print “a is Greater” print “b is Greater”

Stop

Yes No

if a==b

print “Equal Numbers”

Yes No

Nesting of if...else Statement Nesting of if...else Statement

Page 37: 3. control statements

void void mainmain()(){{

intint n1n1, , n2n2;;printfprintf((“Enter Two Nos\n”“Enter Two Nos\n”););scanfscanf((“%d%d”“%d%d”,&,&n1n1,&,&n2n2););ifif((n1n1====n2n2)){{printfprintf((“Both Nos Are Equal”“Both Nos Are Equal”););}}else else {{ifif((n1n1>>n2n2)){{printfprintf((“First No is greater”“First No is greater”););}}elseelse{{printfprintf((“Second No is greater”“Second No is greater”););}}}}

}}

Nesting of if...else Statement Nesting of if...else Statement

Page 38: 3. control statements

if(condition_1)if(condition_1){{

Statement1;Statement1;}}elseelse{{

if(condition_2)if(condition_2){{

Statement2;Statement2;}}elseelse{{

Statement3;Statement3;}}

}}

The if...else...if Ladder The if...else...if Ladder

if(condition_1)if(condition_1){{

Statement1;Statement1;}}else if(condition_2)else if(condition_2){{

Statement2;Statement2;}}elseelse{{

Statement3;Statement3;}}

Page 39: 3. control statements

Simple If

if(test){

statement;}

Various forms of if statementVarious forms of if statement

If...Else

if(test){

statement;}else{

statement;}

Nested If

if(test1){

if(test2){statement;}else{statement;}

}else{

statement;}

If…else if Ladder

if(test1){

statement;}else if(test2){

statement;}else if(test3){

statement;}else{

statement;}

Page 40: 3. control statements

void void mainmain()(){{intint n1n1, , n2n2;;

printfprintf((“Enter Two Nos\n”“Enter Two Nos\n”););scanfscanf((“%d%d”“%d%d”,&,&n1n1,&,&n2n2););

ifif((n1n1====n2n2))printfprintf((“Both Nos Are Equal”“Both Nos Are Equal”););else ifelse if((n1n1>>n2n2))printfprintf((“First No is greater”“First No is greater”););elseelseprintfprintf((“Second No is greater”“Second No is greater”););

}}

The if...else...if Ladder The if...else...if Ladder

Page 41: 3. control statements

Instead of using if-else-if ladder, the switch construct can be used to handle multiple choices, such as menu options.

The objective is to check several possible constant values for an expression.

Switch control structure allows us to make a decision from the number of choices called as ‘Cases’.

The switch-case Statement The switch-case Statement

Page 42: 3. control statements

The switch-case Statement The switch-case Statement switch(integer expression){

case value_1:executable

statement;break;

case value_2:executable

statement;break;

case value_3:executable

statement;break;

default:executable

statement;}

Start

Case 1

Case 2

Case 3

Stop

Statement 1

Statement 2

True

False

Statement 4Default

True

False

Statement 1True

False

Page 43: 3. control statements

switch(integer expression){

case value_1:executable

statement;break;

case value_2:executable

statement;break;

case value_3:executable

statement;break;

default:executable

statement;}

Even if there are multiple statements in front of a case, there is no need to enclose them within pair of curly braces.

Points to remember about SwitchPoints to remember about Switch

Page 44: 3. control statements

switch(integer expression){

case value_1:executable

statement;break;

case value_2:executable

statement;break;

case value_3:executable

statement;break;

}

It’s not necessary to have a ‘default’ case in switch construct.

In such case program simply falls through the entire switch and continues with the next instruction, that follows the closing brace of switch

Points to remember about SwitchPoints to remember about Switch

Page 45: 3. control statements

void main(){int a;printf(“Enter A Number : “);scanf(“%d”, &a);

switch(a%2){

case 0:printf(“Even

Number”);break;

case 1:printf(“Odd

Number”);break;

}}

We can check the value of any integer expression in a switch.

Thus the following switch statements are legal switch (i+j) switch (a*b/c) switch (a%2)

Points to remember about SwitchPoints to remember about Switch

Page 46: 3. control statements

switch(integer expression){

case value_1:executable

statement;break;

case value_2:executable

statement;break;

case value_3:executable

statement;break;

default:executable

statement;}

The switch statement is very useful while writing menu driven programs.

Points to remember about SwitchPoints to remember about Switch

Page 47: 3. control statements

Is switch a replacement for if? Yes

• Because it provides a better way of writing programs as compared to if.

No• Because in certain situations we don’t have any

choice but to use if.• The major limitation of switch is that one cannot have

a case in switch which looks like case i<=15;

• All that we can have after a case keyword is an integer constant.

Points to remember about SwitchPoints to remember about Switch

Page 48: 3. control statements

There are some things which u cannot do with a switch, these are. A float expression cannot be tested using

switch, because switch can compare only char or integer type of variable/expression.

You cannot use relational operator in switch.• For example the case is wrong like, case <=15

Cases can never have variables expressions• For example the case is wrong like, case i+j;

Switch versus if-else ladderSwitch versus if-else ladder

Page 49: 3. control statements

The Conditional “ ? : ” operator is useful The Conditional “ ? : ” operator is useful for making two way decisions. It can be for making two way decisions. It can be used to replace an if…else statement.used to replace an if…else statement.

This operator is a combination of ? and :This operator is a combination of ? and : This operator used three operands. That’s This operator used three operands. That’s

why its called as ‘Ternary Operator’why its called as ‘Ternary Operator’

Condition ? Expression1 : expression2;

The ? : OperatorThe ? : Operator

Page 50: 3. control statements

Condition ? Expression1 : expression2;

The condition evaluated first, if the The condition evaluated first, if the condition is true then expression1 is condition is true then expression1 is executed and its value is returned, and if executed and its value is returned, and if the condition is false then expression2 is the condition is false then expression2 is executed and its values is returned.executed and its values is returned.

The ? : OperatorThe ? : Operator

Page 51: 3. control statements

Consider the following codeConsider the following code

The ? : OperatorThe ? : Operator

if(a>b)if(a>b)max = max =

a;a;elseelse

max = max = b;b; Above if can be replaced by conditional Above if can be replaced by conditional

operator as below.operator as below.

max = a>b ? a : b;

Page 52: 3. control statements

A Segment of program code that is A Segment of program code that is executed repeatedly is called a loop. The executed repeatedly is called a loop. The repetition is done until some condition for repetition is done until some condition for termination of the loop is satisfied.termination of the loop is satisfied.

A Loop structure essentially contains.A Loop structure essentially contains. A Test ConditionA Test Condition Loop StatementsLoop Statements

Iterative Control StructureIterative Control Structure

Page 53: 3. control statements

while loopwhile loop do...while loopdo...while loop for loopfor loop

Iterative Control StructureIterative Control Structure

Page 54: 3. control statements

Iterative Control StructureIterative Control Structure

Condition

Loop Statements

True

False

Stop

Entry

while(condition)while(condition){{

loop Statementsloop Statements}}

Page 55: 3. control statements

void void mainmain()(){{

int int numnum==11;;

whilewhile((numnum<=<=1010)) {{

printfprintf((“\n%d”“\n%d”,,numnum););num num = = numnum + + 11;;

} } } }

Iterative Control StructureIterative Control Structure

This Iteration procedure takes This Iteration procedure takes place in four stepsplace in four steps

Initializing Loop Control VariableInitializing Loop Control Variable Testing The ConditionTesting The Condition Execution of Loop StatementsExecution of Loop Statements Changing value of the control Changing value of the control

variablevariable

In this construct, condition is tested at the beginning of the In this construct, condition is tested at the beginning of the loop, and if loop condition satisfies then statements in the loop, and if loop condition satisfies then statements in the loop body will execute.loop body will execute.

Page 56: 3. control statements

Depending upon when the condition is Depending upon when the condition is tested, loops are of two types.tested, loops are of two types.

Iterative Control StructureIterative Control Structure

Condition

Loop Statements

True

False

Stop

Condition

Loop Statements

True

False

Stop

Entry Controlled Loop / Pre Tested Loop Exit Controlled Loop / Post Tested Loop

Page 57: 3. control statements

void void mainmain()(){{

int int numnum==11;;

dodo{{

printfprintf((“\n%d”“\n%d”,,numnum););num num = = numnum + + 11;;

}}whilewhile((numnum<=<=1010); ); } }

Iterative Control StructureIterative Control Structure

This Iteration procedure takes This Iteration procedure takes place in four stepsplace in four steps

Initializing Loop Control VariableInitializing Loop Control Variable Execution of Loop StatementsExecution of Loop Statements Changing value of the control Changing value of the control

variablevariable Testing The ConditionTesting The Condition

In this construct, the statements in the loop are executed and In this construct, the statements in the loop are executed and the condition test is done at the end of the loop. the condition test is done at the end of the loop.

Page 58: 3. control statements

void void mainmain()(){{

int int numnum;;

forfor((numnum==11; ; numnum<=<=1010; ; numnum++ +)+) {{

printfprintf((“\n%d”“\n%d”,,numnum););} }

}}

Iterative Control StructureIterative Control Structure

forfor((numnum==11; ; numnum<=<=1010; ; numnum++ +)+) {{

printfprintf((“\n%d”“\n%d”,,numnum););}}

Initialization Condition Increment

Page 59: 3. control statements

Iterative Control StructureIterative Control Structure

forfor((initialiseinitialise; ; testtest; ; incrementincrement)){{

statementstatement;;}}