lecture_05 - ECE190 Lecture05 February1,2011...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ECE190 Lecture05 February1,2011 Lecture Topics Conditionalconstructs Iterativeconstructs Examples Style Lecture materials Textbook§13.3 ­13.5 Homework None  Machine problem MP1.1dueFebruary2at5pmsubmittedelectronically MP1.2dueFebruary17at5pmsubmittedelectronically     1 V.Kindratenko ECE190 Lecture05 February1,2011 Conditional constructs InC,conditionalconstructscanbeimplementedusingif,if ­else,orswitchstatements Inthelastlecturewecoveredifandif ­elseconstructs;wewillnowlookattheswitchstatement switch statement considerexampleshownintheleftcolumn;italsocanbeimplementedasshownontheright: Usingcascadedif ­elsestatements if(expression==const1) action1  elseif(expression==const2) action2  elseif(expression==const3) action3  ... else actionN   Usingswitchstatement switch(expression){ caseconst1: action1  break  caseconst2: action2  break  caseconst3: action3  break  ... default: actionN  } evaluate expression true action 1 const1 false true const2 action 2 false ... action N  thisonlyworkswhenweconsidersomediscretevaluestowhichexpressionisevaluated, const1,const2   2 V.Kindratenko ECE190 Lecture05 February1,2011 Iterative constructs Iterativeconstructmeansthatsomestatementswillbeexecutedmultipletimesuntilsome conditionismet: false condition true action  Suchconstructimplementsaloopstructureinwhichactionisexecutedmultipletimes,aslong assomeconditionistrue o actionisalsocalledloopbody InC,iterativeconstructscanbeimplementedusingwhile,do ­while,orforloopstatements while and do ­while statements while(condition){ subtask  } do{ subtask }while(condition)  Forwhileloop,loopbodymayormaynotbeexecutedevenonce Fordo ­whileloop,loopbodywillbeexecutedatleastonce false subtask condition true condition subtask true fals e  Examples  3 V.Kindratenko ECE190 while x=0  while(x<10){ printf \ x=x+1  } Lecture05 February1,2011 do ­while x=0  do{  \ x=x+1  while(x<10)     for statement for(init test reinit){ subtask  } init false condition true subtask reinit  Example while x=0  while(x<10){  \ x=x+1  } for for(x=0 x<10 x++)  \    break and continue breakwillcausethelooptobeterminated continuewillcausetoskiptherestofcodeintheloopandstartexecutingnextloopiteration  4 V.Kindratenko ECE190 Lecture05 February1,2011 Examples Simple calculator Problemstatement:writeaprogramthatletsuserenterasimpleexpressionconsistingoftwo result. Usingsystematicdecomposition,wefirstderiveaflowchartthatshowsallthemainstepsinthe programthatneedtobeimplemented o Getinput(usingscanf) o Recognizewhichoperationistobeimplemented(usingswitchconstruct) o Outputresults(usingprintf) start Getinput true operation + res=op1 + op2 false Compute solution operation - true res=op1 - op2 false ... Output result ... print error message stop   /*simplecalculator Input:anexpressiontobeevaluated,forexample,4/6 Output:valuetowhichtheexpressionevaluates, oranerrormessageiftheoperationisnotsupported */  #include<stdio.h>/*neededforprintfandscanf*/  intmain() { intoperand1,operand2 /*twooperands*/ charoperation /*operationtobeperformed*/ intresult /*resultoftheoperation*/  5 V.Kindratenko ECE190 Lecture05  /*getinput*/    operand2)   /*calculateexpression*/ switch(operation) {  :result=operand1+operand2 break    :result=operand1 operand2 break   :result=operand1/operand2 break   :result=operand1*operand2 break   \ }  /*printresult*/  \n   return0  } February1,2011   Twoproblemswiththisimplementation o Whatifuserenters10/0? o Theprogramwillstillprintout result eveniftheoperatorwasnotsupported.Howdo wefixthis? Character counter Problemstatement:readcharactersfromthekeyboardandconvertthemtolowercaseuntil '0'(sentinel)isentered #include<stdio.h>/*neededforprintfandscanf*/  intmain() { charinchar,outchar        { if((inchar>='A')&&(inchar<+'Z')) outchar=('a' 'A')+inchar  else outchar=inchar    \    }  return0  } Riemann integral Problemstatement:writeaprogramtocomputeintegralofafunctionf(x)onaninterval[a,b].  6 V.Kindratenko ECE190 Lecture05 February1,2011 Algorithm:useintegraldefinitionasanareaunderafunctionf(x)onaninterval[a,b] f(x) n a b   Usingsystematicdecomposition,wefirstderiveaflowchart s=0 i=0 false i<n true dx=(b-a)/n s+=f(a+dx*i)*dx i++  /*computeintegraloff(x)=x*x+2x+3on[a,b]*/ #include<stdio.h>  intmain() { intn=100 /*hardcodednumberofReimannsumterms*/ floata= 1.0f /*hardcoded[a,b]*/ floatb=1.0f   7 V.Kindratenko ECE190 Lecture05 February1,2011 floats=0.0f /*computedintegralvalue*/ inti /*loopcounter*/ floatx,y /*xandy=f(x)*/ floatdx=(b a)/n /*widthofrectangles*/  for(i=0 i<n i++) { x=a+dx*i  y=x*x+2*x+3  s+=y*dx  }  printf("%f\n",s)   return0  } Style Styleiswhatseparatesagoodprogramfromnotsogood Oncetheprogramiswritten,alotoftimewillbespentmaintainingit,thus,itisimportantto makethemaintenancetaskassimpleaspossible o Documentation Programshouldbewell ­documented,itshouldstartwithanopeningcomment describingthepurpose,input,output,authors,revisionhistory,etc. Eachfunctionmustbedocumentedaswell Variablesshouldbedocumented Codesectionsshouldbedocumented o Clarity programshouldreadlikeatechnicalpaper shouldbeorganizedintosectionsbasedonfunctionsimplemented codeinsidefunctionsshouldbeorganizedintoparagraphs,eachparagraph startingwithatopic ­specificcommentandbeseparatedfromotherparagraph byspace indentationshouldbeusedtoidentifycodeinsideblocksorconditionals variablesshouldbenamedtohaveintuitiveenoughmeaning andsoshouldbefunctions o Simplicity Theprogramshouldbemadeassimpleandeasytounderstandaspossible Functionsshouldbenotextensivelylong Avoidcomplexconstructs,suchasnestedifs Statementsshouldbeshort RefertoECE190CCodingConventionsat http://courses.engr.illinois.edu/ECE190/info/conventions.html   8 V.Kindratenko ...
View Full Document

Ask a homework question - tutors are online