lecture06-feb1

lecture06-feb1 - Lecture 6 Announcements Assignment 2 out...

This preview shows pages 1–2. Sign up to view the full content.

2/1/10 1 Lecture 6 Announcements • Assignment 2 out this afternoon – You will need to sketch out a high level algorithm so that you can see the necessary decision and iteration logic; go see a TA in lab hours or recitation if you need help getting started • Topics for today will address: – Boolean conditions • Relational operators (last time) • Logical operators – Selection statements (if … else, switch) – Algorithm formation example – Repetition / iteration control statements (Ch. 6) Selection Construct condition T F Algorithm level if ( shampoo bottle is empty ) go out and buy some more else continue with washing hair endif Code level int i = 3, j = 4, k = 8, flag; . . . if (i + j < k - 1 ) flag = 1; else flag = 0; Boolean Conditions • boolean values true and false do not exist in Std C. – any numeric expression whose value is !=0 is treated as true – any expression whose value is ==0 is treated as false • An integer variable can be used to store a Boolean value. The variable can be assigned 1 to represent true and 0 to represent false: int flag; /* represents a Boolean condition */ flag = 0; /* condition is false */ • To improve program readability, it is a good idea to define symbolic constants named TRUE and FALSE #define TRUE 1 #define FALSE 0 . . . flag = FALSE; Logical Operators For more complex conditionals we have the logical operators ! logical negation logical and || logical or These operators produce 0 or 1 as their result. Their operands are not limited to 0 and 1, however. The precedence of && and || is lower than that of the relational and equality operators. E.g.: i < j && k == m means (i < j) && (k == m) The logical operators behave as follows: – The value of !expr is 1 if expr has the value 0. – The value of expr1 && expr2 is 1 if expr1 and expr2 are both nonzero. – The value of expr1 || expr2 is 1 if either expr1 or expr2 (or both) is nonzero. – In all other cases, these operators produce the value 0. Both && and || perform “short-circuit” evaluation of their operands. As a result, the following expression is legal even if i has the value 0: (i != 0) && (j / i > 0) If Statements • The if statement has two forms: if ( expression ) statement1 if ( expression ) statement1 else statement2 Semantics - If the value of the expression

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 4

lecture06-feb1 - Lecture 6 Announcements Assignment 2 out...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online