Вы находитесь на странице: 1из 48

CProgramming:

ArithmeticandLogicOperations

A.Sahu amd S.V.Rao


Dept of Comp. Sc. & Engg.
DeptofComp.Sc.&Engg.
IndianInstituteofTechnologyGuwahati

1
Algebra:BEDMAS/PEDMASRule
(
(recap)
)
BEDMASorPEDMAS
B/P:BracketorParenthesis()
/ k h ( )
InC,only()usedforexpression
Curlybraces{},andsquarebracket[]usedfor
someotherpurpose.
Again[]mayinvolvesinexpressionasintheformof
arrayaccess
E:Exponentiation
E : Exponentiation
DM:DivisionandMultiplication
AS:AdditionandSubtraction
2
BEDMASequivalentinC
Arithmetic Operators Precedence Rule
ArithmeticOperatorsPrecedenceRule
(recap)
Operator(s) Precedence&Associativity
()
() Evaluatedfirst.Ifnested
Evaluated first If nested
(embedded),innermostfirst.
* / %
*/% Evaluatedsecond.Ifthereare
Evaluated second If there are
several,evaluatedlefttoright.
+ EEvaluatedthird.Ifthereare
l t d thi d If th
several,evaluatedlefttoright.
= Evaluatedlast,righttoleft.
l dl h l f
UsingParentheses
Useparenthesestochangetheorderinwhich
an expression is evaluated.
anexpressionisevaluated.
a + b * c Wouldmultiplyb*cfirst,
t e add a to t e esu t
thenaddatotheresult.
Ifyoureallywantthesumofaandbtobe
p y , p
multipliedbyc,useparenthesestoforcethe
evaluationtobedoneintheorderyouwant.
(a + b) * c
Alsouseparenthesestoclarifyacomplex
expression.
expression
PracticeWithEvaluatingExpressions
(recap)
Givenintegervariablesa,b,c,d,ande,
where a = 1 b = 2 c = 3 d = 4
wherea=1,b=2,c=3,d=4,
evaluatethefollowingexpressions:
a + b - c + d
a * b / c
1 + a * b % c
a + d % b - c
e = b = d + c / b - a
PracticeWithEvaluatingExpressions
(recap)
Givenintegervariablesa,b,c,d,ande,
where a = 1 b = 2 c = 3 d = 4
wherea=1,b=2,c=3,d=4,
evaluatethefollowingexpressions:
a + b - c + d =3-3+4=0+4=4
a * b / c = 2/3+4=0+4=4
2/3+4 0+4 4
1 + a * b % c =1+2%3=1+2=3
a + d % b - c =1+0-3=1-3=-2
1+0 3 1 3 2
e = b = d + c / b a
Increment and Decrement Operators
IncrementandDecrementOperators
The
Theincrementoperator
increment operator ++
Thedecrementoperator
Precedence:lowerthan(),buthigherthan*
d l h () b hi h h *
/and%
Associativity:righttoleft
Incrementanddecrementoperatorscanonly
p y
beappliedtovariables,nottoconstantsor
expressions
p
Increment Operator
IncrementOperator
Ifwewanttoaddonetoavariable,wecansay:
count = count + 1 ;
Programsoftencontainstatementsthat
incrementvariables,sotosaveontyping,C
providestheseshortcuts:
count++ ; OR++count ;
Both do the same thing They change the value
Bothdothesamething.Theychangethevalue
ofcountbyaddingonetoit.
Postincrement Operator
Thepositionofthe++determineswhenthevalueis
incremented If the ++ is after the variable then the
incremented.Ifthe++isafterthevariable,thenthe
incrementingisdonelast(apostincrement).
int amount,
amount count ;
count = 3 ;
amount = 2 * count++ ;
amountgetsthevalueof2*3,whichis6,andthen1
gets added to count
getsaddedtocount.
So,afterexecutingthelastline,amountis6andcount
is 4.
is4.
Preincrement Operator
Ifthe++isbeforethevariable,thentheincrementing
is done first (a preincrement)
isdonefirst(apreincrement).
int amount, count ;
count = 3 ;
amount = 2 * ++count ;

