Documentc

Embed Size (px)

DESCRIPTION

c

Citation preview

  • 7/18/2019 c

    1/64

    Slide 1 of 64Lecture C

    Lesson 3: Conditions and Loops

    Unit 1: The if Statement

  • 7/18/2019 c

    2/64

    Slide 2 of 64Lecture C

    The if Statement

    The Java if statementhas the following syntax:

    if (boolean-condition)

    statement;

    If the Boolean condition is true, the statement isexecuted if it is false, the statement is s!i""ed

    This "rovides #asic decision ma!ing ca"a#ilities

  • 7/18/2019 c

    3/64

    Slide 3 of 64Lecture C

    Tempreture

    classTemperature {

    static final intTHRESHOLD = 65;

    public static voidmainStrin!"# ar!s$ {

    %nputRe&uestor input = ne'%nputRe&uestor$;

    inttemperature =input(re&uest%nt)Enter t*e temperature+,$;

    S-stem(out(println).urrent temperature )/

    temperature$;

    if temperature 0 THRESHOLD$ S-stem(out(println)%t1s cold in *ere2,$;

    3

    3

  • 7/18/2019 c

    4/64

    Slide 4 of 64Lecture C

    If statement flow diagram

    if (condition)

    statement;

    condition

    condition

    statement

    statement

    true

  • 7/18/2019 c

    5/64

    Slide 5 of 64Lecture C

    oolean !"pressions

    The condition of anifstatement must evaluate to a trueor false result

    Java has several e$uality and relational o"erators:

    %ore com"lex Boolean ex"ressions are also "ossi#le

    Operator Meaning

    == equal to!= not equal to

    < less than

    greater than

    >= greater than or equal to

  • 7/18/2019 c

    6/64

    Slide 6 of 64Lecture C

    loc# Statements

    Several statements can #e grou"ed together into a block

    statement

    Bloc!s are delimited #y #races

    & #loc! statement can #e used wherever a statement is

    called for in the Java syntax

    if (boolean-condition){

    statement1;

    statement2;

    }

  • 7/18/2019 c

    7/64Slide $ of 64Lecture C

    !"ample % Temperature2

    classTemperature4 {

    static final intTHRESHOLD = 65;

    public static voidmainStrin!"# ar!s$ {

    %nputRe&uestor input = ne'%nputRe&uestor$;

    inttemperature =

    input(re&uest%nt)Enter t*e temperature+,$;

    S-stem(out(println).urrent temperature )/temperature$;

    iftemperature 0 THRESHOLD$ {

    S-stem(out(println)%t1s cold in *ere2,$;

    S-stem(out(println)ut 'e1ll survive(,$;

    3

    3

    3

  • 7/18/2019 c

    8/64Slide & of 64Lecture C

    If '' !lse Statement

    &nelseclause can #e added to anifstatement to

    ma!e it an if-else statement:

    if (condition)

    statement1;

    else

    statement2;

    If the condition is true, statement1 is executed if thecondition is false, statement' is executed

  • 7/18/2019 c

    9/64Slide ( of 64Lecture C

    !"ample % Temperature3

    classTemperature {

    static final int7REE8%9:

  • 7/18/2019 c

    10/64Slide 1) of 64Lecture C

    If*else flow diagram

    if (condition)

    statement1;

    else

    statement2;

    conditioncondition

    statement2statement2

    true

    statement1statement1

  • 7/18/2019 c

    11/64Slide 11 of 64Lecture C

    +ested If statements

    Since an (If) statement is a statement, it can a""ear inside

    another if statement*

    if (condition1)

    if (condition2)

    statement;

    It can also a""ear in an (else) clause

    if (condition1) statement1;

    else if (condition2)

    statement2;

  • 7/18/2019 c

    12/64Slide 12 of 64Lecture C

    +ested If !"ample?? Reads 4 inte!ers and compares t*em

    class.ompareE@ample {

    public static voidmainStrin!"# ar!s$ {

    %nputRe&uestor input = ne'%nputRe&uestor$;

    inta = input(re&uest%nt)7irst number+,$;

    intb = input(re&uest%nt)Second number+,$;

    ifa 2= b${ ifa A b$

    S-stem(out(printlna/, is !reater,$;

    else

    S-stem(out(printlnb/, is !reater,$;

    3else

    S-stem(out(println)t*e numbers are e&ual,$;

    3

    3

  • 7/18/2019 c

    13/64Slide 13 of 64Lecture C

    Chec#ing ,our Input +hen re$uesting in"ut from the user, !ee" in mind that the in"ut may #e invalid*

    It is good "ractice to chec! the validity of user in"ut

    intnumberOf%tems =

    input(re&uest%nt)Enter number of items+,$;

    ifnumberOf%tems 0 B$ { S-stem(out(println

    )9umber of items must be positive2,$;

    3 else{

    doubleprice = numberOf%tems C %TE

  • 7/18/2019 c

    14/64Slide 14 of 64Lecture C

    Lesson 3: Conditions and Loops

    Unit ': Boolean x"ressions

  • 7/18/2019 c

    15/64Slide 15 of 64Lecture C

    Logical -perators

    Boolean ex"ressions may #e com#ined using logical

    operators

    There are three logical o"erators in Java:

    They all ta!e Boolean o"erands and "roduce Booleanresults

    -ogical ./T is unary 0one o"erand, #ut logical &.2 and

    /3 are #inary 0two o"erands

    Operator Operation

    ! LogicalNOT&& LogicalAN

    Logical O"

  • 7/18/2019 c

    16/64Slide 16 of 64Lecture C

    Logical +-T

    The logical ./T is also called logical negation or logical

    com"lement

    If ais true, !ais false if ais false, then !ais true

    -ogical ex"ressions can #e shown using truth tables

    a !a

    false true

    true false

  • 7/18/2019 c

    17/64Slide 1$ of 64Lecture C

    Logical .+/

    The ex"ression a && #is true if #oth aand#are true,

    and false otherwise

    Truth ta#les show all "ossi#le com#inations of all terms

    a # a && #

    false false false

    false true false

    true false falsetrue true true

  • 7/18/2019 c

    18/64Slide 1& of 64Lecture C

    Logical -0

    The ex"ression a #is true if aor bor #oth are true,

    and false otherwise

    a # a #

    false false false

    false true true

    true false truetrue true true

  • 7/18/2019 c

    19/64Slide 1( of 64Lecture C

    Logical -perators

    -ogical o"erators are used to form more com"lex logical

    ex"ressions

    -ogical o"erators have "recedence relationshi"s #etween

    themselves and other o"erators

    ifa0 FF aG42=B$

    S-stem(out(println

    )T*e input s*ould be an even even number2,$;

  • 7/18/2019 c

    20/64Slide 2) of 64Lecture C

    Logical -perators

    4ull ex"ressions can #e evaluated using truth ta#les

    a < 1 a$2!=% a

  • 7/18/2019 c

    21/64

    Slide 21 of 64Lecture C

    oolean ariales

    Boolean ex"ressions can #e assigned to Boolean

    varia#les

    Boolean varia#les are Boolean ex"ressions

    #oolean# c;

    # = (' > 1);

    c = ('>1) && ('

  • 7/18/2019 c

    22/64

    Slide 22 of 64Lecture C

    !"ample % 0ightTriangle?? Receives t*e len!t* of t*e ed!es of a trian!le

    ?? and determine if t*is is a ri!*t trian!le

    classRi!*tTrian!le {

    public static voidmainStrin!"# ar!s$ {

    %nputRe&uestor input = ne'%nputRe&uestor$;

    floata = input(re&uest%nt)Ed!e+,$;

    float b = input(re&uest%nt)Ed!e4+,$; floatc = input(re&uest%nt)H-potenuse+,$;

    booleantest = aCa/bCb == cCc;

    iftest$

    S-stem(out(println)%t1s a ri!*t trian!le,$;

    else

    S-stem(out(println)%t1s not a ri!*t trian!le,$;

    3

    3

  • 7/18/2019 c

    23/64

    Slide 23 of 64Lecture C

    Lesson 3: conditions and loops

    Unit 56: The while Statement

  • 7/18/2019 c

    24/64

    Slide 24 of 64Lecture C

    The while statement

    & while statementhas the following syntax:

    34ile (condition)

    statement;

    If the condition is true, the statement is executed thenthe condition is evaluated again

    The statement is executed over and over until the

    condition #ecomes false

    If the condition of a34ilestatement is false initially, thestatement is never executed

    Therefore, we say that a34ilestatement executes 7ero

    or more times

  • 7/18/2019 c

    25/64

    Slide 25 of 64Lecture C

    hile statement flow diagram

    34ile (condition)

    statement;

    conditioncondition

    statementstatement

    true

  • 7/18/2019 c

    26/64

    Slide 26 of 64Lecture C

    !"ample % Counter

    ?? .ounts from to 5

    class.ounter { static final intL%%T = 5;

    public static voidmainStrin!"# ar!s$ {

    intcount = ; '*ilecount 0= L%%T$ {

    S-stem(out(printlncount$;

    count = count / ;

    3

    S-stem(out(println)done,$;

    3

    3

  • 7/18/2019 c

    27/64

    Slide 2$ of 64Lecture C

    !"amples % actors?? :ets an inte!er and prints its factors

    class7actorsE@ample {

    public static voidmainStrin!"# ar!s$ {

    %nputRe&uestor input = ne'%nputRe&uestor$;

    inta = input(re&uest%nt)Enter a number+,$;

    inti = ;

    S-stem(out(println)T*e divisors of )/a/, are+,$; '*ile i 0= a$ {

    ifaGi == B$ {

    S-stem(out(printlni$;

    3

    i = i / ;

    3

    3

    3

  • 7/18/2019 c

    28/64

    Slide 2& of 64Lecture C

    Infinite Loops

    The #ody of a34ileloo" must eventually ma!e the

    condition false If not, it is an infinite loop, which will execute until the user

    interru"ts the "rogram

    This is a common ty"e of logical error 88 always dou#le

    chec! that your loo"s will terminate normally

  • 7/18/2019 c

    29/64

    Slide 2( of 64Lecture C

    !"ample % oreer

    ?? T*is pro!ram contains an infinite loop

    class7orever { static final intL%%T = 45;

    public static voidmainStrin!"# ar!s$ {

    intcount = ; '*ilecount 0= L%%T$ {

    S-stem(out(printlncount$;

    count = count ;

    3

    3

    3

  • 7/18/2019 c

    30/64

    Slide 3) of 64Lecture C

    Lesson 3: conditions and loops

    Unit 9: %ore conditionals

  • 7/18/2019 c

    31/64

    Slide 31 of 64Lecture C

    The Conditional -perator

    Java has a conditional o"erator that evaluates a Boolean

    condition that determines which of two ex"ressions isevaluated

    The result of the chosen ex"ression is the result of the

    entire conditional o"erator

    Its syntax is:

    condition5 expression16

    expression2

    If the conditionis true, expression1is evaluated if it isfalse, expression2is evaluated

  • 7/18/2019 c

    32/64

    Slide 32 of 64Lecture C

    The Conditional -perator

    It is similar to an if8else statement, exce"t that it is an

    ex"ression that returns a value

    4or exam"le:

    If ais greater that#, then ais assigned toma'otherwise,#is assigned toma'

    The conditional o"erator is ternary, meaning it re$uires

    three o"erands

    intma@ = a A b$ I a + b;

  • 7/18/2019 c

    33/64

    Slide 33 of 64Lecture C

    The Conditional -perator

    &nother exam"le:

    If conte$uals 1, "ime"is "rinted, otherwise

    "imes"is "rinted

    *+stem,ot,./intln (78o/ c4ane is 79 cont 9

    ((cont == 1) 5 7ime76 7imes));

  • 7/18/2019 c

    34/64

    Slide 34 of 64Lecture C

    .nother Selection Statement

    The ifand the if-elsestatements are selection

    statements, allowing us to select which statement to"erform next #ased on some Boolean condition

    &nother selection construct, called the switch statement,

    "rovides another way to choose the next action

    The switchstatement evaluates an ex"ression, then

    attem"ts to match the result to one of a series of values

    xecution transfers to statement list associated with the

    first value that matches

  • 7/18/2019 c

    35/64

    Slide 35 of 64Lecture C

    The

    s3itc4Statement

    The syntax of the switch statement is:

    switch (expression) {

    case value1:

    statement-list1

    case value2:

    statement-list2

    case

    }

  • 7/18/2019 c

    36/64

    Slide 36 of 64Lecture C

    The s3itc4Statement

    The ex"ression must evaluate to an integral value, such

    as an integer or character

    The breakstatement is usually used to terminate the

    statement list of each case, which causes control to um"

    to the end of the switchstatement

    & defaultcase can #e added to the end of the list ofcases, and will execute if no other case matches

  • 7/18/2019 c

    37/64

    Slide 3$ of 64Lecture C

    The s3itc4Statement

    ?CC

    C > client t*at enables -ou to connect to t*eC banJ server and maJe remote banJin! operations(((

    C?

    public class anJ.lient {

    public static final intK%E>L>9.E = ;

    public static final intK%ES>K%9:S = 4;

    public static final int.>SHTR>9S7ER = ;

    public static final intK%EL>STOT%O9S = M;

    ?? (((

  • 7/18/2019 c

    38/64

    Slide 3& of 64Lecture C

    The s3itc4Statement

    ?? %nside t*e main loop of t*e client+

    intoption =%nputRe&uestor(re&uent%nt)Enter -our c*oice+,$;

    s'itc*option$ {

    caseK%E>L>9.E+

    s*o'alance$;

    breaJ;

    caseK%ES>K%9:S+

    s*o'Savin!s$;

    breaJ;

    default+ output(s*o'essa!e)9o suc* option2,$;

    3

  • 7/18/2019 c

    39/64

    Slide 3( of 64Lecture C

    Lesson 3: conditions and loops

    Unit ;: Shorthand /"erators

  • 7/18/2019 c

    40/64

    Slide 4) of 64Lecture C

    Shorthand -perators

    %any o"erations are very commonly used

    Java has shorthand notations for these increment and decrement o"erators

    assignment o"erators

    @ = @ / ;

    sum = sum / @;

  • 7/18/2019 c

    41/64

    Slide 41 of 64Lecture C

    The Increment and /ecrement -perators

    The increment operator099 adds one to its integer or

    floating "oint o"erand

    The decrement operator0-- su#tracts one

    The statement

    is essentially e$uivalent to

    cont99;

    cont = cont 9 1;

    -

  • 7/18/2019 c

    42/64

    Slide 42 of 64Lecture C

    The Increment and /ecrement -perators

    The increment and decrement o"erators can #e a""lied

    in "refix 0#efore the varia#le or "ostfix 0after the varia#leform

    +hen used alone in a statement, the "refix and "ostfix

    forms are #asically e$uivalent* That is,

    is e$uivalent to

    cont99;

    99cont;

    Th I d / -

  • 7/18/2019 c

    43/64

    Slide 43 of 64Lecture C

    The Increment and /ecrement -perators

    +hen used in a larger ex"ression, the "refix and "ostfix

    forms have a different effect

    In #oth cases the varia#le is incremented 0decremented

    But the value used in the larger ex"ression de"ends on

    the form

    :'./essions O.e/ation ale Of e'./ession

    count++ add 1 old value

    ++count add 1 new valuecount-- subtract 1 old value

    --count subtract 1 new value

    Th I t d / t - t

  • 7/18/2019 c

    44/64

    Slide 44 of 64Lecture C

    The Increment and /ecrement -perators

    If contcurrently contains 9;, then

    assigns 9; to totaland 9< to cont

    If contcurrently contains 9;, then

    assigns the value 9< to #oth totaland cont

    total = count//;

    total = //count;

    Th I t d / t - t

  • 7/18/2019 c

    45/64

    Slide 45 of 64Lecture C

    The Increment and /ecrement -perators

    If sum contains ';, what does this statement "rint=

    >rints the following result:

    2 2 2 2

    sum contains '< after the line is com"lete

    S-stem(out(println sum// / N N/

    //sum / N N/

    sum / N N/

    sum$;

    . i t - t

  • 7/18/2019 c

    46/64

    Slide 46 of 64Lecture C

    .ssignment -perators

    /ften we "erform an o"eration on a varia#le, then store

    the result #ac! into that varia#le

    Java "rovides assignment operatorsthat sim"lify that

    "rocess

    4or exam"le, the statement

    is e$uivalent to

    sum /= value;

    sum = sum / value;

    . i t - t

  • 7/18/2019 c

    47/64

    Slide 4$ of 64Lecture C

    .ssignment -perators

    There are many such assignment o"erators, always

    written as op=, such as:

    O.e/ato/ :'am.le :ialent to

    += x+=y x = x + y

    -= x-=y x = x - y

    *= x*=y x = x * y

    /= x/=y x = x / y

    %= x%=y x = x % y

    . i t - t

  • 7/18/2019 c

    48/64

    Slide 4& of 64Lecture C

    .ssignment -perators

    The right hand side of an assignment o"erator can #e a

    com"lete ex"ression The entire right8hand ex"ression is evaluated first, then

    com#ined with the additional o"eration

    Therefore

    /eslt ?= total-@N;

    is e$uivalent to

    result ?= total%9;

    /eslt = /eslt ? (total-@N);

  • 7/18/2019 c

    49/64

    Slide 4( of 64Lecture C

    Lesson 3: conditions and loops

    Unit 5

  • 7/18/2019 c

    50/64

    Slide 5) of 64Lecture C

    ore 0epetition Constructs

    In addition towhileloo"s, Java has two other

    constructs used to "erform re"etition:

    the dostatement

    the forstatement

    ach loo" ty"e has its own uni$ue characteristics

    ?ou must choose which loo" ty"e to use in each situation

    The d Statement

  • 7/18/2019 c

    51/64

    Slide 51 of 64Lecture C

    The doStatement

    The do statementhas the following syntax:

    do

    statement

    34ile (condition);

    The statementis executed until the condition#ecomes

    false

    It is similar to a whilestatement, exce"t that its

    termination condition is evaluated after the loo" #ody

    The d Statement

  • 7/18/2019 c

    52/64

    Slide 52 of 64Lecture C

    The doStatement

    The !ey difference #etween a doloo" and a whileloo"

    is that the #ody of the doloo" will execute at least once

    If the condition of a whileloo" is false initially, the #ody

    of the loo" is never executed

    &nother way to "ut this is that a whileloo" will execute

    7ero or more times and a doloo" will execute one or

    more times

  • 7/18/2019 c

    53/64

    Slide 53 of 64Lecture C

    /o Statement !"ample

    ?? :ets an inte!er and prints its factors

    class>v!E@ample {

    public static voidmainStrin!"# ar!s${

    %nputRe&uestor input = ne'%nputRe&uestor$;

    double@ sum=B count=;

    do{

    @ = input(Re&uestDouble)9e@t number+,$;

    sum /= @;

    count//;

    3 '*ile@ 2= B$;

    ?? B is a fla! indicatin! end of input S-stem(out(println)T*e avera!e is )/sum?count$;

    3

    3

    The do Statement flow diagram

  • 7/18/2019 c

    54/64

    Slide 54 of 64Lecture C

    The doStatement flow diagram

    statement

    condition

    false

    true

    The fo/ Statement

  • 7/18/2019 c

    55/64

    Slide 55 of 64Lecture C

    The fo/Statement

    %any loo"s have a common "attern, ca"tured #y the for

    statement The syntax of the for loopis

    fo/ (intialiation; condition; increment)

    statement;

    This is e$uivalent to

    initialiBation;

    34ile (condition) {

    statement;

    inc/ement;

    }

    The fo/ Statement: e"amples

  • 7/18/2019 c

    56/64

    Slide 56 of 64Lecture C

    The fo/Statement: e"amples

    xam"les:

    forintcount=; count 0 P5; count//$ {

    S-stem(out(println count$;

    3

    forintnum=; num 0= ma@; num = num C 4$ {

    S-stem(out(println )9e@t po'er of 4+ )/ num$;

    3

    The fo/ Statement

  • 7/18/2019 c

    57/64

    Slide 5$ of 64Lecture C

    The fo/Statement

    The initiali7ation is always "erformed once

    The condition of a forstatement is testedpriorto

    executing the loo" #ody 0li!e in the whilestatement

    Therefore, a forloo" will execute 7ero or more times

    4or loo"s are well suited for cases where the num#er of

    iterations is !nown #eforehand

    The increment is executed after each iteration of the loo"

    -mitting parts in a for Statement

  • 7/18/2019 c

    58/64

    Slide 5& of 64Lecture C

    -mitting parts in a forStatement

    ach ex"ression in the header of a forloo" is o"tional If the initiali7ation is left out, no initiali7ation is "erformed

    If the condition is left out, it is always considered to #e true, and

    therefore ma!es an infinite loo"

    If the increment is left out, no increment o"eration is "erformed

    Both semi8colons are always re$uired

    for;;$ {?? an infinite loop

    S-stem(out(println )beep,$;

    3

    ?? compute a value count for; count 0 ma@ ; count // $ {

    S-stem(out(println count$;

    3

    The fo/ Statement flow diagram

  • 7/18/2019 c

    59/64

    Slide 5( of 64Lecture C

    The fo/Statement flow diagram

    statement

    conditionfalse

    true

    initialization

    increment

    lti li ti T l ! l

  • 7/18/2019 c

    60/64

    Slide 6) of 64Lecture C

    ultiplication Tale !"ample

    classultiplicationTable {

    public static voidmainStrin!"# ar!s${

    forint Q= ; Q 0= B ; Q//$ {

    forint J= ; J 0= B ; J//$

    S-stem(out(printQCJ$;

    S-stem(out(println$; 3

    3

    3

    The #/eaC and contine statements

  • 7/18/2019 c

    61/64

    Slide 61 of 64Lecture C

    The#/eaCand continestatements

    The breakstatement, which we used with switch

    statements, can also #e used inside a loo" +hen the breakstatement is executed, control um"s to

    the statement after the loo" 0the condition is not

    evaluated again

    & similar construct, the continuestatement, can also #eexecuted in a loo"

    +hen the continuestatement is executed, control

    um"s to the end of the loo" and the condition is

    evaluated

    # d C ti ! l

  • 7/18/2019 c

    62/64

    Slide 62 of 64Lecture C

    rea# and Continue !"ampleclass>v!E@ample4 {

    public static voidmainStrin!"# ar!s${

    %nputRe&uestor in = ne'%nputRe&uestor$; double@ sum = B; count = B;

    '*iletrue${

    @ = in(Re&uestDouble$;

    if@ == B$breaJ;

    if@ 0 B$ {

    S-stem(out(println)Onl- positive numbers2,$;

    continue;

    3

    sum /= @ ;

    count // ;

    3 ?? continued on ne@t pa!e

    # d C ti ! l 27

  • 7/18/2019 c

    63/64

    Slide 63 of 64Lecture C

    rea# and Continue !"ample 27

    *+stem,ot,./intln(0T4e ae/ae is 09sm?cont);

    }

    }

    h d + d I d t ti 8

  • 7/18/2019 c

    64/64

    h, do e +eed Indentation8

    class-ster- {

    public static voidmainStrin!"# ar!s$ {%nputRe&uestor in = ne'%nputRe&uestor$;

    int dimension =

    in(re&uest%nt)