control flow of program

53
CS101 Introduction to computing CS101 Introduction to computing Control Flow of Program Control Flow of Program A. Sahu and S. V .Rao Dept of Comp. Sc. & Engg. Dept of Comp. Sc. & Engg. Indian Institute of Technology Guwahati 1

Upload: others

Post on 18-Jan-2022

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Control Flow of Program

CS101 Introduction to computingCS101 Introduction to computing 

Control Flow of ProgramControl Flow of Program

A. Sahu and S. V .RaoDept of Comp. Sc. & Engg.Dept of Comp. Sc. & Engg.

Indian Institute of Technology Guwahati

1

Page 2: Control Flow of Program

Outline• Program flow control

–If‐else–Switch case–Switch case–Looping : while, for, do‐while 

• Looping : while, for, do‐while 

• Problem Solving• Problem Solving

2

Page 3: Control Flow of Program

Structured Programming• All programs can be written in terms of only three control structures– Sequence, selection and repetition

• The sequence structure – Unless otherwise directed, the statements are executed in the order in which they are written. 

Th l i• The selection structure – Used to choose among alternative courses of actionaction. 

• The repetition structure– Allows an action to be repeated while someAllows an action to be repeated while some condition remains true.

Page 4: Control Flow of Program

Sequential ExecutionSequential Execution

Statement 1

Statement 2

...

Statement n

Page 5: Control Flow of Program

Compute the resonant frequency of an RLC circuitfrequency of an RLC circuit

#include <stdio.h>#include <math h>#include <math.h>int main() {

double l, c, omega, f; printf("Enter inductance in mH: ");  //S1scanf("%lf", &l); //S2printf("Enter capacitance in microF: ");  //S4p ( p ); //scanf("%lf", &c);  //S5omega = 1.0/sqrt((l.0/1000)*(c/1000000)); //S6f = omega / (2 * M PI); //S7f = omega / (2 * M_PI);  //S7printf("Resonant freq: %.2f\n", f);  //S8return 0; //S9

}

Page 6: Control Flow of Program

Selective Execution : Flow chart( l f)(only if)

BooleanBoolean true

ExpressionExpression

Statement 1

Statement S

Page 7: Control Flow of Program

Selective Execution : Flow chartSelective Execution : Flow chart

BooleanBooleanExpr

true false

Expr

statement 1 statement 2

Page 8: Control Flow of Program

Selection: the if‐else statementSelection:  the if else statementif ( condition ){

statement(s)/*if clause */}}else {

t t t( ) /* l l */statement(s) /*else clause */}

Page 9: Control Flow of Program

