developmentor - a developer services company				  
				      C# Tutorial
   Modules

Basics


Goals:

  • Experiment with console input and output.
  • Declare and use variables.
  • Practice with language control constructs.
  • Create and manipulate arrays.
  • Perform environment interaction.

Overview

Write some simple programs to practice with language basics such as variables, control constructs, arrays, input and output facilities, etc.


part 1- Console Input and Output

Here we will practice reading and writing to the console using the Console class in the System namespace. In addition, we will examine how to use the methods in the Convert class to convert from the characters the input methods deliver to numeric types such as int and double. Note that the documentation for Console and Convert can be easily accessed from within Visual Studio 2010 by placing the cursor on the name in the text editor and hitting the F1 key. Feel free to browse the documentation and experiment with any methods you find.

steps:

  1. Basic output.
    The Console class provides two output methods: Write and WriteLine. There are many overloaded versions of each method allowing them to handle all the required types. For example, there are versions of both methods that take an int argument, other versions that take a double, versions that takes a string, etc. The difference between Write and WriteLine is that WriteLine automatically adds a line terminator to the output. Experiment with both Write and WriteLine. Print literal values and variables of several different types. A good set of types might be string, int, double, and char. It might also be interesting to see how a bool value is printed. Note that there is a version of WriteLine that takes no arguments and simply prints a line terminator. This might be useful to visually separate the output of your program.

  2. Formatted output.
    There are versions of Write and WriteLine that take a format string followed by a variable number of other arguments. The format string can contain placeholders which consist of an integer inside curly braces. The integer corresponds to the position of one of the additional parameters, so {0} represents the first parameter after the format string, {1} is the second, {2} the third, and so on. WriteLine replaces the placeholder with the value of the specified parameter and prints the resulting string. For example, the following can be used to embed the value of the variable a in the output string:
    Console.WriteLine("The value of a is {0}", a);
    Experiment with this version of WriteLine. It might be interesting to print several variables at once.

  3. Input.
    The Console class offers two input methods: Read and ReadLine. Read returns a single character and ReadLine an entire line of input. For our purposes the easiest approach is to ask our users to enter one input value per line so we can simply assume each call to ReadLine will get one input value. The ReadLine method returns the next input line as a string. For example:
    string s = Console.ReadLine();
    We can then keep the value as a string or convert it to another type, as in:
    int i = Convert.ToInt32(s);
    double d = Convert.ToDouble(s);
    Experiment with the Convert methods by reading a few strings and converting to appropriate types.

Solutions:


part 2- Loops and conditionals

Here we will practice with loops and conditionals by writing a program to calculate a value for Pi using the following formula:
Pi/4 = 1 – 1/3 + 1/5 – 1/7 + 1/9 ...
In other words, we are summing:
1/(2k+1) for k = 0, 1, 2, ...
The more terms in the sum, the more precise the calculated value.

steps:

  1. Write a loop to calculate the individual terms in the series and sum them. To keep things simple, you can choose to simply sum the first 1000 elements of the series. Print out the resulting sum.
    Note that when calculating terms in the series, you have to be careful to force floating point arithmetic. If you write the following integer expression you will get integer arithmetic in which every term will be zero since integer division truncates the result:
    1 / (2 * k + 1)
    An easy way to force floating point arithmetic is to use 1.0 in the numerator instead of 1, as in:
    1.0 / (2 * k + 1)
    Another consideration is that the sign of the terms in the series alternates: positive, negative, positive, and so on. The kth term is positive if k is even, and negative if k is odd. You can test k using the remainder operator (%) to see if the remainder on division by two is 0 (even) or 1 (odd):
    if (k % 2 == 0) // add term, else subtract

Solutions:


part 3- Switch

Write a program to implement a very simple calculator. The calculator will read the operation (+, -, *, /) and the two operands, perform the operation, and output the result.

