Learning C# Part 3: Control Structures

Written By: Kevin Jordan

- 02 Sep 2006 -
















Description: This series aims to take a beginning programmer to an intermediate level in C#. Topics covered in Part 3 include: if/else statements, switch/case, and for, while, and do loops.

  1. If, Else Condition Statements
  2. Switch Statements
  3. for Loops
  4. do and while Loops
  5. Aww Man... Not Homework

Introduction

The goal of these articles is to take a beginning programmer to an intermediate level in C#. By the end of this series you should be able to use object oriented to techniques to create database or xml driven websites and Windows-based applications.

I think practice problems can provide a significant benefit rather than just reading material because that's where you realize if you really understand a concept or not. So, at the end of each section there will be a small practice. If you run into any problems along the way, feel free to , or post it on the forum.

If, Else Condition Statements

A condition statement allows you to control the flow of you program by selecting whether are not a statement is executed based on the value of a Boolean expression. Lets dive right into the code of the if statement and its variants. Be sure the read the comments on the code to understand how everything is working.

// This is performed if the value of x is equal to five
// notice the double = sign for the comparison
if (x == 5)
{
        Console.Write("x is equal to 5");
}
 
// in this example, if x does not equal five the else condition will be
// performed instead
if (x == 5)
{
        Console.Write("x is equal to 5");
}
else
{
        Console.Write("x does not equal 5");
}
 
// This final example checks to see if x is 5 if so then it writes x is 
// equal to 5 and doesn't perform the other checks if it doesn't equal
// 5, it will perform the second check, if x is less than 5, finally if 
// that is not true then it will write the last part: x must be greater
// than 5
if (x == 5)
{
        Console.Write("x is equal to 5");
}
else if (x < 5)
{
        Console.Write("x is less than 5");
}
else
{
        Console.Write("x must be greater than 5");
}

Other than just greater than (>), less than (<), and equal to (==), there is also the greater than or equal to (>=) and the less than or equal to (<=) comparison operators. Sometimes you want to perform more than one check at a time as well.

// In the following statement we use the conditional AND operator
// x must be both less or equal to 100 and greater and or equal 0
if ( (x >= 0) && (x <= 100) )
{
        Console.Write("X is between 0 and 100");
}
 
// The following uses the conditional OR so if it meets either of the 
// following, the statement is considered true
if ( (x < 0 ) || (x > 100) )
{
        Console.Write("X is out of bounds: less than 0 or greater than 100");
}

Next >>