Nesting of if‐else Statementsgif ( condition1 ){

statement(s)}else if ( condition2 )else if ( condition2 ) {

statement(s)}}. . . /* more else clauses may be here */else{{

statement(s) /* the default case */}

Page 10: Control Flow of Program

Bad Example : 2 if 1 elseif ( n > 0 )

if ( a > b )az=a;

else z=b;

if ( n > 0 ){if (a> b)

if ( n > 0 )if ( a > b )

; if (a> b)z=a;

}elseif ( a > b )

z=a;else

else z=b;

z=b;

Indentation will not ensure result : elsematch with closest if Code of Red box behaves like Code of Green box 

Page 11: Control Flow of Program

In Assembly language: No if‐else• Assembly language 

– No support for [if else, No for loop, No while loop]– All higher construct get implemented 

using  if and goto statement goto statement  uses Label

• If else get converted to if gotog g

if(a> b )if(a>b) goto L1:z=b;

z=a;else z=b;NextStmt;

z b;goto L2:

L1: z=a;

11

NextStmt; L1: z a;L2: Next stmt

Page 12: Control Flow of Program

In Assembly language: No if‐elseif(a>b) goto L1:if(a>b) goto L1:

bbz=b;

2

z=b;

2goto L2:L1:

goto L2:L1:

z=a;L2:

z=a;L2:

12

Next stmtNext stmt

Page 13: Control Flow of Program

Multi‐way if else : switch caseMulti way if else : switch case• If‐else : two way, if part and else part • To make it multi‐way: nested if‐else

– Confusing, lengthy

• C language provide – Switch caseSwitch case– Multi way selection– Range multi‐way selectionRange multi way selection 

13

Page 14: Control Flow of Program

The switch Multiple‐Selection Structure• switch

– Useful when expression is tested for multiple values– Consists of a series of case labels and an optional default case

– break is (almost always) necessaryswitch (<expression>){case <Value1> :case <Value1> :

<Action/Stmts for Value1>; break; case <Value2> :

<Action/Stmts for Value2>; break; . . . default: <Action/Stmts for DefaultValue>; / ;

break; }

Page 15: Control Flow of Program

Flowchart of Switch Statement 

truecase acase a

action(s) break

case bcase b

action(s)break

false true

f l

.

false

.

.case z case z

action(s)break

true

action(s)

default

false

action(s)

Page 16: Control Flow of Program

Multiway Switch Selection example int main(){//simple calculator int a=50,b=10, R;char choice;

int main(){//simple calculator int a=50,b=10, R;char choice;char choice;printf(“Enter choice”);scanf(“%c”,&choice);

char choice;printf(“Enter choice”);scanf(“%c”,&choice);

switch (choice){case ‘a’ : R=a+b; printf(“R=%d”,R); break;

switch (choice){case ‘a’ : R=a+b; printf(“R=%d”,R); break; case ‘s’ : R=a-b; printf(“R=%d”,R); break; case ‘m’ : R=a*b; printf(“R=%d”,R); break;case ‘d’ : R=a/b; printf(“R=%d”,R); break;

case ‘s’ : R=a-b; printf(“R=%d”,R); break; case ‘m’ : R=a*b; printf(“R=%d”,R); break;case ‘d’ : R=a/b; printf(“R=%d”,R); break;case d : R a/b; printf( R %d ,R); break;default : printf(“Wrong choice”) ; break;}t 0

case d : R a/b; printf( R %d ,R); break;default : printf(“Wrong choice”) ; break;}t 0return 0;

}return 0;}

Page 17: Control Flow of Program

Multiway Switch Selection example int main(){//simple calculator int a=50,b=10, R;char choice;

int main(){//simple calculator int a=50,b=10, R;char choice;char choice;printf(“Enter choice”);scanf(“%c”,&choice);

char choice;printf(“Enter choice”);scanf(“%c”,&choice);

switch (choice){case ‘a’ : R=a+b; printf(“R=%d”,R); break;

switch (choice){case ‘a’ : R=a+b; printf(“R=%d”,R); break; case ‘s’ : R=a-b; printf(“R=%d”,R); break; case ‘m’ : R=a*b; printf(“R=%d”,R); break;case ‘d’ : R=a/b; printf(“R=%d”,R); break;

case ‘s’ : R=a-b; printf(“R=%d”,R); break; case ‘m’ : R=a*b; printf(“R=%d”,R); break;case ‘d’ : R=a/b; printf(“R=%d”,R); break;case d : R a/b; printf( R %d ,R); break;default : printf(“Wrong choice”) ; break;}t 0

case d : R a/b; printf( R %d ,R); break;default : printf(“Wrong choice”) ; break;}t 0return 0;

}return 0;}

Page 18: Control Flow of Program

Multiway Switch Selection example 

switch (choice){switch (choice){case ‘A’ : // no break, work for both A & a

// next statement automatically // get executed

case ‘A’ : // no break, work for both A & a// next statement automatically // get executed // g

case ‘a’ : R=a+b; printf(“R=%d”,R); break; case ‘S’ :case ‘s’ : R=a-b; printf(“R=%d” R); break;

// gcase ‘a’ : R=a+b; printf(“R=%d”,R); break; case ‘S’ :case ‘s’ : R=a-b; printf(“R=%d” R); break;case s : R=a-b; printf( R=%d ,R); break; case ‘M’ :case ‘m’ : R=a*b; printf(“R=%d”,R); break;

case s : R=a-b; printf( R=%d ,R); break; case ‘M’ :case ‘m’ : R=a*b; printf(“R=%d”,R); break;case ‘D’ :case ‘d’ : R=a/b; printf(“R=%d”,R); break;default : printf(“Wrong choice”) ; break;

case ‘D’ :case ‘d’ : R=a/b; printf(“R=%d”,R); break;default : printf(“Wrong choice”) ; break;p g}

p g}

Page 19: Control Flow of Program

Range Multiway Switch Selection example i ti tint x;scanf(“%d”,&x);switch (x){

int x;scanf(“%d”,&x);switch (x){case 1 ... 20:// 1 space three dots space 20

printf(“You entered >=1 and <=20”); break;

case 1 ... 20:// 1 space three dots space 20 printf(“You entered >=1 and <=20”); break;break;

case 21 ... 30 :printf(“You entered >=21 and <=30”); b k

break; case 21 ... 30 :

printf(“You entered >=21 and <=30”); b kbreak;

default : printf(“You entered < 1 and >31”) ;

break; default :

printf(“You entered < 1 and >31”) ; break;

}break;

}

Syntax = case <low_range> ... <high_range> :

Page 20: Control Flow of Program

Loops and RepetitionLoops and Repetition

• Loops in programs allow us to repeat blocks• Loops in programs allow us to repeat blocks of code U f l f• Useful for:– Counting

i i i i i– Repetitive activities– Programs that never end

• Because of looping feature of computer – We also name “Computer” as “Machine” (which can do repetitive mechanical work for us)do repetitive mechanical work for us)