steps:

  1. Read the operation from the user using ReadLine. The operation can remain as a string or you can convert it into a single character using Convert.ToChar.

  2. Read the two operands using ReadLine. The user will need to enter each on a separate line. Convert the strings into doubles.

  3. Use a switch statement to determine the operation. Perform the operation and output the result.

  4. Use the default case of the switch to notify the user if they enter an invalid operation.

Solutions:


part 4- Array

Write a program to find the minimum value contained in an array.

steps:

  1. Create an array of 10 integers.

  2. Read in values from the user and load them into the array. Use a for loop to loop through the array and assign the values. Use the Length property of the array in the stop condition of the loop. Note that it is not possible to use a foreach loop here since foreach gives read only access to the array elements.

  3. Search through the array and locate the minimum value. Use a foreach loop to loop through the array.

  4. Output the array contents and the minimum value. Use a foreach loop to loop through the array.

Solutions:


part 5- Multidimensional Array (optional)

Multiple array dimensions are supported. The dimensions are comma separated within the square brackets. For example, the following code creates a 3x4 array of int.

int[,] a = new int[3,4];

Element access is performed using a single set of square brackets with the indices for each dimension comma separated. For example:

a[0,0] = 17;    // write a value into row 0, element 0
a[0,1] = 32;    // write a value into row 0, element 1
int x = a[0,1]; // read row 0, element 1

The GetLength method is used to obtain the number of elements in a particular dimension. Note that Length gives the total number of elements in the array. The following code illustrates.

int[,] a = new int[3,4];

int l1 = a.Length;       // yields 12 the total number of elements in all dimensions
int l2 = a.GetLength(0); // yields 3, the number of rows
int l3 = a.GetLength(1); // yields 4, the number of elements in each row

steps:

  1. Create a 2x5 array of double.

  2. Print out Length (the total number of elements).

  3. Use the GetLength method to determine the number of elements in each dimension. Print out the values.

  4. To practice with the element access syntax, write a value into any element of your choice.

  5. Use a foreach loop to iterate through the array. Does foreach go through a single row or the entire array?

Solutions:


part 6- Environment interaction (optional)

Tools such as compilers, linkers, DOS commands, etc. often use command line interfaces. Arguments are passed on the command line and are processed by the program to control its behavior. A return value is sent back at the end of execution to indicate success or failure. Convention dictates that a return value of zero is used to indicate success and non-zero values to indicate failure. Different non-zero return codes can be used for different error conditions. Batch files often test the return value to determine how to proceed.

The Main method can optionally perform environment interaction: it can receive its command line arguments as an array of string and it can return an int to indicate success or failure. To support the various methods of environment interaction, there are four allowable signatures for Main.

static void Main() { ... }
static int  Main() { ... }
static void Main(string[] args) { ... }
static int  Main(string[] args) { ... }

In this lab we will practice accessing the program's environment from with the Main method.

steps:

  1. Declare a class called EnvironmentInteraction and add a Main method. Declare Main so that it takes an array of string argument and returns an int.

    static int Main(string[] args)
    {
      ...
    }
    

  2. Use a foreach loop to loop through the command line parameters and print out each one.

  3. Use a return statement to return an exit code of 0 from Main. An exit code of 0 indicates successful completion. Non-zero values can be used to indicate error conditions.

  4. From within Visual Studio 2010 you can set the command line parameters by right-clicking the project, selecting Properties, opening the Configuration Properties folder, clicking on Debugging and entering a value in the Command Line Arguments property. Alternatively, you can run the program from a command window and type the parameters on the command line.

  5. Run the program. The exit code should be displayed in the debug window if you are running from within Visual Studio 2010.

  6. The System.Environment class offers a alternative way to access a program's environment. Environment provides the ability to get the command line and to exit the program.

    string[] cmdLine = Environment.GetCommandLineArgs();
    
    Environment.Exit(0);
    

    Experiment with the Environment class. Notice that the command line argument array includes the program name. You may want to explore the documentation to see what else the class offers. For example, one thing that may be of interest is the ability to access environment variables.

Solutions:

This material is excerpted from the Programming C# course offered by DevelopMentor.