Branches and Loops (1/42 Branches >Branches are used to select and execute specific sections of the code while skipping other sections >Selection of different sections depend on a condition statement >We will learn: √if statement √ switch statement CPHAW try/catch statement @月协大学 TONGJI UNIVERSITY
Branches and Loops (1/42) Branches ➢ Branches are used to select and execute specific sections of the code while skipping other sections ➢ Selection of different sections depend on a condition statement ➢ We will learn: ✓ if statement ✓ switch statement ✓ try/catch statement
Branches and Loops (2/42 Branch:if >if'Statement condition false if condition ) statement 1 statement 2 true statement end group @日济大学 TONGJI UNIVERSITY
Branches and Loops (2/42) Branch: if ➢ ‘if’ Statement condition statement group true false if ( condition ), statement 1 statement 2 ... end
Branches and Loops (3/42 Branch:if Conditions can be: any real value (0 is false,non-zero is true) combination of relational and logical operators ·e.g.(x>0)&(x<10) √logical functions ·isempty() isnumericO,ischar() isinf(),isnan() exist() CPHAW @月协大学 TONGJI UNIVERSITY
Branches and Loops (3/42) Branch: if ➢ Conditions can be: ✓ any real value (0 is false, non-zero is true) ✓ combination of relational and logical operators • e.g. ( x > 0 ) & ( x < 10 ) ✓ logical functions • isempty() • isnumeric(), ischar() • isinf(), isnan() • exist()
Branches and Loops (4/42 Branch:if Examples: √if(r<=0), disp([Radius must be positive']) end √if((grade<0)川(grade>l00), disp([Grade must be in [0,100]range']) end √if isinf(result), disp(Result is infinite'); end @日济大学 AW TONGJI UNIVERSITY
Branches and Loops (4/42) Branch: if Examples: ✓ if ( r <= 0 ), disp( [ ‘Radius must be positive’ ] ); end ✓ if ( ( grade < 0 ) | ( grade > 100 ) ), disp( [ ‘Grade must be in [0,100] range’ ] ); end ✓ if isinf( result ), disp( ‘Result is infinite’ ); end
Branches and Loops (5/42 Branch:if >Water tank example: r=input('Enter the radius of the tank base(in meters):); if(r<=0), error('Radius must be positive'); end h=input('Enter the height ofthe tank(in meters):); if(h<=0), error(Height must be positive'); end w=input('Enter the amount of water(in m3):); if(w<=0), error('Amount of water must be positive'); end capacity=pi *r2 h; space capacity -w; if (space>0), disp([There is'num2str(space)'m3 extra space']); else @月停大学 disp(Tank is full'); TONGJI UNIVERSITY end
Branches and Loops (5/42) Branch: if ➢ Water tank example: r = input('Enter the radius of the tank base (in meters):'); if ( r <= 0 ), error( 'Radius must be positive' ); end h = input('Enter the height of the tank (in meters):'); if ( h <= 0 ), error( 'Height must be positive' ); end w = input('Enter the amount of water (in m3):'); if ( w <= 0 ), error( 'Amount of water must be positive' ); end capacity = pi * r^2 * h; space = capacity - w; if ( space > 0 ), disp( [ 'There is ' num2str(space) 'm3 extra space' ] ); else disp( 'Tank is full' ); end