Introduction

Any program that does any real work will have to make decisions. These decisions are based on meeting certain conditions. or rather, running code only some of the time when a particular condition or state is met. The central piece of decision-making is a special C# statement called an if statement. We’ll start by looking at the if statement. along with a few related statements. then we’ll look at a variety of ways to compare two values. we’ll then look at a few other special operators called logical operators (not nearly as scary as it sound).

If Statement: making Decisions

In programming we use conditions to execute code only when certain rules are met.

1. The Basic Syntax Every if statement follows this specific structure:

if (condition) 
{
	// this code runs only if the condition is TRUE
}

2. A Real-World example if a teacher wants to call out a perfect score, the code looks like this:

int score = 100;

if (score== 100) {
	Console.WriteLine("Pefect score! you win!")
}

To understand how the program “thinks”, let’s break down the parts:

  • if The Keyword that tells C# a decision is coming up.
  • (score == 100) : The condition. Note the double equals == in C# one = sets a value, but == asks “is this equal to that?”
  • { }; The code block. Anything inside these “curly braces” is the prize - it only happens if the condition is met.

Complete Program.


int score;
Console.Write("Enter your score: ");
string scoreAsText = console.ReadLine();
score = Conver.ToInt32(scoreAsText);

if (score == 100) {
	Console.WriteLinek("Perfect score! You win!");
}

Console.ReadKey();

else Statement “The Backup Plan”

An else block tells the computer: if the first condition was False. do this instead. It ensures your program always has an answer, no matter what the input is

1. Syntax The else block always follows an if block. It doesn’t need its own condition in parentheses because it catches everything else

if (score == 100) 
{
	Console.WriteLine("Perfect score! You Win!");
}else {
	Console.WriteLine("Not a perfect score, bu keep trying!");
}

Else / if Statements

what if you have more than two options (like grades A, B, and C). You use else if The program checks these in order from top to bottom and stops as soon as it finds a “True” one.

if(score == 100)
{
    Console.WriteLine("Perfect score!  You win!");
}
else if(score == 99)
{
    Console.WriteLine("Missed it by THAT much."); 
}
else if(score == 0)
{
    Console.WriteLine("Seriously, dude, you had to have been TRYING to get that bad of a score.");
}
else
{
    Console.WriteLine("Seriously.  Next time, pick a more interesting number.");
}

Nesting if Statements

int age = 21;
bool hasTicket = true;

if (age >= 18) 
{
    // Layer 1: You are old enough. 
    // Now—and only now—do we check for the ticket.
    
    if (hasTicket == true) 
    {
        // Layer 2: You have the ticket!
        Console.WriteLine("Welcome to the show!");
    }
    else 
    {
        // Layer 2: Failed.
        Console.WriteLine("You're old enough, but you need a ticket.");
    }
}
else 
{
    // Layer 1: Failed. 
    // We don't even care about the ticket because you're too young.
    Console.WriteLine("Sorry, you're too young to enter.");
}

Relational Operator


so that’s the basics of decision-making, let’s take a look now at some better and more powerful ways you can specify conditions (you know, the part that says score == 100).

The == operator that we’ve just been introduced to is called relational operator which is a fancy way of saying “an operator that compares two things”. there are lots of other ones.

The Relational Operator
OperatorMeaningExampleTrue if…
==Equal toscore == 100Score is exactly 100.
!=Not equal toscore != 0Score is anything except 0.
>Greater thanscore > 90Score is 91, 92, etc. (90 is False!)
<Less thanscore < 60Score is 59, 58, etc. (60 is False!)
>=Greater than or equalscore >= 90Score is 90 or any number higher.
<=Less than or equalscore <= 60Score is 60 or any number lower.

A common mistake for new students is using > when they should use >=.

  • Scenario A: if ( score > 90 )
    • If the students get exactly 90, they Do Not get a A the computer say “90 is not bigger than 90”
  • Scenario B: if ( score >= 90 )
    • if the student gets exactly 90, they Do get an A. the computer say “90 is equal to 90 , so this is True”.
Console.Write("Enter your score: ");
int score = Convert.ToInt32(Console.ReadLine());

// 1. Check for a special bonus first
if (score == 100)
{
    Console.WriteLine("Perfect score! You win!");
}

if (score >= 90)
{
    Console.WriteLine("You got an A.");
}
else if (score >= 80)
{
    Console.WriteLine("You got a B.");
}
else if (score >= 70)
{
    Console.WriteLine("You got a C.");
}
else if (score >= 60)
{
    Console.WriteLine("You got a D.");
}
else
{
    // This catches everything below 60
    Console.WriteLine("You got an F.");
}

Using Bool in Decision making


Think of the bool (Boolean) data type as a foundation of every decision a computer makes. While we’ve been using expressions like score >= 90 the computer internally converts those expression into a single bool value: True or False

What is a bool A bool is a data type that can only hold two possible values: true or false

  • true: the light is on, the gate is open, the condition is met.
  • false: the light is off, the gat is closed, the condition failed.
int score = 45;
int pointsNeededToPass = 100;

bool levelComplete;

if (score >= pointsNeededToPass)
{
	levelComplete = true;
}
else 
{
	levelComplete = false;
}

if (levelComplete) 
{
	Console.WriteLine("you've beaten the level!");
}

Note, also, that relational operators return a bool value—meaning you can use a relational operator like == or > to directly assign a value to a bool:

int score = 45; 
int pointsNeededToPass = 100;
 
bool levelComplete = (score >= pointsNeededToPass);
 
if(levelComplete)
{
    Console.WriteLine("You've beaten the level!");
}

The ! Operator


A second ago, we look at the != operator, which sees if two things are not equal, There’s another way that we’ll see the ! sign. and that is the negate condition. This is going to be more powerful in a second when we discuss conditional operators. but let’s take a quick look.

The ! operator just takes the opposite value of whatever it is used on. So, for instance:

imagine you have boolean variable that tracks if a light is on

bool isLightOn = false;

if ( !isLightOn)
{
	Console.WriteLine("it is dark in here!");
}

What happened? The computer saw isLightOn was false. The ! flipped it to true. Because the result became true, the code inside the {} ran.

In C#, the ! symbol is officially called the Logical Negation Operator,

The Value Flip

It works on any expression that results in a bool: !true $\rightarrow$ false !false $\rightarrow$ true

Logical Operators: && and || (And and Or)


There are a lot of ways your conditions could be a lot more complicated. For instance, imagine you have a game where the player controls a spaceship that has both shields and armor, and the player only dies when both shields and armor are gone. You will need to check against both things, rather than just one.

Here’s where conditional operators come into play. C# has an and operator, which looks like this: &&, and an or operator that looks like this: ||. You can use these to check multiple things at once:


int shields = 50;
int armor = 20;

if ( shields <= 0 && armor <=0) 
{
	Console.WriteLine("Yourre dead");
}

This means, “if shields are less than or equal to zero, and armor is less than or equal to zero”. Both parts of the condition have to be true.

The || operator works in a similar way, except that only one of the two sides needs to be true:

int shields = 50;
int armor = 20;

if ( shields > 0 || armor > 0) {
	Console.WriteLine("you're still alive! Keep going!");
}

One thing worth mentioning is that with either of these, the computer will do “lazy evaluation.” Meaning that it won’t check the second part unless it knows it needs to. So, for instance, in the example above, the computer will always check to see if shields is greater than 0, but it only bothers checking if armor is greater than 0 if shields is 0.

Also, you can combine lots of these together and, along with parentheses, make some pretty crazy conditions. Anything you want is possible, though readability may quickly become an issue. This leads us to the next section, which might provide an alternative approach that may be more readable.