1getsaddedtocountfirst,thenamountgetsthevalue
of 2 *4,whichis8.
of2 4 which is 8
So,afterexecutingthelastline,amountis8andcount
is 4.
is4.
AHandTraceExample
int ans, val= 4 ;
Code Val Ans
4 garbage
val = value + 1 ;
val++ ;
++val ;
ans = 2 * val++ ;
ans = ++val / 2 ;
val-- ;
--val ;
ans = --val * 2 ;
ans = val-- / 3 ;
AHandTraceExample
int ans, val= 4 ;
Code Val Ans
4 garbage
val = value + 1 ; 5
val++ ; 6
++val ; 7
ans = 2 * val++ ; 8 14
ans = ++val / 2 ; 9 4
val-- ; 8
--val ; 7
ans = --val * 2 ; 6 3
ans = val--
l / 3 ; 5 1
CCode:PreviousExample
int main(){
int ans, val=4;
val = val + 1 ;
printf(ans=%d
i tf( %d val=%d\n,ans,val);
l %d\ l)
val++ ; ++val ;
printf(ans=%d val=%d\n,ans,val);
ans = 2 * val++ ;
printf(ans=%d val=%d\n,ans,val);
val ; val;
val--;--val;
printf(ans=%d val=%d\n,ans,val);
ans=--val*2;
printf(ans %d val=%d\n,ans,val);
printf(ans=%d val %d\n ans val);
ans = val-- / 3 ;
printf(ans=%d val=%d\n,ans,val);
return 0;
}
Practice
Given
int a = 1, b = 2, c = 3 ;

Whatisthevalueofthisexpression?

++a * b - c--

Whatarethenewvaluesofa,b,andc?
Practice
Given
int a = 1, b = 2, c = 3 ;

Whatisthevalueofthisexpression?

++a * b - c--
=1
Whatarethenewvaluesofa,b,andc?
a 2 c 2
a=2c=2
More Practice
MorePractice
Given
int a =1, b =2, c =3, d =4 ;

Whatisthevalueofthisexpression?

++b / c + a * d++

Whatarethenewvaluesofa,b,c,andd?
More Practice
MorePractice
Given
int a =1, b =2, c =3, d =4 ;

Whatisthevalueofthisexpression?

++b / c + a * d++
=1+4=5
Whatarethenewvaluesofa,b,c,andd?
a 1 b 3c 3d 5
a=1,b=3,c=3,d=5
AssignmentOperators
= += = *= /= %=
S
Statement E i l
EquivalentStatement
S
a = a+2 ; a += 2 ;
a = a-3 ; a -= 3 ;
a = a*2 ; a *= 2 ;
a = a/4 ; a /= 4 ;
a = a%2 ; a %= 2 ;
b = b+(c+2); b += c + 2 ;
d =d
=d*(e-5);
(e 5); d *= = e - 5 ;
Practice with Assignment Operators
PracticewithAssignmentOperators
int i = 1, j = 2, k = 3, m = 4 ;

Expression
p Value
i += j + k

j *= k = m + 5

k -= m /= j * 2
Practice with Assignment Operators
PracticewithAssignmentOperators
int i = 1, j = 2, k = 3, m = 4 ;

Expression
p Value
i += j + k i=6

j *= k = m + 5 k=9, j=18

k -= m /= j * 2 m=1, k=2
RelationalExpressionsand
Evaluation
Evaluation

