Lesson 1
Getting Started with While Loop
Learning About While Loops

Ready to dive into the fascinating world of loops in C#? In this unit, we’ll start with one of the simplest yet most powerful types of loops: the while loop. This loop is essential for handling repetitive tasks efficiently. Whether you're keeping track of mission parameters or just counting stars, the while loop is here to help.

What You'll Learn

In this lesson, you’ll learn how a while loop works and how to use it in C#. You'll see how to set the initial condition, write the loop, and control its behavior. We’ll go over a specific example where you will write a loop that prints star counts from 1 to 5.

Here’s a snippet to give you a preview:

C#
1int starCount = 1; 2 3// Continue while starCount is <= 5 4while (starCount <= 5) 5{ 6 // Print current star count 7 Console.WriteLine(starCount); 8 9 // Increment starCount by 1 10 starCount++; 11}
Curious About ++ and --?

You might be wondering what the ++ notation is in the code snippet above.

In C#, ++ is a shorthand for incrementing a variable by 1. Similarly, -- is used to decrement a variable by 1. These operators are commonly used in loops to simplify increment or decrement operations.

For example:

  • a++ is equivalent to: a = a + 1
  • b-- is equivalent to: b = b - 1

By using ++ and --, you can make your code more concise and easier to read, especially within loops.

Why It Matters

Mastering the while loop allows you to automate repetitive tasks, which saves time and reduces errors. This is especially useful in real-world applications where tasks are repetitive but conditions change. Understanding while loops is a fundamental skill that will enhance your coding efficiency and enable you to handle more complex logic down the road.

Excited to give it a try? Let’s get started with the practice section and take control of your code!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.