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).

Saturday, October 22, 2011

1.8. User-entered data: ReadLine

If we want the user to enter the data that our program will use, we need to learn a new command, which will allow us to read from the keyboard. We have "System.Console.WriteLine", but also "System.Console.ReadLine", so we would read text by doing:

myText = System.Console.ReadLine();

but that will happen in the next chapter, when we see how to handle text variables. Currently, we only know how to manipulate integer numbers, so we must convert that text to an integer, using "Convert.ToInt32":

firstNumber = System.Convert.ToInt32( System.Console.ReadLine() );

An example program to add two numbers typed by the user would be:


public class Example03
{
public static void Main()
{
int firstNumber;
int secondNumber;
int sum;
 
System.Console.WriteLine("Enter the first number");
firstNumber = System.Convert.ToInt32(
System.Console.ReadLine());
System.Console.WriteLine("Enter the second number");
secondNumber = System.Convert.ToInt32(
System.Console.ReadLine());
sum = firstNumber + secondNumber;
 
System.Console.WriteLine("The sum of {0} and {1} is {2}",
firstNumber, secondNumber, sum);
}
}



Let's make a small improvement: it is not necessary to repeat "System." at the beginning of the commands related with the system (for now, the console and conversion commands), if we use at the beginning of the program "using System":






using System;
 
public class Example04
{
public static void Main()
{
int firstNumber;
int secondNumber;
int sum;
 
Console.WriteLine("Enter the first number");
firstNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number");
secondNumber = Convert.ToInt32(Console.ReadLine());
sum = firstNumber + secondNumber;
 
Console.WriteLine("The sum of {0} and {1} is {2}",
firstNumber, secondNumber, sum);
}
}



Suggested exercises:
  1. Multiply two numbers typed by user.
  2. The user will type two numbers (x and y), and the program will calculate the result of their division and the remainder of that division.
  3. The user will type two numbers (a and b), and the program will display the result of the operation (a + b) * (a-b) and the result of the operation a2-b2.
  4. Sum three numbers typed by user.
  5. Ask the user a number and show its multiplication table. For example, if the number is 3, something like this should be written

3 x 0 = 0
3 x 1 = 3
3 x 2 = 6
3 x 10 = 30

Friday, October 21, 2011

1.7. Comments

We can write comments, which the compiler ignores, but which may serve us to clarify the logic of the program. They are written between "/*" and "*/":

int sum; /* Because we keep it for later use */

It is advisable to write comments which help us clarify the mission of the parts of our programs that may be less obvious at a glance. It is frequently recommended also to start the program with a comment, to remind us what the program does, not needing to read all the source. An almost too commented example:

/* ---- C# example: sum of two preset numbers ---- */
 
public class Example02b {
    public static void Main()
    {
        int firstNumber;
        int secondNumber;
        int sum;  /* Because we keep it for later use */
 
        firstNumber = 234;
        secondNumber = 567;
        /* We calculate the sum first */        
        sum = firstNumber + secondNumber;
          /* And finally we display the result */
        System.Console.WriteLine("The sum of {0} and {1} is {2}", 
          firstNumber, secondNumber, sum);
    }
}
A comment can start on one line and end in a different one:

/* This
is a comment
more than one line long
*/


We can also use other commenting style: comments which begin with "//" and finish at the end of the current line (so they cannot occupy more than one line). They are "C++ style comments":

// This is a "C++ style" comment

Thursday, October 20, 2011

1.6. Identifiers

The acceptable names for variables (which are known as "identifiers") may consist of letters, numbers or the underscore (_) and must start with letter or underscore. They must not have spaces in between, and accented vowels and "ñ" are not "standard" characters accepted in all languages, so in most occasions they should not be used.

Therefore, these are not valid variable names:

1number (starts with number)
a number (contains a space)
Año1 (contains a "ñ")
MásDatos (has a stressed vowel)
Also, we cannot use C# reserved words as identifiers. For example, the word "int" refers to a certain data type that we can use for variables, so the word "int" may not be used as a identifier (we will not include a list of C# reserved words yet)

For now, we will try to use variable names that seem readable to us, and that seem not to be a C# command.

We must remember that in C# upper case and lower case letters are not interchangeable, so if we try to do

FirstNumber = 0;
firstnumber = 0;

or any similar variation, the compiler will complain and tell us that such variables are unkown, because we declared