21
RelationalOperators
Operator Meaning
< Less than
> Greaterthan
<= lessthanorequalto
>= greaterthanorequalto
== isequalto
q
!= isnotequalto
Relationalexpressions
Relational expressions evaluatetotheinteger
evaluate to the integer
values1(true)or0(false).
Alloftheseoperatorsarecalledbinaryoperators
becausetheytaketwoexpressionsasoperands.
Practice with Relational Expressions
PracticewithRelationalExpressions
int a = 1, b = 2, c = 3 ;
Expression Value Expression Value
a < c (a + b)>= c
b <=
< c (a + b)b)== c
c <= a a != b
a > b ( + b)!=
(a b)! c
b >= c
Practice with Relational Expressions
PracticewithRelationalExpressions
int a = 1, b = 2, c = 3 ;
Expression Value Expression Value
a < c T (a + b)>= c T
b <=
< c T (a + b)b)== c T
c <= a F a != b T
a > b F (
(a + b)!=
b)! c F
b >= c F
ArithmeticExpressions:TrueorFalse
p

Arithmetic
Arithmeticexpressions
expressions evaluatetonumeric
evaluate to numeric
values.

Anarithmeticexpressionthathasavalueof
zero is false
zeroisfalse.

An
Anarithmeticexpressionthathasavalue
arithmetic expression that has a value
otherthanzeroistrue.
Practice with Arithmetic Expressions
PracticewithArithmeticExpressions
int a = 1, b = 2, c = 3 ;
float x = 3.33, y = 6.66 ;
p
Expression NumericValue True/False
/
a + b
b-2*a
c ba
c a
ca
yx
y 2 x
y-2*x
Practice with Arithmetic Expressions
PracticewithArithmeticExpressions
int a = 1, b = 2, c = 3 ;
float x = 3.33, y = 6.66 ;
p
Expression NumericValue True/False
/
a + b 3 T
b-2*a 0 F
c ba 0 F
ca
c a 2 T
yx 3.33 T
y-2*x
y 2 x 0.0 F
StructuredProgramming
Allprogramscanbewrittenintermsofonly
threecontrolstructures
Sequence,selectionandrepetition
Thesequence structure
Unlessotherwisedirected,thestatementsare
executedintheorderinwhichtheyarewritten.
Theselection
Th l i structure
Usedtochooseamongalternativecoursesof
action.
action
Therepetition structure
Allows
Allowsanactiontoberepeatedwhilesome
an action to be repeated while some
conditionremainstrue.
Selection:theifstatement
if ( condition )
{
statement(s) /* body of the if
statement */

}
Thebracesarenotrequiredifthebodycontainsonlya
single statement
singlestatement.

