Chapter_3

download Chapter_3

of 20

description

Matlb file

Transcript of Chapter_3

  • Chapter 3: Selection Statements Exercises1)Whatwouldbetheresultofthefollowingexpressions?

    'b' >= 'c' 1 1 3 == 2 + 1 1 (3 == 2) + 1 1 xor(5 < 6, 8 > 4) 0

    2)Writeascriptthattestswhethertheusercanfollowinstructions.Itpromptstheusertoenteranx.Iftheuserentersanythingotherthananx,itprintsanerrormessageotherwise,thescriptdoesnothing.Ch3Ex2.m

    % Can the user follow instructions?? inx = input('Enter an x: ', 's'); if inx ~= 'x' fprintf('That was no x!\n') end

    3)Writeafunctionnexthourthatreceivesoneintegerargument,whichisanhouroftheday,andreturnsthenexthour.Thisassumesa12hourclock;so,forexample,thenexthourafter12wouldbe1.Herearetwoexamplesofcallingthisfunction.

    >> fprintf('The next hour will be %d.\n',nexthour(3)) The next hour will be 4. >> fprintf('The next hour will be %d.\n',nexthour(12)) The next hour will be 1.

    nexthour.m

    function outhour = nexthour(currenthour) % Receives an integer hour of the day and % returns the next integer hour % Format of call: nexthour(hour of day) % Returns the next integer hour outhour = currenthour + 1; if outhour == 13 outhour = 1; end end

  • 4) Write a script to calculate the volume of a pyramid, which is 1/3 * base * height, where the base is length * width. Prompt the user to enter values for the length, width, and height, and then calculate the volume of the pyramid. When the user enters each value, he or she will then also be prompted for either i for inches or c for centimeters. (Note 2.54 cm = 1 inch). The script should print the volume in cubic inches with three decimal places. As an example, the output format will be:

    This program will calculate the volume of a pyramid. Enter the length of the base: 50 Is that i or c? i Enter the width of the base: 6 Is that i or c? c Enter the height: 4 Is that i or c? i The volume of the pyramid is xxx.xxx cubic inches.

    Ch3Ex4.m

    %Calculate the volume of a pyramid % Prompt the user for the length, width, and height in % either inches or centimeters (inches is assumed and will % be the default) disp('This script will calculate the volume of a pyramid.') len = input('Enter the length of the base: '); lenunit = input('Is that i or c? ','s'); if lenunit == 'c' len = len/2.54; end wid = input('Enter the width of the base: '); widunit = input('Is that i or c? ','s'); if widunit == 'c' wid = wid/2.54; end ht = input('Enter the height: '); htunit = input('Is that i or c? ','s'); if htunit == 'c' ht = ht/2.54; end vol = 1/3 * len * wid * ht; fprintf('\nThe volume of the pyramid is ') fprintf('%.3f cubic inches.\n',vol)

  • 5)Writeascripttoprompttheuserforacharacter,andthenprintetherthatitisaletterofthealphabetorthatitisnot. Ch3Ex5.m

    %Prompt for a character and print whether it is % a letter of the alphabet or not let = input('Enter a character: ', 's'); if (let >= 'a' && let = 'A' && let

  • % Prompts the user for the semimajor and semiminor axes of % an ellipse and calculates and returns the eccentricity % (if the semimajor axis ~=0) a = input('Enter the semimajor axis: '); b = input('Enter the semiminor axis: '); if a == 0 disp('Error: semimajor cannot be 0') else eccentricity = EllEcc(a,b); fprintf('The eccentricity is %.2f\n', eccentricity) end EllEcc.m function eccen = EllEcc(a,b) % Calculates the eccentricity of an ellipse given % the semimajor axis a and the semiminor axis b % Format of call: EllEcc(a,b) % Returns the eccentricity eccen = sqrt(1- (b/a)^2); end 8)Thesystolicanddiastolicbloodpressurereadingsarefoundwhentheheartispumpingandtheheartisatrest,respectively.Abiomedicalexperimentisbeingconductedonlyonsubjectswhosebloodpressureisoptimal.Thisisdefinedasasystolicbloodpressurelessthan120andadiastolicbloodpressurelessthan80.Writeascriptthatwillpromptforthesystolicanddiastolicbloodpressuresofaperson,andwillprintwhetherornotthatpersonisacandidateforthisexperiment.Ch3Ex8.m% Checks blood pressures to determine whether or % not a person is a candidate for an experiment syst = input('Enter the systolic blood pressure: '); diast = input('Enter the diastolic blood pressure: '); if syst < 120 && diast < 80 disp('This person is a candidate.') else disp('This person is not suitable for the experiment.') end 9)Thecontinuityequationinfluiddynamicsforsteadyfluidflowthroughastreamtubeequatestheproductofthedensity,velocity,andareaattwopointsthathavevaryingcrosssectionalareas.Forincompressibleflow,thedensitiesareconstantso

  • theequationisA1V1=A2V2.IftheareasandV1areknown,V2canbefoundas 12

    1 VAA .

    Therefore,whetherthevelocityatthesecondpointincreasesordecreasesdependsontheareasatthetwopoints.Writeascriptthatwillprompttheuserforthetwoareasinsquarefeet,andwillprintwhetherthevelocityatthesecondpointwillincrease,decrease,orremainthesameasatthefirstpoint.Ch3Ex9.m% Prints whether the velocity at a point in a stream tube % will increase, decrease, or remain the same at a second % point based on the cross-sectional areas of two points a1 = input('Enter the area at point 1: '); a2 = input('Enter the area at point 2: '); if a1 > a2 disp('The velocity will increase') elseif a1 < a2 disp('The velocity will decrease') else disp('The velocity will remain the same') end 10)Inchemistry,thepHofanaqueoussolutionisameasureofitsacidity.ThepHscalerangesfrom0to14,inclusive.AsolutionwithapHof7issaidtobeneutral,asolutionwithapHgreaterthan7isbasic,andasolutionwithapHlessthan7isacidic.WriteascriptthatwillprompttheuserforthepHofasolution,andwillprintwhetheritisneutral,basic,oracidic.IftheuserentersaninvalidpH,anerrormessagewillbeprinted.Ch3Ex10.m% Prompts the user for the pH of a solution and prints % whether it is basic, acidic, or neutral ph = input('Enter the pH of the solution: '); if ph >=0 && ph 7 disp('It is basic') end else disp('Error in pH!') end

  • 11)WriteafunctioncreatevecMToNthatwillcreateandreturnavectorofintegersfrommton(wheremisthefirstinputargumentandnisthesecond),regardlessofwhethermislessthannorgreaterthann.Ifmisequalton,thevectorwilljustbe1x1orascalar. createvecMToN.m function outvec = createvecMToN(m,n) % Creates a vector of integers from m to n % Format of call: createvecMToN(m,n) % Returns vector of integers from m:n or m:-1:n if m < n outvec = m:n; else outvec = m:-1:n; end end 12)Writeafunctionflipvecthatwillreceiveoneinputargument.Iftheinputargumentisarowvector,thefunctionwillreversetheorderandreturnanewrowvector.Iftheinputargumentisacolumnvector,thefunctionwillreversetheorderandreturnanewcolumnvector.Iftheinputargumentisamatrixorascalar,thefunctionwillreturntheinputargumentunchanged. flipvec.m function out = flipvec(vec) % Flips it if it's a vector, otherwise % returns the input argument unchanged % Format of call: flipvec(vec) % Returns flipped vector or unchanged [r c] = size(vec); if r == 1 && c > 1 out = fliplr(vec); elseif c == 1 && r > 1 out = flipud(vec); else out = vec; end end 13)Inascript,theuserissupposedtoentereitherayorninresponsetoaprompt.Theusersinputisreadintoacharactervariablecalledletter.ThescriptwillprintOK,continuingiftheuserenterseitherayorYoritwillprintOK,

  • haltingiftheuserentersanorNorErroriftheuserentersanythingelse.Putthisstatementinthescriptfirst:

    letter = input('Enter your answer: ', 's'); Writethescriptusingasinglenestedifelsestatement(elseifclauseispermitted).Ch3Ex13.m% Prompts the user for a 'y' or 'n' answer and responds % accordingly, using an if-else statement letter = input('Enter your answer: ', 's'); if letter == 'y' || letter == 'Y' disp('OK, continuing') elseif letter == 'n' || letter == 'N' disp('OK, halting') else disp('Error') end 14)Writethescriptfromthepreviousexerciseusingaswitchstatementinstead.Ch3Ex14.m% Prompts the user for a 'y' or 'n' answer and responds % accordingly, using an if-else statement letter = input('Enter your answer: ', 's'); switch letter case {'y', 'Y'} disp('OK, continuing') case {'n', 'N'} disp('OK, halting') otherwise disp('Error') end 15)Inaerodynamics,theMachnumberisacriticalquantity.Itisdefinedastheratioofthespeedofanobject(e.g.,anaircraft)tothespeedofsound.IftheMachnumberislessthan1,theflowissubsonic;iftheMachnumberisequalto1,theflowistransonic;iftheMachnumberisgreaterthan1,theflowissupersonic.Writeascriptthatwillprompttheuserforthespeedofanaircraftandthespeedofsoundattheaircraftscurrentaltitudeandwillprintwhethertheconditionissubsonic,transonic,orsupersonic.Ch3Ex15.m% Prints whether the speed of an object is subsonic,

  • % transonic, or supersonic based on the Mach number plane_speed = input('Enter the speed of the aircraft: '); sound_speed = input('Enter the speed of sound: '); mach = plane_speed/sound_speed; if mach < 1 disp('Subsonic') elseif mach == 1 disp('Transonic') else disp('Supersonic') end 16)WriteascriptthatwillprompttheuserforatemperatureindegreesCelsius,andthenanFforFahrenheitorKforKelvin.Thescriptwillprintthecorrespondingtemperatureinthescalespecifiedbytheuser.Forexample,theoutputmightlooklikethis:

    Enter the temp in degrees C: 29.3 Do you want K or F? F The temp in degrees F is 84.7

    Theformatoftheoutputshouldbeexactlyasspecifiedabove.Theconversionsare: 32 C

    59 F

    273.15 C K Ch3Ex16.m% Converts a temperature from C to F or K cel = input('Enter the temp in degrees C: '); fork = input('Do you want F or K? ', 's'); if fork == 'F' || fork == 'f' fprintf('The temp in degrees F is %.1f\n', 9/5*cel+32) else fprintf('The temp in degrees K is %.1f\n', cel+273.15) end 17)Writeascriptthatwillgenerateonerandominteger,andwillprintwhethertherandomintegerisanevenoranoddnumber.(Hint:anevennumberisdivisibleby2,whereasanoddnumberisnot;sochecktheremainderafterdividingby2.)Ch3Ex17.m% Generates a random integer and prints whether it is even or odd

  • ranInt = randi([1, 100]); if rem(ranInt,2) == 0 fprintf('%d is even\n', ranInt) else fprintf('%d is odd\n', ranInt) end 18)Writeafunctionisdivby4thatwillreceiveanintegerinputargument,andwillreturnlogical1fortrueiftheinputargumentisdivisibleby4,orlogicalfalseifitisnot.isdivby4.mfunction out = isdivby4(inarg) % Returns 1 for true if the input argument is % divisible by 4 or 0 for false if not % Format of call: isdivby4(input arg) % Returns whether divisible by 4 or not out = rem(inarg,4) == 0; end 19)Writeafunctionisintthatwillreceiveanumberinputargumentinnum,andwillreturn1fortrueifthisnumberisaninteger,or0forfalseifnot.Usethefactthatinnumshouldbeequaltoint32(innum)ifitisaninteger.Unfortunately,duetoroundofferrors,itshouldbenotedthatitispossibletogetlogical1fortrueiftheinputargumentisclosetoaninteger.Thereforetheoutputmaynotbewhatyoumightexpect,asshownhere.

    >> isint(4) ans = 1 >> isint(4.9999) ans = 0 >> isint(4.9999999999999999999999999999) ans = 1

    isint.m function out = isint(innum) % Returns 1 for true if the argument is an integer % Format of call: isint(number) % Returns logical 1 iff number is an integer

  • out = innum == int32(innum); end 20)APythagoreantripleisasetofpositiveintegers(a,b,c)suchthata2+b2=c2.Writeafunctionispythagthatwillreceivethreepositiveintegers(a,b,cinthatorder)andwillreturnlogical1fortrueiftheyformaPythagoreantriple,or0forfalseifnot.ispythag.mfunction out = ispythag(a,b,c) % Determines whether a, b, c are a Pythagorean % triple or not % Format of call: ispythag(a,b,c) % Returns logical 1 if a Pythagorean triple out = a^2 + b^2 == c^2; end 21)Influiddynamics,theReynoldsnumberReisadimensionlessnumberusedtodeterminethenatureofafluidflow.Foraninternalflow(e.g.,waterflowthroughapipe),theflowcanbecategorizedasfollows:

    Re2300 LaminarRegion23004000 TurbulentRegion

    WriteascriptthatwillprompttheuserfortheReynoldsnumberofaflowandwillprinttheregiontheflowisin.Hereisanexampleofrunningthescript:

    >> Reynolds Enter a Reynolds number: 3500 The flow is in transition region

    Ch3Ex21.m % Prompts the user for the Reynolds number % for an internal flow and prints % whether it is laminar, turbulent, or in % a transition region Re = input('Enter a Reynolds number: '); if Re 2300 && Re

  • else disp('The flow is in turbulent region') end Woulditbeagoodideatowritetheselectionstatementsusingswitch?Whyorwhynot?No,becausetheReynoldsnumbercouldbearealnumberandtherangesaretoolarge.22)TheareaAofarhombusisdefinedasA=

    221dd ,whered1andd2arethelengths

    ofthetwodiagonals.Writeascriptrhombthatfirstpromptstheuserforthelengthsofthetwodiagonals.Ifeitherisanegativenumberorzero,thescriptprintsanerrormessage.Otherwise,iftheyarebothpositive,itcallsafunctionrhombareatoreturntheareaoftherhombus,andprintstheresult.Writethefunction,also!Thelengthsofthediagonals,whichyoucanassumeareininches,arepassedtotherhombareafunction.rhomb.m% Prompt the user for the two diagonals of a rhombus, % call a function to calculate the area, and print it d1 = input('Enter the first diagonal: '); d2 = input('Enter the second diagonal: '); if d1

  • withstormdatawilluseselectionstatementstodeterminetheseverityofstormsandalsotomakedecisionsbasedonthedata.23)Whetherastormisatropicaldepression,tropicalstorm,orhurricaneisdeterminedbytheaveragesustainedwindspeed.Inmilesperhour,astormisatropicaldepressionifthewindsarelessthan38mph.Itisatropicalstormifthewindsarebetween39and73mph,anditisahurricaneifthewindspeedsare>=74mph.Writeascriptthatwillprompttheuserforthewindspeedofthestorm,andwillprintwhichtypeofstormitis.Ch3Ex23.m% Prints whether a storm is a tropical depression, tropical % storm, or hurricane based on wind speed wind = input('Enter the wind speed of the storm: '); if wind < 38 disp('Tropical depression') elseif wind >= 38 && wind < 73 disp('Tropical storm') else disp('Hurricane') end 24)Hurricanesarecategorizedbasedonwindspeeds.ThefollowingtableshowstheCategorynumberforhurricaneswithvaryingwindrangesandwhatthestormsurgeis(infeetabovenormal).

    Cat Windspeed Stormsurge 1 7495 45 2 96110 68 3 111130 912 4 131155 1318 5 >155 >18Writeascriptthatwillprompttheuserforthewindspeed,andwillprintthehurricanecategorynumberandthetypicalstormsurge.Ch3Ex24.m% Prints the category number and storm surge for % a hurricane based on the wind speed wind = input('Enter the wind speed: '); if wind >= 74 && wind 95 && wind

  • fprintf('Category 2; typical storm surge 6-8 ft\n') elseif wind > 110 && wind 130 && wind 155 fprintf('Category 5; typical storm surge > 18 ft\n') else fprintf('Not a hurricane\n') end 25)TheBeaufortWindScaleisusedtocharacterizethestrengthofwinds.Thescaleusesintegervaluesandgoesfromaforceof0,whichisnowind,upto12,whichisahurricane.Thefollowingscriptfirstgeneratesarandomforcevalue.Then,itprintsamessageregardingwhattypeofwindthatforcerepresents,usingaswitchstatement.Youaretorewritethisswitchstatementasonenestedifelsestatementthataccomplishesexactlythesamething.Youmayuseelseand/orelseifclauses.ranforce = round(rand*12); switch ranforce case 0 disp('There is no wind') case {1,2,3,4,5,6} disp('There is a breeze') case {7,8,9} disp('This is a gale') case {10,11} disp('It is a storm') case 12 disp('Hello, Hurricane!') end Ch3Ex25.mif ranforce == 0 disp('There is no wind') elseif ranforce >= 1 && ranforce = 7 && ranforce
  • 26)Cloudsaregenerallyclassifiedashigh,middle,orlowlevel.Theheightofthecloudisthedeterminingfactor,buttherangesvarydependingonthetemperature.Forexample,intropicalregionstheclassificationsmaybebasedonthefollowingheightranges(giveninfeet): low 06500 middle 650020000 high >20000Writeascriptthatwillprompttheuserfortheheightofthecloudinfeet,andprinttheclassification.Ch3Ex26.m% Prints cloud classification cloudHt = input('Enter the height of the cloud in feet: '); if cloudHt > 0 && cloudHt 6500 && cloudHt 20000 disp('This is a high cloud') else disp('Error: how could this be a cloud?') end

    27)Rewritethefollowingswitchstatementasonenestedifelsestatement(elseifclausesmaybeused).Assumethatthereisavariableletterandthatithasbeeninitialized.

    switch letter case 'x' disp('Hello') case {'y', 'Y'} disp('Yes') case 'Q' disp('Quit') otherwise disp('Error') end

    Ch3Ex27.mletter = char(randi([97,122]));

  • if letter == 'x' disp('Hello') elseif letter == 'y' || letter == 'Y' disp('Yes') elseif letter == 'Q' disp('Quit') else disp('Error') end 28)Rewritethefollowingnestedifelsestatementasaswitchstatementthataccomplishesexactlythesamething.Assumethatnumisanintegervariablethathasbeeninitialized,andthattherearefunctionsf1,f2,f3,andf4.Donotuseanyiforifelsestatementsintheactionsintheswitchstatement,onlycallstothefourfunctions.

    if num < -2 || num > 4 f1(num) else if num = 0 f2(num) else f3(num) end else f4(num) end end

    Ch3Ex28.mswitch num case {-2, -1} f3(num) case {0, 1, 2} f2(num) case {3, 4} f4(num) otherwise f1(num) end 29)WriteascriptareaMenuthatwillprintalistconsistingofcylinder,circle,andrectangle.Itpromptstheusertochooseone,andthenpromptstheuserfortheappropriatequantities(e.g.,theradiusofthecircle)andthenprintsitsarea.Iftheuserentersaninvalidchoice,thescriptsimplyprintsanerrormessage.Thescript

  • shoulduseanestedifelsestatementtoaccomplishthis.Herearetwoexamplesofrunningit(unitsareassumedtobeinches).

    >> areaMenu Menu 1. Cylinder 2. Circle 3. Rectangle Please choose one: 2 Enter the radius of the circle: 4.1 The area is 52.81 >> areaMenu Menu 1. Cylinder 2. Circle 3. Rectangle Please choose one: 3 Enter the length: 4 Enter the width: 6 The area is 24.00

    areaMenu.m% Prints a menu and calculates area of user's choice disp('Menu') disp('1. Cylinder') disp('2. Circle') disp('3. Rectangle') sh = input('Please choose one: '); if sh == 1 rad = input('Enter the radius of the cylinder: '); ht = input('Enter the height of the cylinder: '); fprintf('The surface area is %.2f\n', 2*pi*rad*ht) elseif sh == 2 rad = input('Enter the radius of the circle: '); fprintf('The area is %.2f\n', pi*rad*rad) elseif sh == 3 len = input('Enter the length: '); wid = input('Enter the width: '); fprintf('The area is %.2f\n', len*wid) else disp('Error! Not a valid choice.') end 30)ModifytheareaMenuscripttouseaswitchstatementtodecidewhichareatocalculate.

  • areaMenuSwitch.m% Prints a menu and calculates area of user's choice disp('Menu') disp('1. Cylinder') disp('2. Circle') disp('3. Rectangle') sh = input('Please choose one: '); switch sh case 1 rad = input('Enter the radius of the cylinder: '); ht = input('Enter the height of the cylinder: '); fprintf('The surface area is %.2f\n', 2*pi*rad*ht) case 2 rad = input('Enter the radius of the circle: '); fprintf('The area is %.2f\n', pi*rad*rad) case 3 len = input('Enter the length: '); wid = input('Enter the width: '); fprintf('The area is %.2f\n', len*wid) otherwise disp('Error! Not a valid choice.') end 31)ModifytheareaMenuscript(eitherversion)tousethebuiltinmenufunctioninsteadofprintingthemenuchoices.Ch3Ex31.m% Prints a menu and calculates area of user's choice sh = menu('Please choose one:','Cylinder', 'Circle', 'Rectangle'); switch sh case 1 rad = input('Enter the radius of the cylinder: '); ht = input('Enter the height of the cylinder: '); fprintf('The surface area is %.2f\n', 2*pi*rad*ht) case 2 rad = input('Enter the radius of the circle: '); fprintf('The area is %.2f\n', pi*rad*rad) case 3 len = input('Enter the length: '); wid = input('Enter the width: '); fprintf('The area is %.2f\n', len*wid) otherwise disp('Error! Not a valid choice.') end

  • 32)Writeascriptthatpromptstheuserforavalueofavariablex.Then,itusesthemenufunctiontopresentchoicesbetweensin(x),cos(x),andtan(x).Thescriptwillprintwhicheverfunctionofxtheuserchooses.Useanifelsestatementtoaccomplishthis.Ch3Ex32.m% Prints either sin, cos, or tan of x % uses the menu function to choose x = input('Enter a value for x: '); choice = menu('Choose a function','sin','cos','tan'); if choice == 1 fprintf('sin(%.1f) is %.1f\n', x, sin(x)) elseif choice == 2 fprintf('cos(%.1f) is %.1f\n', x, cos(x)) elseif choice == 3 fprintf('tan(%.1f) is %.1f\n', x, tan(x)) end 33)Modifytheabovescripttouseaswitchstatementinstead.Ch3Ex33.m% Prints either sin, cos, or tan of x % uses the menu function to choose x = input('Enter a value for x: '); choice = menu('Choose a function','sin','cos','tan'); switch choice case 1 fprintf('sin(%.1f) is %.1f\n', x, sin(x)) case 2 fprintf('cos(%.1f) is %.1f\n', x, cos(x)) case 3 fprintf('tan(%.1f) is %.1f\n', x, tan(x)) end 34)Writeafunctionthatwillreceiveonenumberasaninputargument.ItwillusethemenufunctionthatwilldisplayChooseafunctionandwillhavebuttonslabeledceil,round,andsign.Usingaswitchstatement,thefunctionwillthencalculateandreturntherequestedfunction(e.g.,ifroundischosen,thefunctionwillreturntheroundedvalueoftheinputargument).choosefn.mfunction outarg = choosefn(inarg)

  • % Chooses whether to use ceil, round, or sign % on the input argument % Format of call: choosefn(input arg) % Returns ceil(input arg) or round or sign choice = menu('Choose a function','ceil','round','sign'); switch choice case 1 outarg = ceil(inarg); case 2 outarg = round(inarg); case 3 outarg = sign(inarg); end end 35)ModifythefunctioninQuestion34touseanestedifelsestatementinstead.choosefn2.mfunction outarg = choosefn2(inarg) % Chooses whether to use ceil, round, or sign % on the input argument % Format of call: choosefn(input arg) % Returns ceil(input arg) or round or sign choice = menu('Choose a function','ceil','round','sign'); if choice == 1 outarg = ceil(inarg); elseif choice == 2 outarg = round(inarg); elseif choice == 3 outarg = sign(inarg); end end 36)Simplifythisstatement:

    if num < 0 num = abs(num); else num = num; end

    if num < 0 num = abs(num); end

  • % or just: num = abs(num); 37)Simplifythisstatement:

    if val >= 4 disp('OK') elseif val < 4 disp('smaller') end

    if val >= 4 disp('OK') else disp('smaller') end