100 likes | 320 Views
Introduction to Programming Using C Week 3 – Lesson 1 (Pages ? to ? in IPC144 Textbook). IPC144. Nesting. A statement inside an if or if-else can be another if or if-else statement – called nesting. if ( mark >= 90 ) printf(“excellent”); else if ( mark >= 60 )
E N D
Introduction to Programming Using C Week 3 – Lesson 1 (Pages ? to ? in IPC144 Textbook) IPC144
Nesting • A statement inside an if or if-else can be another if or if-else statement – called nesting if ( mark >= 90 ) printf(“excellent”); else if ( mark >= 60 ) printf(“good”); else printf(“poor”); if ( mark >= 90 ) printf(“excellent”); else if ( mark >= 60 ) printf(“good”); else printf(“poor”); this layout is better
Combining Conditions - and • “if … is true and … is true” • && means “and” Example /* exam and overall average must be >= 55 */ if ( examMark >= 55 && averageMark >= 55 ) printf(“pass”); else printf(“fail”);
Combining Conditions – or • “if … is true or … is true” • || means “or” Example /* cheaper for kids or seniors */ if ( age <= 13 || age >= 65 ) price = 10.00; else price = 15.00;
Negation of a Condition – not • “if … is not true” • ! means “not” Example /* cheaper for kids or seniors */ if ( !(age <= 13 || age >= 65 ) ) price = 15.00; else price = 10.00; if ( !(age <= 13) && !(age >= 65) ) price = 15.00; else price = 10.00; !(X && Y) = !X || !Y !(X || Y) = !X && !Y !!X = X de Morgan’s Law
Short Circuit (“lazy”) Evaluation consider: if ( age <= 13 || age >= 65 ) • when age is 10, age <= 13 is true so it is notnecessary to test age >= 65 because the result will always be true consider: if ( exam >= 55 && average >= 55 ) • when exam is 40, exam >= 55 is false so it is notnecessary to test average >= 55 because the result will always be false • generally, when conditions are connected by || or && • they are evaluated from left to right • evaluation stops as soon as the answer is known
Example - Leap Year • A year is leap if it is divisible by 4 but not by 100, except years divisible by 400 are leap • 2008, 2000, 2400 are leap; 2009, 2100 are not leap • reason: solar year is 365.242374 days if ( (year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0 ) printf(“%d is a leap year\n”, year); else printf(“%d is not a leap year\n”, year); precedence of && is higher than ||, so brackets could be removed
Multiway Selection – switch statement switch ( expression ) { case constant : statements; break; case constant : statements; break; : default : statements; } Notes: • expression must have an integer value • case labels must be constants • break is optional (and common); w/o break continue to next case • default is optional
Example – switch statement /* given month number print month name */ switch ( month ) { case 1: printf(“January”); break; case 2: printf(“February”); break; : : case 12: printf(“December”); break; default: printf(“Unknown month”); }