Monday, October 24, 2011

2.1. Conditional statements

2.1.1. if

Let's see the way to check if conditions are met. The first statement we will use is "if". Its format is

if (condition) statement;

Let's see an example:

/*---------------------------*/
/*  C# Example #5            */
/*  example05.cs             */
/*                           */
/*  Conditions with if       */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/
  using System;   public class Example05
{
    public static void Main()
    {
        int number;

number = Convert.ToInt32(Console.ReadLine());
          Console.WriteLine("Enter a number");
        if (number>0) Console.WriteLine("The number is positive.");
    }
}
This program asks the user a number. If it is positive (greater than 0), the program writes "The number is positive" on screen. If it is negative or zero, it does nothing.


This program begins with a comment to remind us of what it is. As our sources will become increasingly more complex and now include comments that will enable us to remember at a glance what we wanted to do.

If the statement is long, we can split it into two lines, to make it more readable:

if (number>0)
Console.WriteLine("The number is positive.");

As shown in the example, to check whether a numeric value is greater than another, we use the symbol ">". To see if two values are equal, we use two "equal" symbols: "if (number == 0)". We will see later other possibilities. In all cases, the condition we check should be indicated in parentheses.

This program begins with a comment that reminds us of what it is about. As our sources will become increasingly more complex, from now on we will include comments that will help us to remember at a glance what we wanted to do.

Suggested exercises:
  • Create a program that asks the user an integer number and answers if it is even (hint: you must check if the remainder obtained by dividing by two equals zero: if (x% 2 == 0) ...).
  • Create a program that asks the user two integer numbers and answers which one is the greatest.
  • Create a program that asks the user two integers and answers if the first one is a multiple of the second (hint: as before, you should check if the remainder of the division is zero: a% b == 0).

No comments:

Post a Comment