University of Alaska system



Syntax, Data Types, Arithmetic, Strings, Input

In these notes we’ll look at the basic structure and methods involved in creating C# programs.

General Format of a Simple C# Program

In general, your programs will have the following structure:

using System;

using System.Text;

using...

namespace NameOfProject

{

class NameOfProgram

{

public or private variable declarations

public or private method declarations

static void Main(string[] args)

{

Code here for the starting method...

}

}

}

The “using” statement at the top tells the C# compiler what other namespaces you want to use. Rather than rewrite commonly used code from scratch, you can use pre-built code that is organized in these namespaces. The “using” statement specifies which namespace you wish to use. Next we have class which defines our object. We’ll say a lot more about classes later. For now, all C# programs are organized into classes. When you create a Windows application the IDE adds a class for you called Form1. Inside the class, you will declare variables that belong to that class. We’ll focus on two categories of variables, public and private, where public is information we’ll make available to the rest of the program, and private is only available within the class. Then we’ll define methods that make up the class. Methods perform actions and consists of a group of statements. Each statement corresponds to a single action. The curly braces define blocks of code that make up methods, namespaces, classes, etc.

For example, previously we added the code:

MessageBox.Show("Contact list 1.0. \nWritten by: Kenrick Mock", "About");

This line of code is a single statement. It consists of an invocation to a method called Show that displays information in a window. It sends two arguments to the method, one with the text to display in the window and the other with the text to label the window.

Your program knows where to start

When you created a new Windows application, one of the files added by the IDE is called Program.cs. If you look at it then you will see something like the following:

amespace ContactDatabase

{

static class Program

{

///

/// The main entry point for the application.

///

[STAThread]

static void Main()

{

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new Form1());

}

}

The // are comments and are ignored by the compiler. They are useful for the programmer to add a description of what the program is doing. Three slashes has special meaning to the IDE; normally a programmer would use two slashes.

Every C# program has a special entry point, the method called Main. Even though your program can have a lot of methods, only one can be the first one that gets executed, and that’s your Main method. You can experiment by adding a new Main method to a new Class and rename the old Main method to something else. This will change the entry point to the new Main.

Text Output

To output text, we used “MessageBox.Show” and the message we wanted within quotation marks. The entity in quotation marks is called a literal string because it’s directly embedded in the program. But what if we wanted to print out a double quotation mark? The computer would get confused because it would think the quotation mark you want to print really ends the message to be printed:

static void Main()

{

MessageBox.Show("Jessica Simpson said, "Am I eating chicken or tuna?"");

}

What will happen when this program is compiled? The compiler will complain about missing some expected character. Text enclosed in double quotes is referred to as strings. If we want to print a double quote itself (or some other special characters) then we need to use an escape character. In C#, the escape character is \. The program that works is:

MessageBox.Show("Jessica Simpson said, \"Am I eating chicken or tuna?\"");

Some other escape characters:

\n - newline, Moves the cursor to the next line like endl

\t - horizontal tab

\r - carriage return, but does not advance the line

\\ - print the escape character itself

An alternate technique to output text is to use Console.WriteLine. This will output text to the “Output” window. You might have to make sure it is visible in the IDE. If you run a program from a command prompt then anything output to the console will show up in the command prompt. The following outputs the text to the console:

Console.WriteLine("Jessica Simpson said, \"Am I eating chicken or tuna?\"");

The console can be particularly handy for debugging purposes or writing quick programs to output some data.

Variables and Identifiers

Let’s expand our program a little bit more to include some identifiers. An identifier is made up of letters, numbers, and underscores, but must begin with a letter or an underscore.

BEWARE: C# is case sensitive. This means that Value, VALUE, value, and vaLue are four separate identifiers. In fact, we can construct 32 distinct identifiers from these five letters by varying the capitalization. Which of these identifiers are valid?

_FoosBall F00sBall %FoosBall 9FoosBall% 12391 _*_ _FF99

Note: When picking identifiers try to select meaningful names!

Here is a short program that uses some variables as identifiers:

static void Main()

{

char period = '.'; // Single quotes

string name = "Cotty, Manny"; // Double quotes

string foods = "cheese and pasta";

int someNum = 15;

Console.WriteLine(name + " loves to eat " + foods);

Console.WriteLine(someNum + " times as much as you" + period);

}