int firstNumber;

Wednesday, October 19, 2011

1.5. Introduction to variables: int

Variables are a memory space which we assign a name and where we can store data.

Our first example program was able to write "Hello". The second one allowed us to add two preset numbers. But this situation is not "usual" in real world: most times we will manipulate data that the user has typed or which have been obtained in previous calculations.
That's why we need variables, memory areas where the data and temporary results will be saved. As a first example, let's see how we would sum two integer numbers preset in the program.


1.5.1. Definition of variables: integers

To use a variable, we must declare it first: we will assign it a name, and we will indicate the data type if will be, too.

The first data type we will use is an "integer number" (no decimal places), which is declared using the word "int":

int firstNumber;

This command reserves space enough to store an integer number, which may hold different values, and which we refer to with the name "firstNumber."


1.5.2. Assigning values

We can give a value to that variable in our program:

firstNumber = 234;

Or we can give it an starting value ("initialize it") before the program begins, when we declare it:

int firstNumber = 234;

Or we can even declare and initialize more than one variable at a time

int firstNumber = 234, secondNumber = 567;

(This line reserves space for two variables, which we will use to store integer numbers; one of them is called firstNumber and has a starting value of234 and the other variable is called secondNumber and has 567 as starting value).

After that, we can make operations with variables, just as we did with the numbers::

sum = firstNumber + secondNumber;

1.5.3. Showing the value of a variable on screen

We know how to display a number or the result of a simple operation on screen:

System.Console.WriteLine(3+4);

but the syntax is very similar for a variable:

System.Console.WriteLine(sum);

Also, if we want to display text and also the value of the variable, we can indicate it in quotes, specifying {0} where we want the value of the variable to be displayed:

System.Console.WriteLine("The sum is {0}", sum);

If we want to display more than one variable, we will place them after the text and we will specify where each one of them must be shown, using {0}, {1} and so on:

System.Console.WriteLine("The sum of {0} and {1} is {2}",
firstNumber, secondNumber, sum);

We know enough to create a program which can sum two numbers using variables:

public class Example02
{
public static void Main()
{
int firstNumber;
int secondNumber;
int sum;

firstNumber = 234;
secondNumber = 567;
sum = firstNumber + secondNumber;

System.Console.WriteLine("The sum of {0} and {1} is {2}",
primerNumero, segundoNumero, sum);
}
}


Let's review what it does:
  • (We still skip the details of what "public", "class", "static" and "void" mean).
  • Main() indicates where the body of the program begins, and the body of the program is delimited between curly braces ( "{" and "}" )
  • int firstNumber, reserves space for an integer number, which we will refer to as "firstNumber".
  • int secondNumber, prepares space for another integer number, which we will call "secondNumber".
  • int sum; reserves space to store a third integer, called "sum".
  • firstNumber = 234, sets the value for the first number to be added.
  • secondNumber = 567, sets the value for the second number.
  • sum = firstNumber + secondNumber, calculates the sum of those two numbers and stores the result in another variable, instead of displaying it directly on screen.
  • System.Console.WriteLine ("The sum of {0} and {1} is {2}", firstNumber, secondNumber, sum), displays the text and the values of these three variables (the two starting numbers and their sum).
Suggested exercise: Create a program to calculate the product of the numbers 121 and 132, using variables.

Saturday, October 15, 2011

1.4. Basic mathematical operations in C#

The symbol for the sum is +, and - for the subtraction, but other mathematical operations have less intuitive symbols. Let's see the most important ones:

Operator Operation
+ Sum
- Subtraction, negation
* Multiplication
/ Division
% Remainder of the division ("modulus")

Suggested exercises:
  • Create a program to calculate the product of 12 and 13.
  • Write a program that calculates the difference (subtraction) between 321 and 213.
  • Make a program that computes the result of dividing 301 by 3.
  • Create a program that calculates the remainder of the division of 301 by 3.

1.4.1. Precedence of the operators

It's not difficult:
  • First, the operations indicated in parentheses.
  • Then the negation
  • After that, multiplication, division and the remainder of the division.
  • Finally, addition and subtraction.
  • If two operations have the same priority, they are analyzed left to right.

