Presentation is loading. Please wait.

Presentation is loading. Please wait.

I F S TATEMENTS Tarik Booker CS 290 California State University, Los Angeles.

Similar presentations


Presentation on theme: "I F S TATEMENTS Tarik Booker CS 290 California State University, Los Angeles."— Presentation transcript:

1 I F S TATEMENTS Tarik Booker CS 290 California State University, Los Angeles

2 W HAT WE WILL C OVER … Intro Basic if syntax Expressions The bool type Else Statements Else-if Combining Expressions Operator Precedence

3 S CANF Another way to input data into the computer is to use scanf This can “scan” in characters from the console Format similar to printf int x; scanf(“%d”, &x); This puts the value of %d into x Different types for % (called format specifiers ) %d = decimal (integer) %c = character We will talk about others later…

4 S CANF (2) int x; scanf(“%d”, &x); Note the & sign before the x This is a pointer reference Outside the scope of this class Passes to scanf the memory address of the variable x Keep the same format – don’t worry about pointers

5 I NTRODUCTION There will be situations when you only need something to be true, or false Is it raining? Umbrella Is the number even? (How do I check?) We have in C an if statement If something is true, we do something If something is false (not true), we don’t do it.

6 T HE I F S TATEMENT Two different ways to write: if ( Execute the statement if( { Execute all statements in the block }

7 I F S TATEMENT (2) Ex: if(5 <10) printf(“Five is less than 10! \n”); if(5<10) { printf(“Five is less than 10!\n”); printf(“That should always be true!\n”); } Note: if you want more than one line contained within the if statement, you need to use curly braces

8 I F S TATEMENT (3) Keep in mind that if you don’t include multiple statements in a if block (using {}), the statement will be executed afterward always! Ex: if(5<10) printf(“Five is less than 10!\n”); printf(“That should always be true!\n”); Second statement is always executed

9 E XPRESSIONS Expression A statement, or series of statements that evaluate to a single value We have used them before 10*x+pow(y,2) Conditional Expression Result of the expression is either true, or false True if the expression results in a nonzero number False if the expression results in zero.

10 E XPRESSIONS (2) C also has keywords, true and false true = 1 false = 2 If you perform a comparison, the result evaluates to either true (nonzero) or false (zero) Use relational operators to compare!

11 R ELATIONAL O PERATORS Relational Operators Less than< Less than or equal to<= Greater than> Greater than or equal to>= Equal to==( double equals ) Not equal to!= These result in true (1) or false(0) when evaluated int x; x = 7 < 0; What value is x?

12 C OMPARISON O PERATOR Notice the Comparison Operator == Called the “double equals” sign For comparing two different numbers! DO NOT CONFUSE THIS WITH THE ASSIGNMENT OPERATOR! Assignment operator = Assigns a value to a variable.

13 B OOLEAN D ATA T YPES Booleans are the result of comparison operators (also called relational operators ) Greater than (>), Less than, (<), etc. In C, we can store the result of these comparisons by using the bool data type! bool x; x = 5<7; What is x? (Named after George Boole) George Boole 1815 - 1864

14 B OOLEAN D ATA T YPES (2) What is the result of: 5<7? 4>=7? 7<=7? 5==5? 5!=5?

15 E LSE S TATEMENTS There may be a situation where you want to do something if the condition fails Either/or If something is true do something If not true, do something else This is used in an else statement if(<expression) { Statements } else { Statements }

16 E LSE S TATEMENTS (2) What happens in this program? #include int main() { int num; printf(“Enter a number: ”); scanf(“%d”, &num); if(num < 0) { printf(“You entered a negative number.\n”); } else { printf(“You entered a positive number.\n”); } return 0; }

17 N ESTED IF S TATEMENTS You can have an if statement within another if statement !!!!! Referred to as nested Nested if statements Nested ifs You can also have if-else statements within other if or if-else statements Any legal C statements can be within if or if-else

18 N ESTED IF S TATEMENTS (2) Examples: if(10==5) { true_statement(s); } else { alternate_false_statement(s); } else { alternate_false_statement(s); } if(10==5) { true_statement(s); } else { if(10==5) { true_statement(s); } else { alternate_false_statement(s); }

19 N ESTED IF AND M ULTI -W AY S TATEMENTS (3) Examples (2): double score = 92.5; int test = 1; … test = 5; if(test==1) { statement(s); } else { if(score >=90.0) { System.out.println(“Grade is A”); } else { System.out.println(“Grade is not A”); }

20 C OMMON E RRORS Forgetting braces Don’t forget the correct braces Adding a semi-colon at the end of the if condition Completely legal, so the compiler won’t notice! Dangling else Always specify multiple else statements Else clauses always match the most recent unmatched if clause Comparing equality of two floating-point values NOTE! You cannot reliably test equality of two floating-point values!

21 L OGICAL O PERATORS You can create compound (multiple) boolean expressions Gives the results of multiple true/false results C Logical Operators: !Not(logical negation) &&and (logical conjunction) ||or(logical disjunction)

22 L OGICAL O PERATORS (2) AND (&&) True AND True = ? True AND False = ? False AND True = ? False AND False = ? OR (||) True OR True = ? True OR False = ? False OR True = ? False OR False = ?

23 L OGICAL O PERATORS (3) AND(True when both are true; false elsewhere) True AND True = T True AND False = F False AND True = F False AND False = F OR(True when at least one is true; false when both are) True OR True = T True OR False = T False OR True = T False OR False = F

24 L OGICAL O PERATORS (4) You can use logical operators in expressions Expressions return boolean values Ex: age = 22; height = 60; //in inches What is the result? (age == 18) && !(height < 72); (10 > 7) || (age != 22)

25 S HORT C IRCUITING CHECKS Note! If the first expression of a Boolean is false and you are using &&, the second expression will not be evaluated! Called short circuiting! Useful to write expressions where the second condition should only be checked if the first condition is true Ex: Guarding against division by zero if(x != 0 && 10 / x < 2) { printf(“10 / x is less than 2”); } When evaluated, the program checks if x is 0 (if it can divide) Prevents program from crashing

26 C ONDITIONAL E XPRESSIONS You can shorten an if-else statement to an expression Called a conditional expression (operator) Also the “if-then” Also the ternary operator Use ? : boolean_expression ? expression1 : expression2; Read: if boolean_expression is true, then execute expression1 If boolean_expression is false, then execute expression2

27 C ONDITIONAL E XPRESSIONS (2) Useful in not having to write a lot of statements max = (num1 > num2) ? num1 : num2; System.out.println((num % 2 == 0)? “Num is even”: “Num is odd”); However, don’t use too often! Code won’t be as readable!

28 O PERATOR P RECEDENCE Precedence Chart: Postfix(var++, var--) +, - (Unary plus and minus); Prefix ( ++var, --var) (type) (Casting) ! (Not) *, /, %(Multiplication, Division, Remainder) +,-(Addition, Subtraction) = (Relational) ==, !=(Equality) &&(AND) ||(OR) =, +=, -=, *=, /=, %=(Assignment Operators)

29 O PERATOR P RECEDENCE (2) Assignment operators are right associative Start on the immediate right a = b += c = 5; Legal, but don’t do this! DON’T DO THIS!!!!!! Limits readability


Download ppt "I F S TATEMENTS Tarik Booker CS 290 California State University, Los Angeles."

Similar presentations


Ads by Google