Let’s walk through the program:

Lines 3 through 6 instruct the compiler to assign variables of a particular type. The format is to first indicate the data type identifier, in this case char, string, or int.

- char indicates that the value to be stored is to hold a single ASCII character.

- string indicates that the value to be stored can be composed of many characters.

- int indicates that we want to store an integer value

In line 3, a period is stored in the variable named period. In line 4, the string made up of the characters ‘C’, ‘o’, ‘t’, ‘t’, ‘y’, ‘,’ , ‘ ‘, ‘M’, ‘a’, ‘n’, ‘n’, ‘y’ is stored in name. By convention, most C# programmers use all uppercase for identifiers that won’t change, and lowercase mixed with uppercase for ones that may change. Since these strings won’t change, we could have named this identifier NAME instead of name.

In line 6, we defined one numeric value, someNum to 15. This sets someNum to fifteen.

When the compiler processes the variable declarations, it assigns a memory location to each one. It is intended that the data we store in each memory location is of the same type that we defined it in the program. For example, we defined someNum to be of type int. This means we should only store integers into the memory location allocated for someNum. We shouldn’t be storing floating point numbers, strings, or characters.

Finally, we have output statements that print the contents of the variables. Note that when we use WriteLine, we can print out variables of different types and concatenate the output using the + symbol. The + symbol will also serve as addition as we will see later! So be aware that a symbol may do different things in a different context.

The final output when run is:

Cotty, Manny loves to eat cheese and pasta

15 times as much as you.

Words and Symbols with Special Meanings

Certain words have predefined meanings within the C# language; these are called reserved words or keywords. For example, the names of data types are reserved words. In the sample program there are reserved words: char, int, void, main. We aren’t allowed to use reserved words as names for your identifiers. A complete list of reserved words is given in the book.

Data Types

A data type is a set of values and a set of operations on these values. In the preceding program, we used the data type identifiers int, char, and string.

C# distinguishes between a number of fundamental data types. Of these, the ones we will use most commonly are:

int

long

float (also called a single)

double

string

char

byte

bool

The table below summarizes the different types:

[pic]

An int is a positive or negative number with no value past the decimal point. Note the limitation on the range of values it can hold. If we allocate more storage space (e.g., more bytes) then we can represent larger numbers.

The long data type uses 8 bytes of storage instead of 4 like the int, so it can represent much larger values.

Similarly, C# has two commonly used floating point values: float and double. These data types are used to represent real numbers. The float uses 4 bytes and the double uses 8 bytes, so the double can store larger values than the float (also called a single.)

If double has a larger data range than integer, and can store floating point numbers, you might wonder why we don’t just always use a double. We could do this, but it would be wasteful – the double format takes up more space than an integer. Also it is slower to perform arithmetic operations on a number stored as double than it is on a number stored as integer. The integer data type is better to use if that is all your application needs.

bool stands for Boolean and is used to represent True or False. These are the only two values that are allowed. Booleans are useful in programming due to their ability to select a course of action based upon some outcome that is either true or false, so we will use Booleans extensively in decision-making.

Strings consist of textual data and are enclosed in double-quotes. Strings are represented as a sequence of bit patterns that match to alphanumeric values. For example, consider the following mapping for the letters A, B, and C:

A 01000001

B 01000010

C 01000011

To store the string “CAB” we would simply concatenate all of these codes:

01000011 01000001 01000010

Note that there is a difference between a string of numbers, and a number such as an Integer. Consider the string “0” and the number 0. The String “0” is represented by the bit pattern 00110000 while the integer 0 is represented by 00000000. Similarly, the string “10” would be represented as 00110001 00110000 while the integer 10 is represented as 00001010.

Strings are simply a sequence of encoded bit patterns, while integers use the binary number format to represent values. We will often convert back and forth between String and Number data types.

Numbers

We have already seen a little bit of working with numbers – for example, setting the size or position of a window. When we put a numeric value directly into the program, these are called numeric literals.

C# allows us to perform standard arithmetic operations:

Arithmetic Operator C# Symbol

Addition +

Subtraction -

Multiplication *

Division / (truncation if both operands are integers!)