Page 21: Control Flow of Program

Three Types of Loops/Repetition in CThree Types of Loops/Repetition in C 

• while–top‐tested loop (pretest)f• for–counting loopcounting loop–forever‐sentinel

• do–bottom tested loop (posttest)–bottom‐tested loop (posttest)

Page 22: Control Flow of Program

The while loopTop‐tested loop (pre‐test)

while (condition)

Note that as in IF selection only one

( )statement;

Note that, as in IF selection, only one statement is executed. You need a block to repeat more than one statement (using { })repeat more than one statement (using { })

while (condition){while (condition){statements;

}}

Page 23: Control Flow of Program

while(condition)statement;

condition

truef l

statements

false

statements

Page 24: Control Flow of Program

Similar to the if statement

• Check the Boolean condition• If true, execute the statement/block

Repeat the above until the Boolean is false

Page 25: Control Flow of Program

In Assembly language: No while loop• Assembly language 

– No support for [while loop]– All higher construct get implemented 

using  if and goto statement goto statement  uses Label

• while get converted to if gotog g

while(Cond){ L1:if(!Cond)goto L2;STMTS;

}Next STMT;

L1:if(!Cond)goto L2; STMTS;goto L1;

25

Next STMT; g ;L2:Next STMT

Page 26: Control Flow of Program

While statement using goto

L1:if(!C)goto L2L1:if(!C)goto L2

condition

L1:if(!C)goto L2

Statements

L1:if(!C)goto L2

Statementstrue false

Statements

goto L1

Statements

goto L1statements goto L1

L2

goto L1

L2L2:L2:

Page 27: Control Flow of Program

While loop

ditiditifalse

while(condition)statement;

conditioncondition

truewhile(condition){statement1;

statementsstatementsstatement1;statement2;

}}

