Comp 101 Examples

Examples of If-Then Logic

Example #1

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

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

Example #2

let compare = 6;
if (compare/2 === 0) {    
      print("That was even!");
}
if (compare/2 !== 0) {  
      print("That was odd!");
}

"That was even!" was printed and "That was odd" was not because six is divisible by two!

Example #3

let compareStrings = "I love Carolina";
if (compareStrings === "I love Carolina") {    
      print("GO TAR HEELS!!!);
} 
if (compareStrings === "I love Duke") {        
      print("Do you even go here?");
}

"GO TAR HEELS!!!" was printed, because "I love Carolina" makes the first conditional true! The second conditional is false because our string does not say "I love Duke"

Examples of Else-If Logic

Example #1

let hateCookies = false;
let loveChocolate = false;
let loveOatmeal = 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.