70 likes | 159 Views
Notes About Boolean Expressions. No boolean type, so boolean expressions evaulate to 0(false) or 1(true). x = (x > y); // is valid. It will set x to 0 or 1. if (x) x++; // is valid. If x isn’t 0, it adds 1 to x. !!5 // is equal to 1
E N D
Notes About Boolean Expressions • No boolean type, so boolean expressions evaulate to 0(false) or 1(true). • x = (x > y); // is valid. It will set x to 0 or 1. • if (x) x++; // is valid. If x isn’t 0, it adds 1 to x. • !!5 // is equal to 1 • For these reasons, try to use boolean expressions ONLY where they are meant to be used.
Short-Circuit Evaluation • AND (&&) • If the first component is false, the second is never evaluated • if (b !=0 && (a/b > 0)) … // If b is zero, we never try to divide by it • OR (||) • If the first component is true, the second is never evaluated • if (age >= 21 || fakeid == 1) … // If you are older than 21, you don’t need to check for the fake!
Block of Statements/ Empty Statement • A block of statements ({}) acts as a single statement for syntactic purposes, which is why we use a block for a part of an if statement • An empty statement is as follows: ; This is important because if you add a semicolon somewhere, it changes the interpretation of the statement • if (b !=0); value = a/b; // Here, the division happens even when b is 0…
#include <stdio.h> int main() { int roomlen, roomwid; int desklen, deskwid; printf("Enter the length and width of the room.\n"); scanf("%d%d",&roomlen, &roomwid); printf("Enter the length and width of the desk.\n"); scanf("%d%d",&desklen, &deskwid); if ((deskwid <= roomwid) && (desklen <= roomlen)) printf(“The desk will fit in the room.\n”); else printf(“The desk will not fit in the room.\n”); return 0; }
Revision #1 • //Adjust lengths and widths, if necessary • if (roomlen < roomwid) { • roomlen = roomwid; • roomwid = roomlen; • } • if (desklen < deskwid) { • desklen = deskwid; • deskwid = desklen; • } • What’s WRONG with this solution?
Corrected Program • Add the following after the scanfs to the original program: • //Adjust lengths and widths, if necessary • if (roomlen < roomwid) { • temp = roomlen; • roomlen = roomwid; • roomwid = temp; • } • if (desklen < deskwid) { • temp = desklen; • desklen = deskwid; • deskwid = temp; • }
Another Solution • if ((deskwid <= roomwid) && (desklen <= roomlen)) • printf(“The desk will fit in the room.\n”); • else if ((deskwid<=roomlen) && (desklen<=roomwid)) • printf(“The desk will fit in the room.\n”); • else • printf(“The desk will not fit in the room.\n”);