Modulus %

Here are some examples of arithmetic operations and outputting the result to the console:

Console.WriteLine(3 + 2) ;

Console.WriteLine (3 - 2) ;

Console.WriteLine (5 * 2 * 10) ;

Console.WriteLine (14 % 5) ;

Console.WriteLine (9 % 4) ;

Console.WriteLine (10 / 2) ;

Console.WriteLine (11 / 2) ;

Console.WriteLine (1 / 2) ;

Console.WriteLine(1.0 / 2) ;

The results are:

5

1

100

4

1

5

5

0

0.5

Take care when using division! If an intermediate result is less than zero, the whole thing becomes zero, even though mathematically it should not be zero:

Console.WriteLine((1 / 2) * 4);

In addition to the standard arithmetic operators, C# provides an increment operator and a decrement operator. The increment operator ++ adds one to its operand; the decrement operator -- subtracts one from its operand.

To complicate matters a bit more, if ++ and -- are used within an expression, we get different results depending upon its placement. ++x is a pre-increment while x++ is a post-increment operation. In a pre-increment operation, the variable is incremented before evaluated. In a post-increment operation, the variable is not incremented until after evaluation. Consider the following example:

int x=1;

int y=1;

x = (y++)*2;

Console.WriteLine(x + " " + y);

x = 1;

y = 1;

x = (++y)*2;

Console.WriteLine (x + " " + y);

The output from this program is:

2 2

4 2

In the post-increment evaluation of (y++)*2, we assign the current value of y multiplied by 2 into x (which is 1*2 = 2) and then increment y to 2.

In the pre-increment evaluation of (++y)*2, we first increment y to 2, then compute 2*2=4 and assign that into x.

Shorthand Assignment Operators

A useful shorthand in C# for assignment statements is to combine the assignment along with a mathematical operator. In general, we can use a math symbol in combination with an = to apply the operation to the same variable on the left, and store the result back into that variable.

The following are equivalent:

