Comp 110 Examples

Examples of If-Then Logic

Example #1

let isHappy: boolean = true;
if (isHappy) {
      print(":~)");
}

":~)" is printed, because isHappy evaluates to true!

Example #2

let compareNumbers: boolean = 6 < 15;
if (compareNumbers) {    
      print("That was true!");
} else {    
      print("That wasn't true...");
}

"That was true" was printed, because 6 < 15 evaluates to true!

Example #3

let compareStrings: boolean = "I love Carolina" === "I love Duke";
if (compareStrings) {    
      print("Yay collaboration");
} else {        
      print("GO TAR HEELS!!!");
}

"GO TAR HEELS!!!" was printed, because "I love Carolina" and "I love Duke" are not the same string, and so the else-block was printed instead of the if-block.

Examples of Else-If Logic

Example #1

let hateCookies: boolean = false;
let loveChocolate: boolean = false;
let loveOatmeal: boolean = true;
if (hateCookies) {
      print("You hate cookies!");
} else if (loveChocolate) {
      print("You love chocolate chip cookies!");
} else if (loveOatmeal) {
      print("You love oatmeal raisin cookies!");
} else {
      print("You're no fun!");
}

"You love oatmeal raisin cookies!" is printed, as loveChocolate and hateCookies both evaluate to false. Since loveOatmeal evaluates to true, the program does not enter into the final else block.

Example #2

if (6 < 3) {
      print("Red");
} else if (5 > 2) {
      print("Yellow");
} else {
      print("Purple");
}

"Yellow" is printed because 6 < 3 evaluates to false, and 5 > 2 evaluates to true. "Purple" does not print because 5 > 2 evaluates to true and the program does not enter into the final else block.