int i = 10;hile(i > 0) {while(i > 0) {

printf("i=%d\n", i);i = i ‐ 1;i = i  1;

}

Page 28: Control Flow of Program

Forever loops and never loopsB th diti l b•Because the conditional can be 

–“always true” : you can get a loop that runs forever– or “always false”, you can get a loop  never runs at all.

i t t 0int count=0;while(count !=0) 

i tf(“Hi \ ”) // i tprintf(“Hi .. \n”);// never prints

hil ( t 1)//i idi !!!while (count=1)//insidious error!!!count = 0;   

What is wrong with these statements?

Page 29: Control Flow of Program

How to count using while1. First, outside the loop, initialize the counter 

variable2. Test for the counter’s value in the Boolean3 Do the body of the loop3. Do the body of the loop4. Last thing in the body should change the value 

f th t !of the counter!1. i = 1;2 while(i <= 10) {2. while(i <= 10)  {3. printf("i=%d\n", i);4. i = i + 1;;

}

Page 30: Control Flow of Program

The for loop• The while loop is pretty general. 

–Anything that can be done using repetition can be done with a while loop

• Because counting is so common–There is a specialized construct–There is a specialized construct –Called :  for loop.

• for loop–Makes it easy to set up a counting loop–Makes it easy to set up a counting loop

Page 31: Control Flow of Program

For loop:  Three partsThree parts to a for loop (just like the while):while):– Set the initial value for the counterS t th diti f th t– Set the condition for the counter

– Set how the counter changes each time through the loop

f ( ){for ( count=1; count<=5;  count++ ){statement;

}}

Page 32: Control Flow of Program

For Loop: Examplef ( )for(count=1; count<=5; count++)

printf(“count=%d\n”, count);

count = 1

falsecount <= 5count <= 5true

printf

count ++

Page 33: Control Flow of Program

For loop:  Ascending for

for ( ctrl_var=init_val; ctrl ar < limit al

ctrl_var = init_val

 ctrl_var <=limit_val;    ctrl_var++) {             statement;

cntrl varcntrl vartrue false

statement;}

<= limit_valcntrl_var<= limit_val

true false

statement

lctrl_var ++

Page 34: Control Flow of Program

For Loop : Descending for

for ( ctrl_var=init_val; ctrl ar > limit al

ctrl var = init val

 ctrl_var >=limit_val;    ctrl_var‐‐) {             statement;ctrl_var = init_val statement;

}

cntrl_var>= limit_valcntrl_var>= limit_val

true false

statement

ctrl_var ‐‐

Page 35: Control Flow of Program

Precaution in CodingPrecaution in Coding

• Dangerous to alter within the body of g ythe loopcontrol variable ctrl var– control variable ctrl_var

– limit_var

• Components of the for statement can be a arbitrary statementsy– e.g. the loop condition may be a function callfunction call.

Page 36: Control Flow of Program

For loop : Examplesfor(i=1; i<=10; i++){

printf("%d\n" i);printf( %d\n , i);}

i = 1

i <= 10truefalse

printf

i ++

Page 37: Control Flow of Program

For loop  Examples : Float ctrl variable for(t=1.7; t<3.5; t=t+0.1){

printf("%f\n", t);}

t = 1.7

t < 3.5truefalse

printf

t=t+0.1 

Page 38: Control Flow of Program

For Loop: “one off” errorFor Loop:  one off  error• It is easy to get a for loop to be “one off” of the number you want.number you want. • Be careful of the combination of init_value and <  vs. <=

–for(i=0; i<10; i++)–for(i=0; i<=10; i++)for(i 0; i< 10; i++)–for(i=1; i<10; i++)for(i=1; i<=10; i++)–for(i=1; i<=10; i++)

• Counting from 0, with <, is a good combination and good for invariants as welland good for invariants as well. 

Page 39: Control Flow of Program

For Loop: “one off” errorFor Loop:  one off  error• It is easy to get a for loop to be “one off” of the number you want. y• Be careful of the combination of init_value and <  vs. <=

–for(i=0; i<10; i++)–for(i=0; i<=10; i++)

10 values: 0 to 911 values: 0 to 10

–for(i=1; i<10; i++)–for(i=1; i<=10; i++)C i f 0 i h i d bi i

9 values:  1 to 910 values:  1 to 10

• Counting from 0, with <, is a good combination and good for invariants as well

–As array indexing in C start with 0 : will be discussedAs array indexing in C start with 0 : will be discussed later

Page 40: Control Flow of Program

Nested For loop : Examplesfor(i=1; i<5; i++){for(i=1; i<5; i++){

for(j=1;  j<4;  j++){printf("%d * %d = %d\n", 

i= 1

i, j, i*j);}

}

false

}

j= 1

i < 5true falsej= 1

j< 4tfalse

FOR LOOPj< 4

printf

true

i++J++

Page 41: Control Flow of Program

Equivalence of top‐tested while loop d f land for loop

• The following loop for(x=init; x<=limit; x++){

statement_list

• Is equivalent to

}

Is equivalent to

x=init;hil ( < li it) {while (x<=limit) {

statement_list;++x++;

}

Page 42: Control Flow of Program

For‐ever or infinite loopFor ever or infinite  loop• Used for event driven case• Mostly event break the infinite loop using break statement : coming out of the loopbreak statement  : coming out of the loop

while(1) { /* Loop until value is valid *//* Loop until value is valid */

}

for(;;) { /* Loop without testing *// Loop without testing /

}

Page 43: Control Flow of Program

For‐ever or infinite  loop• Used for event driven case• Mostly event break the infinite loop using• Mostly event break the infinite loop using break statement  while(1) {while(1) {

scanf(“%c”,&c);if(c==‘e’ || c==‘E’) { ( || ) {printf(“\nEntered the required

character e or E\n”);break; // coming out of the loop}

printf(“%c” c);printf(“%c”,c); }

Page 44: Control Flow of Program

For‐ever or infinite  loop• Used for event driven case• Mostly event break the infinite loop usingMostly event break the infinite loop using break statement  f ( ) {for(;;) {

scanf(“%c”,&c);if(c==‘e’ || c==‘E’) {if(c e || c E ) {

printf(“\nEntered the required character e or E\n”);

break; // coming out of the loop}

i f(“% ” )printf(“%c”,c);}

Page 45: Control Flow of Program

Finite for loop with : breakfor(i=1; i<=10; i++){

i = 1

for(i=1; i<=10; i++){printf("%d, ", i);if(i==5) break;

i < 10 false

( ) ;}

i <= 10

printf

true

1, 2, 3, 4, 5,printf

i 5true

1, 2, 3, 4, 5, 

i == 5

false// coming out of the loop

i ++

Page 46: Control Flow of Program

Finite while loop with : breaki=0;

i = 0

i 0; while(i<=10){

printf("%d, ", i);if(i 5) b k

i < 10 false

if(i==5) break;i=i+1;

}i <= 10

printf

true

printf

i 5true

0, 1, 2, 3, 4, 5, 

i == 5

false// coming out of the loop

i=i+1

Page 47: Control Flow of Program

Finite for loop with : continuefor(i=1; i<=10; i++){

i = 1

for(i=1; i<=10; i++){if(i==5) continue;printf("%d\n", i); 

i < 10 false

p ( , );}

i <= 10true

true 0, 1, 2, 3, 4, 6, 7, 8, 9, 10,  i == 5

false

true

// Ski if

, , , , , , , , , ,

printffalse // Skip  a case if 

condition satisfied 

i ++

Page 48: Control Flow of Program

Finite while loop with : continue

i = 0i=0;While(i<=10){i++;

i 10i < 10true false

i++; if(i==5) continue;printf("%d, ", i);i 10i <= 10

i ++

printf( %d,  , i); }

i ++

i 5true 1, 2, 3, 4, 6, 7, 8, 9, 10,  

i == 5

false // Skip  a case if printf condition satisfied 

Page 49: Control Flow of Program

The do‐while loop• bottom‐tested loop (posttest)• One trip through loop is guaranteed i eOne trip through loop is guaranteed, i.e. statement is executed at least oncedo

statementwhile (loop condition);while (loop_condition);

do {do {statement1;statement2;

} hil (l diti )

Usually!} while (loop_condition);

Page 50: Control Flow of Program

do‐while loopdo {

statement;}while(condition);

statement;

true falseconditionconditiontrue false

Page 51: Control Flow of Program

do loop Examplesdo loop Examplesi = 0;d {do {

i++;i tf("%d\ " i)printf("%d\n", i);

} while(i < 10);

do {printf("Enter a value>0: ");printf( Enter a value>0: );scanf("%lf", &val);} while(val <= 0);} while(val < 0);

Page 52: Control Flow of Program

Bottom‐tested Equivalence• Bottom‐tested do loop (posttest)

do {statement;} while (condition);

• Similar to bottom‐tested forever loop

} while (condition);

p

for (;;) {statement_list;if (!condition) break;}}

Page 53: Control Flow of Program

Thanks

53