x = x+ y (( x += y

x = x* y (( x *= y

x = x - y (( x -= y

x = x/ y (( x /= y

x = x% y (( x %= y

Generally these are used with constants; e.g.:

x += 5;

Precedence Rules

The precedence rules of arithmetic apply to arithmetic expressions in a program. That is, the order of execution of an expression that contains more than one operation is determined by the precedence rules of arithmetic. These rules state that:

1. parentheses have the highest precedence

2. multiplication, division, and modulus have the next highest precedence

3. addition and subtraction have the lowest precedence.

Because parentheses have the highest precedence, they can be used to change the order in which operations are executed. When operators have the same precedence, order is left to right.

Examples:

int x; Value stored in X

x = 1 + 2 + 6 / 6; 4

x = (1 + 2 + 3) / 6; 1

x = 2 * 3 + 4 * 5; 26

x = 2 / 4 * 4; 2

x = 2 / (4 * 4); 0

x = 10 % 2 + 1; 1

In general it is a good idea to use parenthesis if there is any possibility of confusion.

There are a number of built-in math functions that are useful with numbers. Here are just a few:

Math.Sqrt(number) returns the square root of number

Ex:

Console.WriteLine(Math.Sqrt(9)); // Displays 3

double d;

d = Math.Sqrt(25);

Console.WriteLine(d); // Displays 5

Console.WriteLine(Math.Sqrt(-1)); // Displays NaN

Math.Round(number); returns the number rounded up/down

Ex: Math.Round(2.7); returns 3

Math.Abs(number); returns the absolute value of number

Ex: Math.Abs(-4); returns 4

There are many more, for sin, cos, tan, atan, exp, log, etc.

When we have many variables of the same type it can sometimes be tedious to declare each one individually. C# allows us to declare multiple variables of the same type at once, and assign initial values if we like, for example:

double a, b;

double c = 2, d = 5.5;

int e = 10;

(Break for Who Wants To Be A Millionaire Quiz)

Converting Numeric Types

If an integral and a floating point variable or constant are mixed in an operation, the integral value is changed temporarily to its equivalent floating point representation before the operation is executed. This automatic conversion of an integral value to a floating point value is called type coercion. In C#, if a literal floating point value like 0.5 is represented as a double. For example the expression:

1 / 2.0

The 2.0 is represented as a double, the 1 is converted from an int to a double, and the division is performed on two doubles resulting in 0.5 as a double.

When we perform an assignment the data types must match. A common problem is trying to assign a floating point value into an integer variable:

intVar = floatValue;

The compiler will complain that the types don’t match. One way around this problem is to explicitly cast the type:

intVar = (int) floatValue;

This is done by putting the “target” type in parenthesis; floatValue is turned into an int, then the int is copied into intVar. However, when a floating point value is coerced into an integral value, loss of information occurs unless the floating point value is a whole number. That is, 1.0 can be coerced into 1, but what about 1.5? Is it coerced into 1 or 2? In C# when a floating point value is coerced into an integral value, the floating point value is truncated. Thus, the floating point value 1.5 is coerced into 1:

intVar = (int) 1.5; // 1 is copied into intVar

intVar = (int) 1.2; // 1 is copied into intVar

Type changes can be made explicit using the Convert class:

intValue = Convert.ToInt32(10.66);

this rounds up and produce the value 11 in intValue. I tend to like using the Convert technique because it’s more general and works in more cases, but does take longer to type.

We can convert to Double, Long, String, Single (float) and every other common data type. Later we’ll use this to convert strings to numeric values.

Sometimes the mistake is made that a data type is a floating point type but we end up with an integer value instead. Here is an example with float:

float x=1;

x = 11 / 2;

Console.WriteLine(x);

You might think this would produce 5.5. But instead it produces 5.0. Why? How to fix it?

How about the following:

x = 2 / 4 * 4 / 2;

x = 2 / 4.0 * 4 / 2; // Gives error message about double/float

We get an error message on the last expression because 4.0 is considered a double and this forces the entire right hand side to be computed as a double, but then the double is assigned into a float (x). We can convert it, but at the potential of a loss of precision in the double since it stores more bits than the float:

x = Convert.ToSingle(2 / 4.0 * 4 / 2);

The bottom line here is to be careful if you are mixing integers with floating point values in arithmetic expressions. Especially if performing division, you might end up with zero when you really want a floating point fractional answer. The solution is to coerce one of the integers into a float or double so the entire calculation is made using floating point.

Example

Let’s put together what we know so far with an example program. Here is the problem:

You are running a marathon (26.2 miles) and would like to know what your finishing time will be if you run a particular pace. Most runners calculate pace in terms of minutes per mile. So for example, let’s say you can run at 7 minutes and 30 seconds per mile. Write a program that calculates the finishing time and outputs the answer in hours, minutes, and seconds.

Input:

Distance : 26.2

PaceMinutes: 7

PaceSeconds: 30

Output:

3 hours, 16 minutes, 30 seconds

For now we’ll just hard-code the inputs into the program, but shortly we will allow the user to enter values when running the program.

Here is one algorithm to solve this problem:

1. Express pace in terms of seconds per mile, call this SecsPerMile

2. Multiply SecsPerMile * 26.2 to get the total number of seconds to finish. Call this result TotalSeconds.

3. There are 60 seconds per minute and 60 minutes per hour, for a total of 60*60 = 3600 seconds per hour. If we divide TotalSeconds by 3600 and throw away the remainder, this is how many hours it takes to finish.

4. TotalSeconds mod 3600 gives us the number of seconds leftover after the hours have been accounted for. If we divide this value by 60, it gives us the number of minutes, i.e. (TotalSeconds % 3600) / 60

5. TotalSeconds mod 3600 gives us the number of seconds leftover after the hours have been accounted for. If we mod this value by 60, it gives us the number of seconds leftover. (We could also divide by 60, but that doesn’t change the result), i.e. (TotalSeconds % 3600) mod 60

6. Output the values we calculated!

Code:

static void Main(string[] args)

{

double distance = 26.2;

int paceMinutes = 7;

int paceSeconds = 30;

int secsPerMile, totalSeconds;

secsPerMile = (paceMinutes * 60) + paceSeconds;

totalSeconds = Convert.ToInt32(distance * secsPerMile);

Console.Write("You will finish in: ");

Console.Write(totalSeconds / 3600 + " hours, ");

Console.Write((totalSeconds % 3600) / 60 + " minutes, ");

Console.WriteLine((totalSeconds % 3600) % 60 + " seconds.");

Console.ReadLine();

}

A few things to note about this program:

totalSeconds = Convert.ToInt32(distance * secsPerMile);

Since distance is a double and secsPerMile is an int, the whole thing is converted to an int, which is the type of totalSeconds. We lose fractions of a second in this case.

Console.Write is the same as Console.WriteLine, except Console.Write does not add a newline to the end of the output. This means that everything gets printed onto the same line until the very final statement, which prints a newline with the WriteLine statement.

The output is;

You will finish in: 3 hours, 16 minutes, 30 seconds.

If we wanted to calculate the finish time for different distances and different paces, we’ll need to change the values in the program and recompile it. This can be inconvenient – it would be nice to have the user input any values he or she desires. In the next few lectures we’ll see how to input values from the user.

Named Constants

In the prior example, let’s say that the program is only going to be used for the marathon. In this case, the variable “distance” is always going to be set to 26.2. If a value is never going to change, it is a good programming practice to define the value as a constant rather than as a variable.

As the name implies, something defined as a constant may never be changed. To create a constant, add the word const in front of the variable declaration:

const datatype varname = value;

For example:

static void Main(string[] args)

{

const double DISTANCE = 26.2;

int paceMinutes = 7;

int paceSeconds = 30;

int secsPerMile, totalSeconds;

secsPerMile = (paceMinutes * 60) + paceSeconds;

totalSeconds = Convert.ToInt32(DISTANCE * secsPerMile);

Console.Write("You will finish in: ");

Console.Write(totalSeconds / 3600 + " hours, ");

Console.Write((totalSeconds % 3600) / 60 + " minutes, ");

Console.WriteLine((totalSeconds % 3600) % 60 + " seconds.");

Console.ReadLine();

}

It is not required, but normal practice for programmers to spell named constants using all uppercase letters.

The use of named constants can make your program easier to read and modify than if the actual value were scattered throughout the program. By using the constant, if the distance ever changes, there is only one place that needs to be changed. When applicable, a constant is also a bit more efficient than using a variable in terms of speed of execution.

More on Strings

A string variable is a variable that refers to a sequence of textual characters. A string variable named s is declared by using the data type of string:

string s;

To assign a literal value to a string, the value must be in double quotes. The following shows how to output three strings:

string day1, day2;

day1= "Monday";

day2= "Tuesday";

Console.WriteLine(day1);

Console.WriteLine (day2);

Console.WriteLine ("Wednesday");

This outputs “Monday”, “Tuesday”, and “Wednesday”.

Two strings can be combined to form a new string consisting of the strings joined together. The joining operation is called concatenation and is represented by a +.

For example, the following outputs “hello world”:

string str1 = “hello”;

string str2 = “world”;

Console.WriteLine(str1 + “ “ + str2);

This outputs: hello world

Note that if we output: Console.WriteLine(str1 + str2)

Then we would get: helloworld

Sometimes with strings we can end up with very long lines of code. The line will scroll off toward the right. You can keep on typing to make a long line, but an alternate method is to continue the line on the next line. To do that, just close an strings and add newlines. Remember that the compiler ignores whitespace:

msg = "640K ought to be enough " +

"for anybody. (Bill Gates, 1981)"

is the same as:

msg = “640K ought to be enough “ + “for anybody. (Bill Gates, 1981)”

String Methods and Properties

There are a number of useful string methods and properties. Strings are also objects and thus have their own properties and methods. To access them, give the name of the string followed by a dot:

str.Length() ; returns number of characters in the string

str.ToUpper() ; returns the string with all letters in uppercase

does not change the original string, returns a copy

str.ToLower() ; returns the string with all letters in lowercase

does not change the original string, returns a copy

str.Trim() ; returns the string with leading and trailing whitespace

removed. Whitespace is blanks, tabs, cr’s, etc.

str.Substring(m,n) ; returns the substring of str starting at character m

and fetching the next n characters. M starts at 0

for the first character! If n is left off, then the remainder

of the string is returned starting at position m.

Here are some examples:

string s = "eat big macs ";

Console.WriteLine(s.Length);

Console.WriteLine(s.ToUpper());

Console.WriteLine(s + "!");

s = s.Trim();

Console.WriteLine(s + "!");

Console.WriteLine(s.Substring(0, 3));

Console.WriteLine(s.Substring(4));

Console.WriteLine(s.Substring(20));

Output:

15

EAT BIG MACS

eat big macs !

eat big macs!

eat

big macs

CRASH! Error message (do you know why?)

On occasion you may be interested in generating the empty string, or a string with nothing in it. This is a string of length 0. It is referenced by simply “” or two double quotes with nothing in between.

You may notice that when you type the dot, Visual Studio pops up a list of selectable names. You can hit tab to select the current one. This feature is called intellisense.

Creating Windows Graphical Applications

So far we have focused on console output. For most of this class we’ll instead create Windows GUI (Graphical User Interface) applications. To do this, in Visual Studio choose Windows application instead of Console application when creating a new project.

A default form will be created named Form1. You can now click and drag controls (graphical “widgets”) from the Toolbox on the left onto the Form:

[pic]

If the toolbox isn’t visible, you can view it from the V)iew menu.

In class we’ll demonstrate adding the following controls to the form:

• Text Box

• Button

• Label

• Radio Button

• Checkbox Button

• Picturebox

• Using Help, Fonts / Auto Hide

You should be familiar with all of these because they are common elements of Windows programs (e.g. web browser, application, etc.) Each control:

• All controls have properties

• Each property has a value (or values)

o To do in class: experiment with the properties of the controls (text, color, etc.)

• Not all properties deal with appearance

• The name property establishes a means for the program to refer to that control

• Controls are assigned relatively meaningless names when created

• Programmers usually change these names to something more meaningful

A common naming convention is for the first 3 letters to be lowercase and indicate the type of control. For example

txt… for Text Boxes

lbl… for Labels

btn… for Buttons

After that, capitalize the first letter of each word. For example, a textbox dealing with how many hours someone works might be named txtHoursWorked.

Events

GUI applications are generally event-driven. This means that the application waits until some event occurs, and then executes some code to handle the event. Typical user-initiated events include pressing a key or clicking the mouse. In C# we can handle events by creating a method. Visual Studio will handle most of the details for us. In our case, the events we will start with will be button click events – for example, we want to do something when someone clicks on a button.

There are several ways to create and add code to an event:

• In the Code Window select the control on the left side menu and the event of interest on the right side menu

• Or double-click the control in the design view to bring up the most common event for that control

• Select the control in the design view, then click on the lightning bolt in the properties window to find the event you’re interested in for the selected control

Other methods for opening the Code window:

• If the Code window is visible, click on it

• Double-click anywhere on the Form window

• Select the Code option from the View menu

• Press the F7 method key anywhere on the design form

• Select the View Code icon from the Project Window

For example, creating a button and then double-clicking it results in the following event handler:

private void button1_Click(object sender, EventArgs e)

{

}

For now, don’t worry about the object sender, EventArgs e part. For now all you really need to know is that any code you enter between the curly braces will be executed when the button is clicked.

Try adding some code that changes the colors of other controls along with the text of the form:

this.Text = "Title of the form!";

button1.BackColor = Color.Blue;

txtTest.Text = "You clicked the button!";

In this example, we programmatically changed the values of properties that we can examine through the Visual Studio properties window. Of particular interest is to change the .Text property of labels or textboxes. This provides us a way to output messages on the form back to the user. To clear a textbox we can set the .Text property to "".

Using Text Boxes for Input and Output

It turns out that any text property of a control is also a string, so what we previously learned about strings also applies to the controls! A particularly useful example is to manipulate the content of text boxes.

For example, say that we create a text box control named txtBox. Whatever the user enters into the textbox is accessible as a string via txtBox.Text . For example:

string s;

s = txtBox.Text.ToUpper()

txtBox.Text = s

This changes the txtBox.Text value to be all upper case letters.

Text Boxes provide a nice way to provide textual input and output to your program. However, recall that other items also have a text property, such as Me.Text, which will change the caption on the title bar of your application.

Because the contents of a text box is always a string, sometimes you must convert the input or output if you are working with numeric data. Use the convert function:

Convert.ToDouble(string);

Convert.ToInt32(string);

Convert.ToString(number);

Etc.

For example, the following increments the value in a text box by 1:

private void button1_Click(object sender, EventArgs e)

{

int i;

i = Convert.ToInt32(txtBox.Text);

i = i + 1;

txtBox.Text = Convert.ToString(i);

}

We can also use the Parse() and toString() methods:

int i;

i = int.Parse(txtBox.Text);

i = i + 1;

txtBox.Text = i.ToString();

I will tend to use the Convert methods rather than Parse.

Comments

As your code gets more complex, it is a good idea to add comments. You can add a comment to your code by using the // characters. Anything from the // characters to the end of the line will be ignored. If you neglect to add comments, it is very common to forget how your code works when you go back and look at it later!

Another common use of comments is to “comment out” blocks of code. For example, if you insert code for testing purposes or if code is not working properly, you can comment it out and have the compiler ignore it. However, the code will still be there if you want to use it again later without having to type it in again – just uncomment the code.

Visual Studio has a button to comment and uncomment blocks of code:

[pic]

Highlight the text to comment and click the icon shown above on the left.

Highlight the text to uncomment and click the icon shown above on the right.

You can also comment out code by placing it inside /* and */

In-class Exercise:

It is recommended that you maintain your training heart rate during an aerobic workout. Your training heart rate is computed as:

0.7(220-a)+(0.3*r)

where a is your age in years and r is your resting heart rate. Write a program to compute the training heart rate as shown below:

[pic]

In-Class Exercise: Write a program that takes as input an amount between 1 and 99 which is the number of cents we would like to give change. The program should output the minimum number of quarters, dimes, nickels, and pennies to give as change assuming you have an adequate number of each coin.

For example, for 48 cents the program should output;

1 quarter

2 dimes

0 nickels

3 pennies

First write pseudocode for the algorithm to solve the problem. Here is high-level pseudocode:

• Dispense max number of quarters and re-calculate new amount of change

• Dispense max number of dimes and re-calculate new amount of change

• Dispense max number of nickels and re-calculate new amount of change

• Dispense remaining number of pennies

Exceptions

Consider the following code:

int i = Convert.ToInt32(txtBox.Text);

This looks harmless, but txtBox might contain a non-numerical value, like “abc123” which could cause problems with the logic of the program.

This type of error is called a runtime error and is not caught until the program runs, because the result depends on the data input to the program (as opposed to compiler errors, which are caught when the program is compiled).

In the case of the error above, and others that are similar, C# will throw an exception and crash. An exception is some condition that was not expected and caused an error. If we want the program to fail more gracefully we can use the try/catch block:

try

try-block

catch (exception type)

catch-block

The try-block contains program statements that might throw an exception.

The catch-block contains statements to execute if an exception is thrown.

Here is a short example:

float f;

try

{

f = Convert.ToSingle(txtBox.Text);

MessageBox.Show(f.ToString());

}

catch (Exception ex)

{

Console.WriteLine("There was an error.");

}

If the user enters a value such as “123” then the program will “catch” the error in the conversion and skip directly to the catch block:

There was an error.

There are more detailed ways to handle exceptions and specific types of exceptions. We’ll look at that later when we cover file I/O.

Introduction to Debugging

If a program is not running the way you intend, then you will have to debug the program. Debugging is the process of finding and correcting the errors. There are two general ways to go about debugging:

1. Add Console.WriteLine or MessageBox statements at strategic points in the program to display the values of selected variables or expressions until the error is detected.

2. Use an integrated debugger the lets you pause, view, and alter variables while the program is running. Such a tool is called a debugger.

Debugging with WriteLines

Let’s first examine the WriteLine method. Although somewhat “primitive” it is useful since it works in virtually any programming environment. Consider the following program which converts a temperature from Fahrenheit to Celsius using the formula:

private void btnConvert_Click(object sender, EventArgs e)

{

int celsius;

int fahrenheit;

const int CONVERSIONFACTOR = 5/9;

fahrenheit = Convert.ToInt32(txtTempF.Text);

celsius = CONVERSIONFACTOR * (fahrenheit - 32);

MessageBox.Show("The temp in Celsius is " + celsius.ToString());

}

When run, it compiles and executes but gives incorrect outputs. For example, on an input of 100 F, we get 0 C, which is incorrect. What is wrong?

One technique is to add WriteLine statements to output intermediate values of interest:

private void btnConvert_Click(object sender, EventArgs e)

{

int celsius;

int fahrenheit;

const int CONVERSIONFACTOR = 5/9;

fahrenheit = Convert.ToInt32(txtTempF.Text);

Console.WriteLine("Fahrenheit = " + fahrenheit);

Console.WriteLine("Conversion = " + CONVERSIONFACTOR);

celsius = CONVERSIONFACTOR * (fahrenheit - 32);

MessageBox.Show("The temp in Celsius is " + celsius.ToString());

}

The program outputs to the console:

Fahrenheit = 100

Conversion = 0

The Conversion factor is obviously incorrect! This should give you enough information to see that the variable was defined incorrectly as an int and truncated to 0, since an integer cannot store the number 5 / 9 .

The first correction is to change this to a double. This requires also converting the resulting double to an int when we store into Celsius:

private void btnConvert_Click(object sender, EventArgs e)

{

int celsius;

int fahrenheit;

const double CONVERSIONFACTOR = 5/9;

fahrenheit = Convert.ToInt32(txtTempF.Text);

Console.WriteLine("Fahrenheit = " + fahrenheit);

Console.WriteLine("Conversion = " + CONVERSIONFACTOR);

celsius = Convert.ToInt32(CONVERSIONFACTOR * (fahrenheit - 32));

MessageBox.Show("The temp in Celsius is " + celsius.ToString());

}

If we run this new version we still get zero! That is because 5/9 is computed with integer division, giving us zero, and then the zero is converted to a double. The fixed version performs floating point division by making one of the operands a floating point number:

const double CONVERSIONFACTOR = 5.0/9;

Once the error is found and detected, then using the WriteLine method we would then remove or comment out the WriteLine statements that helped us track down the source of the error.

Using the Integrated Debugger

While the process described above works, it is somewhat tedious to all of the WriteLine statements and them remove them. A much nicer technique is to use the built-in debugger.

Visual Studio .NET programs run in one of three modes – design mode, run mode, or break mode. The current mode is displayed in parentheses in the Visual Studio title bar. Design mode is where you design the program. Run mode is when you run the program. Break mode is when you pause the program to debug it.

If we return to the original program with the bugs, one way to enter break mode is to add a breakpoint. A breakpoint stops execution at a particular line of code and enters Break mode. This is useful when you know that a particular routine is faulty and want to inspect the code more closely when execution reaches that point.

To set a breakpoint, click in the border to the left of the code. A red dot will appear. Click the same dot to turn the breakpoint off.

[pic]

When we run the program and reach this code, the program automatically enters Break mode and stops. Execution stops before the line with the breakpoint is executed. The current line is indicated in yellow:

[pic]

The first thing we can do is inspect the value of variables. One way to do this is to hover the mouse over the variable or constant, and a popup window will display its contents:

[pic]

In this case, I have hovered over “ConversionFactor” and its value is displayed as 1. This by itself would give us enough information to debug the program. Note that we did not have to add any WriteLine statements!

We can also immediately see the contents of all the active variables by looking in the “Autos” window:

[pic]

We can also click on the “Locals” tab to see all local variables in the current procedure:

[pic]

If a value is displayed in red this indicates that the variables has just been changed.

To illustrate this, we can now step through the program one line at a time using the buttons:

[pic]

These buttons are used respectively to step into a method, step over a method, or step out of a method. We can use these buttons and view our variables change as we run the program. When we define our own methods this will make more sense, but for now the first two buttons do the same thing when we’re executing code within a subroutine.

Click on the “Step Into” or “Step over” buttons to execute the current line of code and move on to the next line:

[pic]

As a shortcut, F11 steps into a method, and F10 steps over a method. These commands are the same for non- method (i.e. the move to the next statement).

Whenever you are done debugging your program, you must make sure that the debugging session is ended before you go back to edit your code. Click the “Stop Debugging” button to exit the debugger.

[pic]

To remove a breakpoint, click again on the red dot. It can take some time to get used to using the debugger, but it will be time well-spent, as it can usually save you a lot of time down the road when your program doesn’t work correctly.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download