If/Else

Types we know

// int
var cupsOfWater = 5; 

// double
var tip = 13.45;

// string
var dayOfWeek = "Tuesday";

boolean

var needCoffee = true;

var hungry = false;

Now that we tools to store a yes or no value, we can have our programs make decisions

"if" statements allow our programs to make basic decisions based on a yes or no value 

if statements

var coffeeCupIsEmpty = true 
if (coffeeCupIsEmpty) {
   // re fill coffee
} else {
   // Drink Cofee 
}
// Get work done

Boolean expression

Comparing


var redCrayons  = 10;

var blueCrayons = 7;


var w = redCrayons > blueCrayons; // true

var x = redCrayons >= blueCrayons; // true

var y = redCrayons < blueCrayons; // false

var z = redCrayons <= blueCrayons; // false

Equality



var currentScore = 10

var target = 15


var isEqual = currentScore == target; // false




Simple if

var animal = Console.ReadLine();
var habitat = "the city";

if (animal == "ox"){
   habitat = "the farm";
}

else

var animal = Console.ReadLine();
var habitat = "the city";


if (animal == "ox"){
   habitat = "the farm";
} else {
   habitat = "woods";
}

else if

var animal = Console.ReadLine();
var habitat = "the city";

if (animal == "ox"){
   habitat = "the farm";
} else if (animal == "moose"){
   habitat = "tundra";
} else {
   habitat = "woods";
}

They stack!

var animal = Console.ReadLine();
var habitat = "the city";

if (animal == "ox"){
   habitat = "the farm";
} else if (animal == "moose"){
   habitat = "tundra";
} else if (animal == "otter"){
   habitat = "river";
} else if (animal == "sea tutle"){
   habitat = "sea";
} else {
   habitat = "woods";
}

boolean logic

var niceOutside = sunny && notTooHot;

var shouldIwatchAMovie = GoodMovie || Raining;

var isNight= !isDay;

don't be scared, might get a bit math-y

Truth tables

A B Result
T T T
T F F
F T F
F F F

A && B

Truth tables

A B Result
T T T
T F T
F T T
F F F

A || B

Sample if

const ringsToDestroy = Console.ReadLine();

const ringBearer = Console.ReadLine();

if (ringsToDestroy > 0 && ringBearer == "Frodo"){
   // Keep walking
} else if (ringsToDestroy == 0){
   // relax in the Shire
} else if (ringBearer != "Frodo") {
    // Find the ring! 
}


How are we feeling?

Expand the Tip Calculator!

If/Else C#

By Mark Dewey

If/Else C#

  • 181