Skip to main content
C# for Games – Complete Beginner to Advanced Guide
CHAPTER 03 Beginner

Conditions and Loops

Updated: May 16, 2026
20 min read

# CHAPTER 3

Conditions and Loops

1. Introduction

Games are fundamentally about choices and consequences. *If* the player presses the jump button, *then* the character jumps. *If* the player's health drops to zero, *then* trigger the Game Over screen. Without conditional logic, a game is just a movie playing exactly the same way every time. In this chapter, we will master Control Flow. We will learn how to make decisions using if/else and switch statements, and how to execute repetitive tasks instantly using for and while loops. These are the core building blocks of all game mechanics.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use Comparison Operators (==, >, <) to evaluate data.
  • Write if, else if, and else statements to branch game logic.
  • Use switch statements to cleanly manage player states.
  • Automate repetitive tasks using for and while loops.
  • Understand how loops relate to spawning and inventory systems.

3. Comparison and Logical Operators

To make a decision, the computer must compare two things.
  • == (Is Equal To) *Note: A single = assigns a value; double == compares!*
  • != (Is Not Equal To)
  • >, <, >=, <= (Greater than, Less than, etc.)
  • && (AND): Both conditions must be true.
  • || (OR): Only one condition must be true.

4. If / Else Statements (The Crossroads)

The if statement checks a condition inside parentheses (). If it evaluates to true, the code inside the curly brackets {} executes.
csharp
1234567891011121314
int health = 0;

if (health <= 0)
{
    Console.WriteLine("Player Died!"); // This will run
}
else if (health < 20)
{
    Console.WriteLine("Low Health Warning!");
}
else
{
    Console.WriteLine("Player is healthy.");
}

5. Switch Statements (The State Manager)

If you have 10 different enemy types, writing 10 else if statements becomes messy. A switch statement is a cleaner way to check a single variable against many possible matches (called cases). It is perfect for State Machines.
csharp
1234567891011121314
string enemyState = "Patrol";

switch (enemyState)
{
    case "Patrol":
        Console.WriteLine("Walking back and forth.");
        break; // You MUST include 'break' to exit the switch!
    case "Chase":
        Console.WriteLine("Running at player!");
        break;
    default:
        Console.WriteLine("Standing idle.");
        break;
}

6. Loops (Repetitive Power)

Computers excel at doing repetitive math instantly.
  • The while loop: Runs continuously *as long as* a condition is true. Be careful—if the condition never becomes false, you create an "Infinite Loop" and crash the game!
  • The for loop: The safest and most common loop. You tell it exactly how many times to run. It has three parts: (Start ; Condition ; Increment).
csharp
123456
// Example: Spawning 5 enemies
// i starts at 0. As long as i < 5, run the code, then add 1 to i (i++).
for (int i = 0; i < 5; i++)
{
    Console.WriteLine("Spawned Enemy number: " + i);
}

7. Visual Learning: Logic Flowchart

txt
123456789
                   [ Start Check ]
                          |
             (Is Player Health <= 0?)
              /                      \
         [ YES ]                    [ NO ]
            |                          |
    Play Death Animation        Keep Playing Game
            |
        Show Menu

8. Best Practices

  • Curly Bracket Formatting: In C#, standard convention dictates that the opening curly bracket { goes on a *new line* beneath the if or for statement, unlike Java or JavaScript where it stays on the same line. Following this convention makes your C# code look professional to studio leads.

9. Common Mistakes

  • The Assignment vs. Comparison Typo:
Writing if (health = 0) instead of if (health == 0). The single = tells the computer "Make health zero." The double == asks the computer "Is health currently zero?". This typo will break your game logic completely.

10. Mini Project: The Damage Calculator

Objective: Use logical operators and an if statement to simulate combat.
  1. 1. Open Visual Studio. Create a new Console App.
  1. 2. Write the following combat logic:
csharp
1234567891011121314151617181920212223242526272829
using System;

class Program
{
    static void Main()
    {
        int playerArmor = 10;
        int enemyDamage = 25;
        bool isDefending = true;

        Console.WriteLine("An enemy attacks for 25 damage!");

        // If defending, armor is doubled!
        if (isDefending == true)
        {
            playerArmor *= 2; // playerArmor becomes 20
            Console.WriteLine("Player raises shield! Armor doubled to " + playerArmor);
        }

        // Calculate final damage (ensure it doesn't go below 0)
        int finalDamage = enemyDamage - playerArmor;
        if (finalDamage < 0)
        {
            finalDamage = 0;
        }

        Console.WriteLine("Player takes " + finalDamage + " final damage.");
    }
}
  1. 3. Run the program. Change isDefending to false and run it again to see the branching logic at work!

11. Practice Exercises

  1. 1. Write a for loop that counts down from 10 to 1, printing each number to the console (like a bomb timer).
  1. 2. What is the difference between the && operator and the || operator?

12. MCQs with Answers

Question 1

You want to check if a player has enough gold (50) AND has the VIP pass (true) before letting them enter a shop. Which logical operator should you use?

Question 2

What critical keyword must be placed at the end of every case block inside a switch statement to prevent the code from bleeding into the next case?

13. Interview Questions

  • Q: Explain the syntax structure of a for loop in C#. In what game development scenario would you explicitly choose a for loop over a while loop?
  • Q: A junior programmer creates a while (isAlive) loop to handle the player's breathing animation, but the game immediately freezes and crashes. What is an Infinite Loop, and why did this happen?
  • Q: How do switch statements improve code readability and performance compared to deeply nested if / else if chains when implementing an NPC State Machine?

14. FAQs

Q: Can I put an if statement inside another if statement? A: Yes, this is called "Nesting." For example, if (hasKey) { if (isAtDoor) { open door } }. However, too much nesting creates "Spaghetti Code." It is often cleaner to combine them using && operators.

15. Summary

In Chapter 3, we gave our game the ability to think. We learned how to use Comparison Operators to evaluate data, and utilized if/else and switch statements to branch our code, creating dynamic choices. We also unlocked the incredible processing power of the computer by using for and while loops to execute repetitive tasks instantaneously. Our code is no longer a static script; it is a reactive flowchart.

16. Next Chapter Recommendation

Our Main function is getting very long and messy. To build complex games, we need to organize our code into reusable blocks. Proceed to Chapter 4: Functions and Methods.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·