However,theyareagoodideaandarerequiredbythe
CCodingStandards.
d d d
Examples
if ( age >= 18 )
{
printf(Vote!\n) ;
}
if ( value == 0 )
{
printf(You entered a zero.\n) ;
printf (Please try again.\n) ;
}
Good Programming Practice
GoodProgrammingPractice
Alwaysplacebracesaroundthebodyofanif
statement.
Advantages:
Easiertoread
Willnotforgettoaddthebracesifyougoback
andaddasecondstatementtothebody
Lesslikelytomakeasemanticerror
Indentthebodyoftheifstatement3to4
spaces
p beconsistent!
Selection: the ifelse
Selection:theif elsestatement
statement
if ( condition )
{
statement(s)/*if
statement(s)/ if clause */
/
}
else
l
{
statement(s) /*else clause */
}
Example
if ( age >= 18 )
{
printf(Vote!\n) ;
}
else
{
printf(Maybe next time!\n) ;
}
GoodProgrammingPractice
Alwaysplacebracesaroundthebodiesoftheif
and else clauses of an ifelse
andelseclausesofanif elsestatement.
statement.
Advantages:
Easiertoread
Easier to read
Willnotforgettoaddthebracesifyougobackand
add a second statement to the clause
addasecondstatementtotheclause
Lesslikelytomakeasemanticerror
IIndentthebodiesoftheifandelseclauses3to
d t th b di f th if d l l 3t
5spaces beconsistent!
NestingofifelseStatements
g
if ( condition1 )
{
statement(s)
}
else if ( condition2 )
{
statement(s)
}
. . . /* more else clauses may be here */
else
{
statement(s) /* the default case */
}
Good Example : 2 if 2 else
GoodExample:2if2else
if ( value == 0 )
{
printf(Value you entered was 0\n);
}
else if ( value < 0 )
{
printf(%d
p t ( %d is
s negative.\n,
egat e.\ , value)
a ue) ;
}
else
{
printf(%d is positive.\n, value) ;
}
BadExample:2if1else
if ( n > 0 )
if ( a > b )
z=a;
a if ( n > 0 )
else {
;
z=b; if (a> b)
z=a;
if ( n > 0 ) }
if ( a > b ) else
z=a; z=b;
else
z=b;
Indentationwillnotensureresult:
else matchwithclosestif
CodeofRedboxbehaveslikeCodeofGreenbox
Gotcha! =versus==
int a = 2 ;
if ( a = 1 )/
)/* semantic(logic)
( g ) Err! */
/
{
printf (
(aa is one\n)
one\n ) ;
}
else if (a == 2 )
{
printf (
(aa is two\n)
two\n ) ;
} else {
printf
i tf (a
( i is %d\
%d\n,
a)) ;
}
Gotcha..
Thestatementif(a=1)issyntacticallycorrect,so
noerrormessagewillbeproduced.(Somecompilers
g p ( p
willproduceawarning.)However,asemantic(logic)
errorwilloccur.
Anassignmentexpressionhasavalue
h l thevalue
h l
beingassigned.Inthiscasethevaluebeingassigned
is 1, which is true.
is1,whichistrue.
Ifthevaluebeingassignedwas0,thentheexpression
wouldevaluateto0,whichisfalse.
ThisisaVERYcommonerror.So,ifyourifelse
structurealwaysexecutesthesame,lookforthis
typographical error
typographicalerror.
LogicalOperators
Sofarwehaveseenonlysimpleconditions.
if ( count > 10 ) . . .
Sometimesweneedtotestmultipleconditionsin
order to make a decision
ordertomakeadecision.
Logicaloperators areusedforcombiningsimple
conditions to make complex conditions.
conditionstomakecomplexconditions.
&&isAND if(x>5&&y<6)
||isOR if(z==0||x>10)
!
!isNOT
is NOT if (! (bob > 42) )
if(!(bob>42))
Example Use of &&
ExampleUseof&&

if ( age < 1 && gender == m)


{
printf (Infant boy\n) ;
}
Truth Table for&&
TruthTable for &&
Expression1 Expression2 Expression1 &&Expression
&& Expression2

0
000
0 0
0nonzero0
nonzero00
nonzerononzero 1

Exp1 &&Exp
&& Exp2 &&&&Exp
&& && Expn willevaluateto1(true)only
will evaluate to 1 (true) only
ifALLsubconditions aretrue.
Example Use of ||
ExampleUseof||

if (grade==E || grade==F)
{
printf(See you next semester!\n) ;
}
Truth Table for ||
TruthTablefor||
Expression1 Expression2 Expression1 ||Expression
|| Expression2

0
000
0 0
0nonzero1
nonzero01
nonzerononzero 1

Exp1 &&Exp
&& Exp2 &&&&Exp
&& && Expn willevaluateto1(true)if
will evaluate to 1 (true) if
onlyONEsubcondition istrue.
Example Use of !
ExampleUseof!

if (!(x==2))
(!( 2)) /* S
Same as (x!=2)
( ! 2) */
{
printf(x is not equal to 2) ;
}
Truth Table for !
TruthTablefor!
Expression ! Expression
!Expression

0
01
1
nonzero0
Operator Precedence and Associativity
OperatorPrecedenceandAssociativity
Precedence Associativity

() lefttoright/insideout
/
++ ! +(unary) (unary)(type) righttoleft
* / %
*/% left to right
lefttoright
+(addition) (subtraction) lefttoright
<<=>>= left ot right
leftot
==!= lefttoright
&& lefttoright
|| lefttoright
=+==*=/=%= righttoleft
,(comma) righttoleft
Thanks

48

Вам также может понравиться