# Conditional Statements Syntax

Document Sample

```					       Conditional Statements                                                  Outline
For computer to make decisions, must be able        II. Program Basics
to test CONDITIONS                                   G. Expressions
3. Binary operators
relational operators == != < > <= >=
IF it is raining                                             logical operators && || !
7. Logical data
THEN I will not go outside
H. Statements
3. If
IF Count is not zero                                     4. If-Else
matching else
THEN the Average is Sum divided by Count
5. Switch
default
break
Conditions specified using logical data

Logical Data in C                                    Logical Expressions
• no explicit logical type                          • Relational operators:
• int and char values can be treated as logical        – operators to compare two values
values                                               – syntax: expr1 relop expr2
• two possible logical values                          – expressions must be of same type (any)
0 or ‘\0’ - false                                 • Logical operators:
anything else - true                                 – operators to logically combine logical values
• specific operators produce logical values            – produce complex combinations of conditions
– operators apply to logical values

Relational Operators                                  Relational Examples
Operator                  Meaning               A: 4     B: 3        C: 2.5
X == Y                  X equal to Y            A < B 0 (false)
‘A’ < ‘B’ 1 (true)
X != Y                X not equal to Y
X < Y                  X less than Y           When chars compared, ASCII codes compared
X > Y                X greater than Y          ‘A’ != ‘a’ 1 (true)
X <= Y            X less than or equal to Y
Note, expressions must be of same type
X >= Y           X greater than or equal to Y   But, implicit conversions will be done
B > C 1 (true), B converted to float

1
Combined Expressions                                    Complex Example
Complex combinations of operations can be             10 % 4 * 3 - 8 <= 18 + 30       / 4 - 20
used:
2   * 3 - 8 <= 18 + 30       / 4 - 20
4<3+2
4< 5                                                       6   - 8 <= 18 + 30       / 4 - 20
1 (true)                                                   6   - 8 <= 18 +          7   - 20
Why isn’t expression evaluated as (4 < 3) + 2?                  -2   <= 18 +          7   - 20
Relational operators have lower precedence than
arithmetic operators, higher than assignment                -2   <=    25             - 20
Have left-associativity                                       -2   <=                   5
Operator      Precedence
> < >= <=         10                                               1 (true)
= !=               9

Logical Operators                                  Logical Expression
• Simple (relational) logical expressions true        Syntax:
or false depending on values compared
• Compound logical expressions built out of             LogExpr1 LogicalOp LogExpr2 (&& ||)
logical combinations of simple expressions            LogicalOp LogExpr (!)
• Examples:
“I am standing in a lecture hall AND
the moon is made of green cheese”                  (2 < 3) && (17 != 29) /* && - AND */
is false, but                                          1    &&      1      /* true AND true */
“I am standing in a lecture hall OR
the moon is made of green cheese”                           1             /* true */
is true

AND (&&) and OR (||)                                    Logical Examples
• AND (&&) of two logical expressions:                month is 2, year is 1999
resulting compound expression true when             (month == 2)   && ((year % 4) == 0)
both expressions true                                   1 (true)   && ((year % 4) == 0)
• OR (||) of two logical expressions:                     1          && (      3    == 0)
expression true when either expression true             1          &&             0 (false)
0 (false)
• Truth table:
E1            E2       E1 && E2    E1 || E2    day is 6
1   (true)    1   (true)    1 (true)    1 (true)    (day == 0) || (day == 6)
1   (true)    0   (false)   0 (false)   1 (true)     0 (false) || (day == 6)
0   (false)   1   (true)    0 (false)   1 (true)     0         || 1 (true)
1 (true)
0   (false)   0   (false)   0 (false)   0 (false)

2
Short-Circuit Aspect                                                Negation
• && and || are short-circuit operators - if the        • Arithmetic negation:
-(4*A*C)
first operand determines the value, the                    Operator minus (-) negates numeric value
second operand is not evaluated                       • Logical negation
• first operand of && is 0, result is 0 without              Logical operator (!) negates logical value
E               ! E
evaluating second operand                                  1 (true)        0 (false)
• first operand of || is 1, result is 1 without              0 (false) 1 (true)
evaluating second operand                                  Example: ! (3 > 4)
! 0 (false)
• second operand evaluated when needed                                 1 (true)

Complex Expressions                                                  Example
Expressions can be built using arithmetic,
relational and logical operators                   !((-5 >= -6.2) || (7 != 3) && (6 == (3 + 3)))
!(    1 (true)        || (7 != 3) && (6 == (3 + 3)))
!((-5 >= -6.2) || (7 != 3) && (6 == (3 + 3)))
!(    1               || 1 (true) && (6 == (3 + 3)))
operator                 precedence, associativity   !(    1               || 1            && (6 ==         6   ))
+ - (unary) ! & *        15 right
(typename)               14 right                    !(    1               || 1            &&   1 (true)         )
* / %                    13 left
+ - (binary)             12 left                     !(    1               ||             1 (true)               )
< > <= >=                10 left
== !=                     9 left                     !                     1 (true)
&&                        5 left                                0 (false)
||                        4 left
assignments               2 right

Decision Making                                              IF Statement
• Problem: input two numbers and store the              • Syntax: if (LogicalExpr) Statement
largest in Big                                        • Program context:
statement1;
Num1: 17 Num2: 53 Big: 53                                 if (LogicalExpr) statement2;
• Algorithm                                                  statement3;
• Order of execution:
1. Input Num1 and Num2                                         LogicalExpr
2. Store largest of Num1 and Num2 in Big                  1 (true)    0 (false)
2.1 Store Num1 in Big                                  statement1 statement1
2.2 IF Num2 > Num1 THEN store Num2 in Big              statement2 statement3
statement3

3
Flow of Execution                      Flow Chart for our Problem
statement1                                     input Num1
input Num2

Store Num1 in Big
Logical        true
statement2
Expression
true
Num2 > Num1                     Store Num2 in Big
false
false
statement3

Code for Solution                                 Trace of Solution
int findMax(int Num1, int Num2) {            Trace of findMax(17,53):
int Big;
Num1        Num2         Big
Big = Num1;                              statement                        17          53           ?
if (Num2 > Num1) Big = Num2;             Big = Num1;                                               17
return Big;                              if (Num2 > Num1)
Big = Num2;                                                 53
}
return Big;

Trace of Solution                  Executing > 1 Statement in an If
Trace of findMax(9,6):                       • What if you want to execute > 1 stmt in If?
statement1
Num1     Num2   Big
statement                9        6     ?
Logical           true
Big = Num1;                             9                   Expression                  statement2
statement3
if (Num2 > Num1)                                                                        statement4
false
return Big;
statement5

4
> 1 Stmt in an If                                       > 1 Stmt in an If (A solution)
Does this work?                                                     Solution - use a compound statement:
Statement1;
If (LogicalExpr)                                                    Statement1;
Statement2;                                                       If (LogicalExpr) {
Statement3;                  P
Statement2;
Statement4;
Statement5;                                                           Statement3;
Statement4;
No, the indenting is irrelevant, section P is:
If (LogicalExpr)                                                    }
Statement2;                                                       Statement5;
Statement3;
Statement4;

Statement in If                                                Two-Way Selection
Any statement reasonable as the single                              • Sometimes desirable for statement to be executed
statement in if                                                      when Logical Expression false
statement1
– expression statement
• assignment statement
• function call ( printf, scanf, etc.)                                          false    Logical      true
statement3                                 statement2
Expression
– compound statement
– if statement
statement4

Two-Way Selection with If                                                      If-Else Statement
statement
1

• Possible to use                                                      • Syntax:
if (LogicalExpr)
combinations of if:                 Logical      true
statement2        StatementA
Expression
Statement1;                                                            else
if (LogicalExpr)                        false                            StatementB
Statement2;
if (!(LogicalExpr))                             true                                 false     Logical      true
! Logical                            statementB                                  statementA
Statement3;                    Expression
statement3                             Expression
Statement4;
false
• But not efficient
statement4

5
FindMax with If-Else                            Using If-Else for Robustness
int findMax(int Num1, int Num2) {
int Big;                                            float calcAverage(float sum,
Big = Num1;                  /* 1 assign + */         int count) {
if (Num2 > Num1) Big = Num2; /* 1 test + */
return Big;                  /* maybe 1 assign */     if (count == 0)
} /* test plus 1 or 2 assigns */
return 0.0;
int findMax(int Num1, int Num2) {
int Big;                                              else
if (Num2 > Num1) /* 1 test + */                         return sum / count;
Big = Num2;     /* 1 assign or */                 }
else
Big = Num1;     /* 1 assign */
return Big;                                         • Note return statement for each condition
} /* test plus 1 assign */

Compound Statements and If-Else                       Programming Tip: Compound Stmt
if ((year % 4) == 0) {                                • Does not hurt to always use compound statements
for if, if-else statements
printf(“Leap year\n”);                                 if (LogicalExpr) {
/* statement or statements */
numDays = 366;                                         }
}
if (LogicalExpr) {
else {                                                     /* statement(s) */
}
printf(“Not a leap year\n”);                           else {
numDays = 365;                                           /* statement(s) */
}
}                                                     • Easy to add statements later

Programming Tip: Indenting                          Programming Tip: Conditions
• Use indenting to make code more clear
• Code most likely conditions first
– indent statements in function definition to
clearly identify body of function                • Code positive conditions where possible
– indent statement(s) executed for if by fixed
amount (2,3 chars) every time                    • Code parts of solution executed most often
– for ifs within an if indent further
– indent else statements(s) similarly                first
– may want to make {,} match (on separate lines)

6
Multiway Selection                                Multiway Flow Chart
• Multiway if more than 2 alternatives                           Score        true
Failing
<= 55
• Example:
false
Student Score                 Message
0-55                          Failing
Score        true
Unsatisfactory
56-65                         Unsatisfactory                   <= 65

66-100                        Satisfactory                         false

• If-Else has two alternatives, to do multiway,                Satisfactory

string together If-Else statements

Multiway with If-Else                      Indenting If-Else Combinations
if (score <= 55)                                  • Multiway if-else statements sometimes
printf(“Failing\n”);                              indented:
if (score <= 55)
else                                                   printf(“Failing\n”);
if (score <= 65)                                   else if (score <= 65)
printf(“Unsatisfactory\n”);
printf(“Unsatisfactory\n”);                      else
else                                                 printf(“Satisfactory\n”);
printf(“Satisfactory\n”);                     • Rule for else: else matches most recent if

Conditions Checked in Reverse                              Ordering Conditions
if (score > 65)
Score       true                       printf (“Satisfactory\n”);
Satisfactory
> 65                                else if (score > 55)
printf (“Unsatisfactory\n”);
false                            else
printf (“Failing\n”);
true
• But must check conditions in correct order
Score
> 55
Unsatisfactory    if (score > 55)
printf (“Unsatisfactory\n”);
false
else if (score > 65)
printf (“Satisfactory\n”);
Failing                              else
printf (“Failing\n”);
• Score of 70 would produce “Unsatisfactory”

7
Multiway with If Statements                              Program Robustness
• Possible but inefficient:                       • Example assumes score in interval [0,100]
if (score <= 55)                                but doesn’t check
if ((score > 55) && (score <= 65))               if ((score >= 0) && (score <= 100))
printf(“Unsatisfactory\n”);                      /* print message */
if (score > 65)                                  else

Completed Code                                       Nesting Example
if ((score >= 0) && (score <= 100)) {             if (A > 0)                  false                     true
A>0
if (score <= 55)                                  if ((A % 2) == 0)
printf(“Failing\n”);                            S1 = S1 + A;                                  (A % 2)
A == 0
else if (score <= 65)                           else                                              == 0
S2 = S2 + A;                                              true
printf(“Unsatisfactory\n”);                                     false         true          false
else                     NS =                  S2 =        S1 =
else                                                                             printf
if (A == 0)           NS + A                S2 + A     S1 + A
printf(“Satisfactory\n”);
printf(“A zero\n”);
}                                                                                    printf("All done")
else
else                                                  NS = NS + A;
printf (“Bad score: %d\n”,score);               printf(“All done.\n”);

Matching Else Example                                Matching Single Else

false                    true          • Easy to make mistake
X<0
if (X < 0)
if (Y < 0)
PosCount++;
Y<0
else
true
false                      NegCount++;
Increment                   Increment
NegCount                    PosCount    • Despite indenting, else matches wrong if
• PosCount updated when X < 0, Y >= 0

8
Matching Single Else Solutions                            Choosing Conditions
if (X < 0)                if (X < 0) {
Selection      Example       C Statement
if (Y < 0)                if (Y < 0)

PosCount++;
PosCount++;             One way          X>0              If
} /* compound stmt */
else                    else                        Two way         X>0             If-Else
; /* empty */           NegCount++;                               X <= 0
else
NegCount++;             if (X >= 0)                 Multiway     0 <= X <= 10       Nested
NegCount++;                            11 <= X <= 20     If-Elses
else
21 <= X <= 30
if (Y < 0)
PosCount++;

Another Multiway Method                                 Switch Statement
• More readable approach: switch statement
• Consider another if ((score == 9) ||                switch (score) {
(score == 10))                     case 9: case 10:
else if ((score == 7) ||
9-10      A                                         case 7: case 8:
(score == 8))
7-8       B       grade = ‘B’;                        break;
5-6       C     else if ((score == 5) ||            case 5: case 6:
0-4       F       (score == 6))                       grade = ‘C’;
else                                case 0: case 1: case 2: case3: case 4:

Switch Format                                       Switch Rules
switch ( Expression) {
case const1-1: case const1-2: ...               • Expression must be integral type (no float)
statement                                     • Case labels must be constant values
statement
...                                           • No two case labels with same value
case const2-1: case const2-2: ...
statement                                     • Two case labels can be associated with
statement
...
same set of statements
default: ...                                    • Default label is not required
statement
statement                                     • At most one default label
...
}

9
Switch Rules                                 Executing Switch Example
switch (score) {
Evaluating                                                 case 9: case 10:
• score is 7:
case 7: case 8:              grade = ‘C’
–   look for corresponding label                           grade = ‘B’;
–   if no corresponding label look for default           case 5: case 6:
grade = ‘C’;           • score is 5:
–   if no corresponding label or default, do nothing   }                              grade = ‘C’
–   execute all statements from label to }             • score is 9:
grade = ‘A’             • not quite what we
ALL statements from label to } ???

The break Statement                                              default case
The default case can be used to deal with robustness
issues (score is < 0 or > 10)
• break used to indicate a set of statements is             switch (score) {
case 9: case 10:
finished (and no more should be executed)                     grade = ‘A’;
break;
• syntax: break;                                              case 7: case 8:
• break says to stop executing and go to the                    break;
case 5: case 6:
next } (skipping any statements in between)                   grade = ‘C’;
break;
• add after each set of cases                                 case 0: case 1: case 2: case3: case 4:
break;
default:
}

Other Expression Types                                  When Not to Use Switch
• Any integral type can be used as expression            • Example: Case 0 <= X <= 100
• Cases must match                                          switch        (x) {
char married;                                               case        0: case 1: case 2: case 3:
switch (married) {                                          case        4: case 5: case 6: case 7:
case ‘S’: case ‘s’:                                       …
printf(“single”); break;
case        100:
case ‘D’: case ‘d’:
printf(“divorced”); break;                            …
case ‘M’: case ‘m’:                                     }
printf(“married”);                                 • Better to use nested ifs
}

10

```
DOCUMENT INFO
Shared By:
Categories:
Stats:
 views: 7 posted: 1/7/2011 language: English pages: 10
Description: Conditional Statements Syntax document sample
How are you planning on using Docstoc?