Suggested exercise: Calculate (by hand and then check it using C#) the result of the following operations:
  • -2 + 3 * 5
  • (20+5) % 6
  • 15 + -5*6 / 10
  • 2 + 10 / 5 * 2 - 7 % 1

1.4.2. Introduction to overflow problems

The space available for storing numbers is limited. If the result of an operation is "too big", we will get an error message or a wrong result. Because of this, in out first examples we will use small numbers. Later we will see the reason this problem and how to avoid it. As a example, the following program does not even compile because the compiler knows that the result will be "too big":



public class MultiplyOverflow
{
public static void Main()
{
System.Console.WriteLine(10000000*10000000);
}
}
 

Thursday, October 13, 2011

1.3. Display integer numbers on screen

When we write text "as is", as in the previous example above, we enclose it in quotes. But in most occasions we will not want to write predefined texts, but something which must be calculated.

A very simple example is a mathematical operation. We will not use quotation marks for it, so our C# compiler will try to parse the contents of the expression and guess what we mean. For example, to sum 3 and 4 we would do as follows:

public class Example01sum
{
     public static void Main()
     {
         System.Console.WriteLine(3+4);
     }
}


Suggested exercise: Write a C# program to display the sum of 118 and 56.

Monday, October 10, 2011

1.2. How to test this program using Mono

As mentioned, we will use Mono as a development platform for our first programs. Therefore, we will start downloading this tool, installing it and seeing how to use it.

Mono can be downloaded from its official website:


The download link is the upper right part. We must choose the platform we will use. In this text, we will download the latest version for Windows (2.10.5 at the time of this writing).

This is a file near 90 MB in size. When the download is completed, we have to double click the received file and the installation will start (probably after a Windows security warning). Then we will have to accept the license agreement, and we will be asked which installation folder we prefer. As usual, we are proposed to use "Program Files".

Then we have to choose which components we want to install (Mono, Gtk #, XSP). We can install Mono, along with Gtk# libraries for creating user interfaces and XSP (eXtensible Server Pages, a web server). I prefer not install everything. Mono is a must. The creation of user interfaces with Gtk # is beyond the scope intended by this text, but may still be of interest for someone. XSP web server is unnecessary at this point, and it would install a service which might slow down our computer slightly, so prefer not to install it.

Installation is not difficult alter that: we will choose a folder in our Start Menu, see a summary, and then file copying will start. If everything is correct, after a short while we will see a confirmation message, which informs us that the installation is complete.
Mono is ready to use. In our Start menu we should have a new folder called "Mono x.x.x for Windows", (x.x.x would be our version number, such as 2.10.5). In that folder we should be able to find "Mono-x.x.x Command Prompt":
If we click this option, the operating system black screen (the "console") will be displayed, and the "search path" will prepared for us to access the compiler-

We might be taken to a folder inside "Documents and settings" or maybe even to one where we do not have write permission, such as "Windows\System32". If we want to change Mono start folder, we can do by right clicking on "Mono-xxx Command Prompt" from the Start menu and selecting "Properties".

Now we must type our source file. We can use any plain text editor for this. In this first approach, we will use Windows "Notepad". Let’s type:
notepad example01.cs

Notepad should warn us that there is no such file, and ask us if we want to create it. If we answer yes, and we can start typing the previous example.

Then we’ll save the changes, exit "notepad" and we’ll be at the black command prompt screen. The next step is compiling our source file. Now let’s type

gmcs example01.cs

If we see no answer, it means that there are no errors, so a file called "ejemplo01.exe" should have been created. New we could run the program by typing

mono ejemplo01.exe

and the message "Hello" should be displayed on the screen.

If our computer has "Dot Net Framework" installed (it is usual in the latest Windows versions) of Windows), our program should also run correctly if we just type its name:

ejemplo01



Note: If you want a more powerful editor than Windows Notepad, you can try Notepad++, which is free ("open source" actually) and can be easily found on the Internet. Geany is an interesting option, too. And if you prefer an environment from which you can type, compile and test your programs, even if they are large projects, we will discuss later about SharpDevelop and Visual Studio.

Saturday, October 8, 2011

1.1 Display a text using C#

Let's start with a first example of C# program, probably the simplest one which is capable of "doing something useful." It writes a text on the screen. We saw it in the previous section. Let's look at it now in more detail:

public class Example01 
{
     public static void Main()
     {
         System.Console.WriteLine("Hello");
     }
}

It displays "Hello" on screen. But there are many words around that "Hello", so let's comment a bit about them before going on, even though many details will become clear later. In this first analysis, we will go inside out:

  • WriteLine("Hello"); - "Hello" is the text we want to write, and WriteLine is the command which writes a text on screen (and moves the cursor to the next line).
  • Console.WriteLine("Hello"); - because WriteLine is a command related to “Console” (the black text screen we can use when we use the operating system).
  • System.Console.WriteLine("Hello"); - because the commands related to Console belong to “System” category.
  • The curly braces { and } are used to mark the beginning and the end of a program block (now, the “main” block of the program).
  • public static void Main() - Main is the "body" of our program (a program can be split intro several parts, as we'll see later). Every C# program must have a "Main" block. Why "void"? Why "static"? Why "public"? Why those empty parentheses ? We'll see those details later. For now, we'll just remember that this is the usual way to write "Main".
  • public class Example01 – At this point, we'll just consider that "Example01" is the name for our program, and that a line like that must exist in all of our programs. Again, we'll see later the details on why is it a "class" and why is it "public".

As you can see, much of this program is still almost a "leap of faith" for us. We must believe that "it will work properly." Little by little we will be explaining why "public", "static", "void", "class"... For now we will just "fill in" the body of the program to understand the basic concepts of programming, and skip these advanced details.

Suggested exercise: Write a C# program which greets you using your name (eg: "Hi, Nacho").
Only a few more things before proceeding:

  • Each C# statement must end with a semicolon (;)

  • C# is a free format language, so we can write several commands on one line, and we can split statements into several lines or using spaces. For this reason, the above program could also be written like this (though not advisable, because it can be less readable):

public class Example01 {
public
static
void Main() { System.Console.WriteLine("Hello"); } }

In fact, there are two particularly common places for the starting brace, and I will use both interchangeably. One is as we have done in the first example, placing the opening brace alone in a line alone, exactly over the corresponding closing brace. This is what many authors call the "C Style". The second common way is by placing it after the name of the starting block (the "Java style"), as follows:

public class Ejemplo01 {
    public static void Main(){
        System.Console.WriteLine("Hola");
    }
}

(This is the way I will preferably use in this text when we are working with big source files, so that they take a little less space)

  • The vast majority of orders that we can find in the C# language are English words or abbreviations of them. But keep in mind that C# is case sensitive, so "WriteLine" is a recognized word, but "writeLine", "WriteLine" or "WriteLine" are not.

1. First contact with C#

C# is a computer programming language. It is a modern language, evolved from C and C++, and its syntax is very similar to Java's. The programs created with C# might not run as fast as those created with C, but the programmer's productivity is much higher.

C# is a language created by Microsoft, in order to allow software development for their .NET platform, and was later standardized by ECMA and ISO. Also there is an alternative "open source" implementation of C#, called the "Mono Project" which is available for Windows, Linux, Mac OS X and other operating systems.

We'll start begin by using Mono as a development platform for our first examples. When we know the basics, we will move to Microsoft Visual C#, which requires a more powerful computer but includes a very advanced development environment, and has a free version available (Visual Studio Express Edition).

The steps we will follow to create a program in C# are:

1. Write the C# program (source file), with any text editor.
2. Compile it with our compiler. This will produce an "executable file".
3. Run the executable file.

Most modern compilers allow us take those steps from a single environment in which we write our programs, compile them, and debug them in case they don't work properly.

In the next section we will see an example of one of these environments, where to find it and how to install it.

Friday, October 7, 2011

0. Suggested exercises

  • Find in Internet an emulator for a 80s computer, such as the Amstrad CPC series, the MSX range or the Commodore 64 (Sinclair ZX Spectrum is not recommended for this exercise) and test the first example program in section 0.1 (the BASIC source program).
  • Change the first example, so that it writes you name, instead of "Hello".
  • Find a Pascal compiler named Free Pascal, install it and test the second example program.
  • Change the second example, so that it writes you name.
  • Find a C compiler for the operating system you are using (on Linux it is probably installed; on Windows or Mac OS X, you can try CodeLite) and test the third example program.
  • Change the third example, so that it writes you name.

0.3. Pseudocode

Although high-level languages are close to human language, it is usual to explain the steps required to solve a problem using "pseudocode", a language which is more strict than human language, but does not follow the syntax of any real high-level language.

The sequence of steps required to solve a problem is called an "algorithm" (actually, there are a few conditions more, for example, there must be a finite number of steps). Therefore, a computer program is an algorithm expressed using a programming language.

For example, an algorithm to process payments made in a store using credit card, written in pseudocode, might be:


Read card’s magnetic band
Connect with bank central
If connection_available and correct_card:
Request PIN
If PIN is correct
Check balance
If balance >= shopping_amount
Accept Operation
balance = balance - amount
End If
End If
End If


Wednesday, October 5, 2011

0.2. Assemblers, compilers and interpreters

As we have seen, the commands that we have written (the "source program") must be converted to something that the computer understands (an "executable" program).

If we choose a low-level language such as "assembly", such translation is simple, and is made using tools called assemblers.

If we choose a high level language, the translation is more complex, and it might also involve collecting multiple source programs or including "libraries". The tools for such tasks are called compilers.

The executable program created by the compiler or the assembler can run be run on another computer, even if that computer has no compiler or assembler in it.

For example, the program that greets us using Pascal language, we would type those commands and save them in a source file named SALUDO.PAS. This file would be useless on a computer with no Pascal compiler. But after we compile it, we would get SALUDO.EXE (supposing we are on MsDos or Windows), which can be run on any computer with the same operating system, even if it has no Pascal compiler. This program would not run in other operating systems (such as Linux or Mac OS X, for example).

An interpreter is a similar tool, but it does not create any "executable" file which can be run on its own. This way, if we want to distribute our program to someone else, we must give the program source and also the interpreter which is able to understand it.

When the program is run, the interpreter converts each high-level statement into machine code commands, one at a time. If one statement is run 1000 times, it will be analyzed and translated 1000 times, so interpreted programs use to be slower than compiled programs.

Nowadays there is another alternative, halfway between a compiler and an interpreter. Some languages are not compiled to an executable for a certain computer, but to a "generic" executable, which can be run on different kinds of computers, provided that in such computer there is a "virtual machine" capable of understanding these executable programs. This happens with Java language: Java source programas are text files with ".java" extension, and executable programs are files with ".class" extension. These ".class" files can be run in any computer that has a "Java Virtual Machine" installed in it (and such virtual mahines are available for most operating systems). The same idea applies in C#, based on a virtual machine called "Dot Net Framework".

0.1. High-level and low-level languages.

Let's see some examples of high-level languages first, and then compare them with low-level languages, which are closer to the computer.

BASIC is an old but still used high-level language. In this language, if we want to write Hello on screen, we would use:

PRINT "Hello"

Other languages, such as Pascal, have a more strict syntax which means that we shall have to type more, but that makes it easier for us to find out errors (we'll see later why):

program HelloUsingPascal;

begin
write('Hello');
end.


The equivalent program written in C language is more difficult to read:

#include 

int main()
{
printf("Hola");
}


In more modern languages, such as C#, it takes even more steps to achieve the same result:

public class Example01
{
public static void Main()
{
System.Console.WriteLine("Hello");
}
}


As we have seen, as languages evolve, they are able to help the programmer in more tasks, but on the other side, simple programs tend to be more complex. Luckily, not all the languages follow this rule, and some of them are designed to make simple tasks simple (again). For example, to write something on screen using Python language we would type:

print("Hello")


On the other hand, low-level languages are closer to the computer, less similar to human languages. That makes them more difficult to learn, and errors are more difficult to detect and correct, but in return we can get more execution speed and even reach a higher level of control, that sometimes can not be achieved with other languages.

For example, to write Hello using assembly language of a x86 computer running MsDos we might do as follows:

dosseg
.model small
.stack 100h

.data
hello_message db 'Hola',0dh,0ah,'$'

.code
main proc
mov ax,@data
mov ds,ax

mov ah,9
mov dx,offset hello_message
int 21h

mov ax,4C00h
int 21h
main endp
end main


It is quite difficult to understand. But that is not what the computer understands yet... only an almost direct equivalent. What the computer can really understand is a sequence of zeros and ones. For example, the commands "mov ds, ax" and "mov ah, 9" (whose meaning we shall not care about) would become the following sequence:

1000 0011 1101 1000 1011 0100 0000 1001

(Note: the colors shown in the above examples are used in some programming environments, so that mistakes in our programs can be easier to find).