lecture_04 - ECE190 Lecture04 January27,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 Lecture04 January27,2011 Lecture Topics Operators Conditionalconstructs Example Lecture materials Textbook§12.3.,12.4,13.1,13.2 Homework None  Machine problem MP1.1dueFebruary2at5pmsubmittedelectronically     1 V.Kindratenko ECE190 Lecture04 January27,2011 Operators Operators  o Example:z=x*y; Expressionx*yisevaluatedand theresultingvalueisassignedtovariablez threethingstoknowaboutoperators: o function whatitdoes o precedence inwhichorderareoperatorscombined o associativity inwhichorderoperatorsofthesameprecedenceareexecuted Assignment operator =istheassignmentoperator o Thevalueontherightoftheassignmentoperatorwillbeassignedtothevariablewhose nameisprovidedontheleftsideoftheoperator Thevalueactuallywillbecopiedtothememoryassociatedwiththevariable nameontheleftoftheassignmentoperator o Example:a=b+c; Ifthetypeofthevalueontherightoftheassignmentoperatorisnotthesameasthetypeof thevariableontheleftoftheassignmentoperator,datatypeconversionwilltakeplace Example: o intx,a  doubley,z  z=x+y < ­valueofxwillbeconvertedtodoubletypebeforetheexpression isevaluated a=x+y < ­onceevaluated,thesumwillbeconvertedtointtypebefore assigningittovariablea Arithmetic operators Definedforint,float,andchardatatypes *,+, ­,/,%(modulus) Precedence:*,/,%areexecutedfirst,followedby+and  o 2+3x4=2+(3x4) Associativity:operatorswiththesameprecedenceareexecutedsequentially o 2+3 ­4+5=((2+3) ­4)+5 Parenthesiscanbeusedtooverridetheevaluationorder Whilefloating ­pointadditionandmultiplicationarebothcommutative(a+b=b+aand a*b=b*a),theyarenotnecessarilyassociative.Thatis,(a+b)+cisnotnecessarilyequaltoa+ (b+c). (Post/pre ­) in ­/de ­crement Borrowedfromassembly ++, ­ ­  2 V.Kindratenko ECE190 Lecture04 January27,2011 Examples o x=4;y=x++;/*postincrement:y=4,x=5*/ o z=++x;/*pre ­increment:z=6,x=6*/ Bitwise operators normallyusedwithunsignedintandunsignedchardatatypes,theyreallyjustmanipulatebits withoutregardstothenumericalvalue/meaning ~bitwiseNOT:~x &bitwiseAND:y&x |bitwiseOR:x|y ^bitwiseXOR:x^y <<leftshift:x<<y(forpositiveintsameasx*2y) >>rightshift:x>>y(forpositiveintsameasx/2y) Examples o h=f&g; o h=g<<4; o h=~f|~g; Relational operators >less >=lessorequal <more <=moreorequal ==equal !=notequal Examples o q=(321==83);/*q=0*/ o q=(x==y);/*qisoneifx==y,otherwiseitis0*/ o h=f<=g;/*his1whenfislessofequalg*/ Logical operators valueof0isreferredtoaslogicallyfalse valueof~0isreferredtoaslogicallytrue ! ­logicalNOT &&logicalAND ||logicalOR Example:y=(10<=x)&&(x<=20)/*trueif10<=x<=20,otherwisefalse*/ Expressions with multiple operators Example:y=x&z+3||9 w%6; Applyingoperatorsprecedencerules,thisisequalto o y=(x&(z+3))||(9 (w%6));  3 V.Kindratenko ECE190 Lecture04 January27,2011 Table12.5fromthetextbooklistsoperatorsprecedencesequence Tobesurethecodedoeswhatyouwantittodo,justuseparenthesis! Special operator: conditional x=y?z:t; ifyisTRUE,x=z,otherwise,x=t o workslikeaMUX example:x=(y>0)?y: ­y;/*x=|y|*/ Compound ­assignment operators var1operator=var2;inCisthesameasvar1=var1operatorvar2; +=additionassignment,a+=bsameasa=a+b  ­=subtractionassignment *=multiplicationassignment /=bdivisionassignment %=bmoduloassignment &=bbitwiseANDassignment |=bbitwiseORassignment ^=bbitwiseXORassignment <<=bbitwiseleftshiftassignment >>=bbitwiserightshiftassignment Conditional constructs Therearethreebasicprogramingconstructs:sequential,conditional,iterative SequentialconstructmeansthatCprograminstructions(statements)areexecutedsequentially, oneafteranother: Statement1 Statement 2 Statement 3  Conditionalconstructmeansthatoneoranotherstatementwillbeexecuted,butnotboth, dependingonsomecondition:  4 V.Kindratenko ECE190 Lecture04 January27,2011 Test condition  Statement 1 Statement 2  InC,conditionalconstructscanbeimplementedusingif,if ­else,orswitchstatements if statement if(condition) action  false condition true action  examples o if(x<0) x= x /*simplestatement*/ o if(x>5&&x<25){ y=x*x+5 /*compoundstatement*/  \  } actionstatementcanbesimple,asinfistexample,orcompound,asinsecondexample if ­else statement if(condition) action_when_condition_is_true  else action_when_condition_is_false   5 V.Kindratenko ECE190 Lecture04 January27,2011 false true condition action 1 action 2  examples o if(x<0) x= x  else x=x*2  o if(x>5&&x<25){ y=x*x+5   \  } else  \  associatingifswithelses o inacascadedif ­elsestatement,anelseisassociatedwiththeclosestif thatis,whennotusingbraces,whichisnotagoodpractice if(x!=0) if(y>3) z=z/2  else z=z+2    sameas if(x!=0){ if(y>3) z=z/2  else z=z+2  }     o ifwereallywanttoassociateelsewiththefirstif,thenweshouldusebraces: if(x!=0){ if(y>3) z=z/2  } else z=z+2  o usebracestowriteclearandreadablecode! commonprogrammingerrors o if(x=2)usingassignmentoperatorinsteadof==  6 V.Kindratenko ECE190 Lecture04 January27,2011 Example Computing solution of a quadratic equation ax2+bx+c=0 Algorithm: o D=b2 4ac o IfDequals0,thereisonerealroot:x= ­b/(2a) o IfDispositive,therearetworoots:x1,2=( ­b )/(2a) o IfDisnegative,norealrootsexist Problemdecompositionintoseparatestepsusingaflowchart o Getinput o Computesolutionaccordingtotheabovealgorithm o Printoutput start Compute D D=b2-4ac Getinput (a,b,c) D>0 Compute solution  x1,2=(-b )/(2a) D==0 Output roots x1,2 x=-b/(2a) stop   Oncewehavetheproblemdecomposedintoindividualsteps,translatingitintoCis straightforward: /*solutionofthequadraticequationax^2+bx+c=0 */  #include<stdio.h>/*neededforprintfandscanf*/ #include<math.h>/*neededforsqrtf*/  intmain()  7 V.Kindratenko ECE190 Lecture04 January27,2011 { floata,b,c /*quadraticequationcoefficients*/ floatD /*determinant*/ floatx1,x2 /*solution(s)*/  /*getequationcoefficients*/ printf("Entera,b,andc:")  scanf("%f%f%f",&a,&b,&c)  printf("Solvingequation%fx^2+%fx+%f=0\n",a,b,c)   /*computesolution*/ D=b*b 4*a*c /*computedeterminant*/  if(D>0)/*tworealrootsexist*/ { x1=( b+sqrtf(D))/(2*a)  x2=( b sqrtf(D))/(2*a)  } elseif(D==0)/*onlyonerootexists*/ x1= b/(2*a)   /*printresults*/ if(D>0) printf("x1=%f,x2=%f\n",x1,x2)  elseif(D==0) printf("x=%f\n",x1)  else printf("Norealrootsexist\n")   return0  } Tocompile,wewillneedtolinkthecodewithadditionallibrary(libm.a)using ­lmcompilerflag Examples: o x2+2x ­8=0:x1=2,x2= ­4 o x2 ­10x+25=0:x=5 o 5x2 ­2x+2=0:norealroots   8 V.Kindratenko ...
View Full Document

Ask a homework question - tutors are online