3. Introduction to C# Applications

Objectives

In this chapter you’ll learn:

• To write simple C# applications using code rather than visual programming.

• To write input/output statements.

• To declare and use data of various types.

• To store and retrieve data from memory.

• To use arithmetic operators.

• To determine the order in which operators are applied.

• To write decision-making statements.

• To use relational and equality operators.

• To use message dialogs to display messages.

What’s in a name? That which we call a rose by any other name would smell as sweet.

William Shakespeare

When faced with a decision, I always ask, “What would be the most fun?”

Peggy Walker

“Take some more tea,” the March Hare said to Alice, very earnestly. “I’ve had nothing yet,” Alice replied in an offended tone, “so I can’t take more.” “You mean you can’t take less,” said the Hatter: “it’s very easy to take more than nothing.”

Lewis Carroll

Outline

3.1 Introduction

3.2 A Simple C# Application: Displaying a Line of Text

3.3 Creating a Simple Application in Visual C# Express

3.4 Modifying Your Simple C# Application

3.5 Formatting Text with Console.Write and Console.WriteLine

3.6 Another C# Application: Adding Integers

3.7 Arithmetic

3.8 Decision Making: Equality and Relational Operators

3.9 Wrap-Up

3.1 Introduction

In this chapter, we introduce console applications—these input and output text in a console window, which in Windows XP and Windows Vista is known as the Command Prompt. We use live-code examples to demonstrate input/output, text formatting and arithmetic, equality and relational operators. The optional Software Engineering Case Study section examines the requirements document that specifies what our ATM must do.

3.2 A Simple C# Application: Displaying a Line of Text

Let’s consider an application that displays a line of text. (Later in this section we discuss how to compile and run an application.) The application and its output are shown in Fig. 3.1. The application illustrates several important C# language features. For your convenience, each program we present in this book includes line numbers, which are not part of actual C# code. In Section 3.3 we show how to display line numbers for your C# code in the IDE. We’ll soon see that line 10 does the real work of the application—namely, displaying the phrase Welcome to C# Programming! on the screen. We now do a code walkthrough.

Fig. 3.1. Text-displaying application.

image

Line 1 begins with //, indicating that the remainder of the line is a comment. We begin every application with a comment indicating the figure number and the name of the file in which the application is stored.

A comment that begins with // is called a single-line comment, because it terminates at the end of the line on which it appears. A // comment also can begin in the middle of a line and continue until the end of that line (as in lines 7, 11 and 12).

Delimited comments such as

/* This is a delimited comment.
   It can be split over many lines */

can be spread over several lines. This type of comment begins with the delimiter /* and ends with the delimiter */. All text between the delimiters is ignored by the compiler. C# incorporated delimited comments and single-line comments from the C and C++ programming languages, respectively. In this book, we use only single-line comments in our programs.

Common Programming Error 3.1

image

Forgetting one of the delimiters of a delimited comment is a syntax error.

Line 2 is a single-line comment that describes the purpose of the application. Line 3 is a using directive that tells the compiler where to look for a class that is used in this application. A great strength of Visual C# is its rich set of predefined classes that you can reuse rather than “reinventing the wheel.” These classes are organized under namespaces—named collections of related classes. Collectively, .NET’s namespaces are referred to as the .NET Framework Class Library. Each using directive identifies a namespace containing predefined classes that a C# application should be able to use. The using directive in line 3 indicates that this example uses classes from the System namespace, which contains the predefined Console class (discussed shortly) used in line 10, and many other useful classes.

Error-Prevention Tip 3.1

image

Forgetting to include a using directive for a namespace that contains a class used in your application typically results in a compilation error, containing a message such as “The name 'Console' does not exist in the current context.” When this occurs, check that you provided the proper using directives and that the names in the using directives are spelled correctly, including proper use of uppercase and lowercase letters.

For each new .NET class we use, we indicate the namespace in which it’s located. This information is important, because it helps you locate descriptions of each class in the .NET documentation. A web-based version of this documentation can be found at

msdn.microsoft.com/en-us/library/ms229335.aspx

You can also place the cursor on the name of any .NET class or method, then press the F1 key to get more information.

Line 4 is simply a blank line. Blank lines, space characters and tab characters are whitespace. Space characters and tabs are known specifically as whitespace characters. Whitespace is ignored by the compiler. We use whitespace to enhance application readability.

Line 5 begins a class declaration for the class Welcome1. Every application you create consists of at least one class declaration that is defined by you. These are known as user-defined classes. The class keyword introduces a class declaration and is immediately followed by the class name (Welcome1). Keywords (also called reserved words) are reserved for use by C# and are always spelled with all lowercase letters. The complete list of C# keywords is shown in Fig. 3.2.

Fig. 3.2. C# keywords and contextual keywords.

image

By convention, all class names begin with a capital letter and capitalize the first letter of each word they include (e.g., SampleClassName). This is frequently referred to as Pascal casing. A class name is an identifier—a series of characters consisting of letters, digits and underscores ( _ ) that does not begin with a digit and does not contain spaces. Some valid identifiers are Welcome1, identifier, _value and m_inputField1. The name 7button is not a valid identifier because it begins with a digit, and the name input field is not a valid identifier because it contains a space. Normally, an identifier that does not begin with a capital letter is not the name of a class. C# is case sensitive—that is, uppercase and lowercase letters are distinct, so a1 and A1 are different (but both valid) identifiers. Identifiers may also be preceded by the @ character. This indicates that a word should be interpreted as an identifier, even if it’s a keyword (e.g., @int). This allows C# code to use code written in other .NET languages where an identifier might have the same name as a C# keyword.

The contextual keywords in Fig. 3.2 can be used as identifiers outside the contexts in which they’re keywords, but for clarity this is not recommended.

Good Programming Practice 3.1

image

By convention, always begin a class name’s identifier with a capital letter and start each subsequent word in the identifier with a capital letter.

Common Programming Error 3.2

image

C# is case sensitive. Not using the proper uppercase and lowercase letters for an identifier normally causes a compilation error.

In Chapters 39, every class we define begins with the keyword public. For now, we’ll simply require this keyword. You’ll learn more about public and non-public classes in Chapter 10, Classes and Objects: A Deeper Look. When you save your public class declaration in a file, the file name is usually the class name followed by the .cs file-name extension. For our application, the file name is Welcome1.cs.

Good Programming Practice 3.2

image

By convention, a file that contains a single public class should have a name that is identical to the class name (plus the .cs extension) in both spelling and capitalization. Naming your files in this way makes it easier for other programmers (and you) to determine where the classes of an application are located.

A left brace (in line 6 in Fig. 3.1), {, begins the body of every class declaration. A corresponding right brace (in line 12), }, must end each class declaration. Lines 7–11 are indented. This indentation is one of the spacing conventions mentioned earlier. We define each spacing convention as a Good Programming Practice.

Error-Prevention Tip 3.2

image

Whenever you type an opening left brace, {, in your application, immediately type the closing right brace, }, then reposition the cursor between the braces and indent to begin typing the body. This practice helps prevent errors due to missing braces.

Good Programming Practice 3.3

image

Indent the entire body of each class declaration one “level” of indentation between the left and right braces that delimit the body of the class. This format emphasizes the class declaration’s structure and makes it easier to read. You can let the IDE format your code by selecting Edit > Advanced > Format Document

Good Programming Practice 3.4

image

Set a convention for the indent size you prefer, then uniformly apply that convention. The Tab key may be used to create indents, but tab stops vary among text editors. We recommend using three spaces to form each level of indentation. We show how to do this in Section 3.3.

Common Programming Error 3.3

image

It’s a syntax error if braces do not occur in matching pairs.

Line 7 is a comment indicating the purpose of lines 8–11 of the application. Line 8 is the starting point of every application. The parentheses after the identifier Main indicate that it’s an application building block called a method. Class declarations normally contain one or more methods. Method names usually follow the same Pascal casing capitalization conventions used for class names. For each application, one of the methods in a class must be called Main (which is typically defined as shown in line 8); otherwise, the application will not execute. Methods are able to perform tasks and return information when they complete their tasks. Keyword void (line 8) indicates that this method will not return any information after it completes its task. Later, we’ll see that many methods do return information. You’ll learn more about methods in Chapters 4 and 7. We discuss the contents of Main’s parentheses in Chapter 8. For now, simply mimic Main’s first line in your applications.

The left brace in line 9 begins the body of the method declaration. A corresponding right brace must end the method’s body (line 11 of Fig. 3.1). Line 10 in the body of the method is indented between the braces.

Good Programming Practice 3.5

image

As with class declarations, indent the entire body of each method declaration one “level” of indentation between the left and right braces that define the method body. This format makes the structure of the method stand out and makes the method declaration easier to read.

Line 10 displays the string of characters contained between the double quotation marks. Whitespace characters in strings are not ignored by the compiler.

Class Console provides standard input/output capabilities that enable applications to read and display text in the console window from which the application executes. The Console.WriteLine method displays a line of text in the console window. The string in the parentheses in line 10 is the argument to the method. Method Console.WriteLine displays its argument in the console window. When Console.WriteLine completes its task, it positions the screen cursor at the beginning of the next line in the console window.

The entire line 10, including Console.WriteLine, the parentheses, the argument "Welcome to C# Programming!" in the parentheses and the semicolon (;), is called a statement. Most statements end with a semicolon. When the statement in line 10 executes, it displays the string Welcome to C# Programming! in the console window. A method is typically composed of one or more statements that perform the method’s task.

Error-Prevention Tip 3.3

image

When the compiler reports a syntax error, the error may not be in the line indicated by the error message. First, check the line for which the error was reported. If that line does not contain syntax errors, check several preceding lines.

Some programmers find it difficult when reading or writing an application to match the left and right braces ({ and }) that delimit the body of a class declaration or a method declaration. For this reason, we include a comment after each closing right brace (}) that ends a method declaration and after each closing right brace that ends a class declaration. For example, line 11 specifies the closing right brace of method Main, and line 12 specifies the closing right brace of class Welcome1. Each of these comments indicates the method or class that the right brace terminates. Visual Studio can help you locate matching braces in your code. Simply place the cursor immediately in front of the left brace or immediately after the right brace, and Visual Studio will highlight both.

Good Programming Practice 3.6

image

Following the closing right brace of a method body or class declaration with a comment indicating the method or class declaration to which the brace belongs improves application readability.

3.3 Creating a Simple Application in Visual C# Express

Now that we have presented our first console application (Fig. 3.1), we provide a step-by-step explanation of how to compile and execute it using Visual C# Express.

Creating the Console Application

After opening Visual C# 2010Express, select File > New Project... to display the New Project dialog (Fig. 3.3), then select the Console Application template. In the dialog’s Name field, type Welcome1. Click OK to create the project. The IDE now contains the open console application, as shown in Fig. 3.4. The editor window already contains some code provided by the IDE. Some of this code is similar to that of Fig. 3.1. Some is not, and uses features that we have not yet discussed. The IDE inserts this extra code to help organize the application and to provide access to some common classes in the .NET Framework Class Library—at this point in the book, this code is neither required nor relevant to the discussion of this application; delete all of it.

Fig. 3.3. Creating a Console Application with the New Project dialog.

image

Fig. 3.4. IDE with an open console application.

image

The code coloring scheme used by the IDE is called syntax-color highlighting and helps you visually differentiate application elements. For example, keywords appear in blue, and comments appear in green. When present, comments are green. In this black-and-white book, we syntax-shade our code similarly—bold for keywords, gray for comments, bold gray for literals and constants, and black for other text. One example of a literal is the string passed to Console.WriteLine in line 10 of Fig. 3.1. You can customize the colors shown in the code editor by selecting Tools > Options.... This displays the Options dialog. Then expand the Environment node and select Fonts and Colors. Here you can change the colors for various code elements.

Modifying the Editor Settings to Display Line Numbers

Visual C# Express provides many ways to personalize your coding experience. In this step, you’ll change the settings so that your code matches that of this book. To have the IDE display line numbers, select Tools > Options.... In the dialog that appears (Fig. 3.5), click the Show all settings checkbox on the lower left of the dialog, then expand the Text Editor node in the left pane and select All Languages. On the right, check the Line numbers checkbox. Keep the Options dialog open.

Fig. 3.5. Modifying the IDE settings.

image

Setting Code Indentation to Three Spaces per Indent

In the Options dialog that you opened in the previous step (Fig. 3.5), expand the C# node in the left pane and select Tabs. Make sure that the option Insert spaces is selected. Enter 3 for both the Tab size and Indent size fields. Any new code you add will now use three spaces for each level of indentation. Click OK to save your settings, close the dialog and return to the editor window.

Changing the Name of the Application File

For applications we create in this book, we change the default name of the application file (i.e., Program.cs) to a more descriptive name. To rename the file, click Program.cs in the Solution Explorer window. This displays the application file’s properties in the Properties window (Fig. 3.6). Change the File Name property to Welcome1.cs.

Fig. 3.6. Renaming the program file in the Properties window.

image

Writing Code and Using IntelliSense

In the editor window (Fig. 3.4), type the code from Fig. 3.1. As you begin typing (in line 10) the class name class name Console, an IntelliSense window containing a scrollbar is displayed as shown in Fig. 3.7. This IDE feature lists a class’s members, which include method names. As you type characters, Visual C# Express highlights the first member that matches all the characters typed, then displays a tool tip containing a description of that member. You can either type the complete item name (e.g., Console), double click the item name in the member list or press the Tab key to complete the name. Once the complete name is provided, the IntelliSense window closes. While the IntelliSense window is displayed, pressing the Ctrl key makes the window transparent so you can see the code behind the window.

Fig. 3.7. IntelliSense feature of Visual C# Express.

image

When you type the dot (.) after Console, the IntelliSense window reappears and shows only the members of class Console that can be used on the right side of the dot (Fig. 3.7, part 1). When you type the open parenthesis character, (, after Console.WriteLine, the Parameter Info window is displayed (Fig. 3.8). This window contains information about the method’s parameters. As you’ll learn in Chapter 7, there can be several versions of a method.

Fig. 3.8. Parameter Info window.

image

That is, a class can define several methods that have the same name, as long as they have different numbers and/or types of parameters—a concept known as overloaded methods. These methods normally all perform similar tasks. The Parameter Info window indicates how many versions of the selected method are available and provides up and down arrows for scrolling through the different versions. For example, there are 19 versions of the WriteLine method—we use one of these 19 versions in our application. The Parameter Info window is one of many features provided by the IDE to facilitate application development. In the next several chapters, you’ll learn more about the information displayed in these windows. The Parameter Info window is especially helpful when you want to see the different ways in which a method can be used. From the code in Fig. 3.1, we already know that we intend to display one string with WriteLine, so, because you know exactly which version of WriteLine you want to use, you can simply close the Parameter Info window by pressing the Esc key.

Saving the Application

Select File > Save All to display the Save Project dialog (Fig. 3.9). In the Location textbox, specify the directory where you want to save this project. We chose the MyProjects directory on the C: drive. Select the Create directory for solution checkbox and click Save.

Fig. 3.9. Save Project dialog.

image

Compiling and Running the Application

You’re now ready to compile and execute your application. Depending on its type, the compiler may compile the code into files with a .exe (executable) extension, a .dll (dynamically linked library) extension or one of several other extensions. Such files are called assemblies and are the packaging units for compiled C# code. These assemblies contain the Microsoft Intermediate Language (MSIL) code for the application.

To compile the application, select Debug > Build Solution. If the application contains no syntax errors, this will compile your application and build it into an executable file (named Welcome1.exe, in one of the project’s subdirectories). To execute it, type Ctrl + F5, which invokes the Main method (Fig. 3.1). (If you attempt to run the application before building it, the IDE will build the application first, then run it only if there are no compilation errors.) The statement in line 10 of Main displays Welcome to C# Programming!. Figure 3.10 shows the results of executing this application, displayed in a console (Command Prompt) window. Leave the application’s project open in Visual C# Express; we’ll go back to it later in this section. [Note: Many environments show Command Prompt windows with black backgrounds and white text. We adjusted these settings in our environment to make our screen captures more readable.]

Fig. 3.10. Executing the application shown in Fig. 3.1.

image

Error-Prevention Tip 3.4

image

When learning how to program, sometimes it’s helpful to “break” a working application so you can familiarize yourself with the compiler’s syntax-error messages. Try removing a semicolon or brace from the code of Fig. 3.1, then recompiling the application to see the error messages generated by the omission.

Running the Application from the Command Prompt

As we mentioned at the beginning of the chapter, you can execute applications outside the IDE in a Command Prompt. This is useful when you simply want to run an application rather than open it for modification. To open the Command Prompt, select Start > All Programs > Accessories > Command Prompt. The window (Fig. 3.11) displays copyright information, followed by a prompt that indicates the current directory. By default, the prompt specifies the current user’s directory on the local machine (in our case, C:Userspaul). On your machine, the folder name paul will be replaced with your user-name.

Fig. 3.11. Command Prompt window when it’s initially opened.

image

Enter the command cd (which stands for “change directory”), followed by the /d flag (to change drives if necessary), then the directory where the application’s .exe file is located (i.e., your application’s binDebug or binRelease directory). For example, the command

cd /d C:MyProjectsWelcome1Welcome1inRelease

(Fig. 3.12) changes the current directory, to the Welcome1 application’s Release directory on the C: drive. The next prompt displays the new directory. After changing to the proper directory, you can run the application by entering the name of the .exe file—Welcome1. The application will run to completion, then the prompt will display again, awaiting the next command. To close the Command Prompt, type exit (Fig. 3.12) and press Enter.

Fig. 3.12. Executing the application shown in Fig. 3.1 from a Command Prompt window.

image

Visual C# 2010 Express maintains a Debug and a Release directory in each project’s bin directory. The Debug directory contains a version of the application that can be used with the debugger (see Appendix G, Using the Visual C# 2010 Debugger). The Release directory contains an optimized version that you could provide to your clients. In the complete Visual Studio 2008, you can select the specific version you wish to build from the Solution Configurations drop-down list in the toolbars at the top of the IDE. The default is the Release version. The Debug version is created if you run the program with Debug > Start Debugging.

Syntax Errors, Error Messages and the Error List Window

Go back to the application in Visual C# Express. As you type code, the IDE responds either by applying syntax-color highlighting or by generating a syntax error, which indicates a violation of Visual C#’s rules for creating correct applications (i.e., one or more statements are not written correctly). Syntax errors occur for various reasons, such as missing parentheses and misspelled keywords.

When a syntax error occurs, the IDE underlines the error in red and provides a description of it in the Error List window (Fig. 3.13). If the Error List window is not visible in the IDE, select View > Error List to display it. In Figure 3.13, we intentionally omitted the comma between "Welcome to" and "C# Programming!" in line 10. The first error is simply indicating that line 10 is not a valid statement. The second error indicates that a right parenthesis is expected at character position 51 in the statement, because the compiler is confused by the unmatched left parenthesis from earlier in line 10. The third error has the text “Invalid expression term’)’”, because the compiler thinks the closing right parenthesis should have appeared earlier in the line. The fourth error has the text “; expected”, because the prior errors make the compiler think that the statement should have been terminated with a semicolon earlier in the line. Although we deleted only one comma in line 10, this caused the compiler to misinterpret several items in this line and to generate four error messages. You can double click an error message in the Error List to jump to the place in the code that caused the error.

Fig. 3.13. Syntax errors indicated by the IDE.

image

Error-Prevention Tip 3.5

image

One syntax error can lead to multiple entries in the Error List window. Each error that you address could eliminate several subsequent error messages when you recompile your application. So when you see an error you know how to fix, correct it and recompile—this may make several other errors disappear.

3.4 Modifying Your Simple C# Application

This section continues our introduction to C# programming with two examples that modify the example of Fig. 3.1 to display text on one line by using several statements and to display text on several lines by using only one statement.

Displaying a Single Line of Text with Multiple Statements

"Welcome to C# Programming!" can be displayed several ways. Class Welcome2, shown in Fig. 3.14, uses two statements to produce the same output as that shown in Fig. 3.1. From this point forward, we highlight the new and key features in each code listing, as shown in lines 10–11 of Fig. 3.14.

Fig. 3.14. Displaying one line of text with multiple statements.

image

The application is almost identical to Fig. 3.1. We discuss only the changes here. Line 2 is a comment stating the purpose of this application. Line 5 begins the Welcome2 class declaration. Lines 10–11 display one line of text in the console window. The first statement uses Console’s method Write to display a string. Unlike WriteLine, after displaying its argument, Write does not position the screen cursor at the beginning of the next line in the console window—the next character the application displays will appear immediately after the last character that Write displays. Thus, line 11 positions the first character in its argument (the letter “C”) immediately after the last character that line 10 displays (the space character before the string’s closing double-quote character). Each Write statement resumes displaying characters from where the last Write statement displayed its last character.

Displaying Multiple Lines of Text with a Single Statement

A single statement can display multiple lines by using newline characters, which indicate to Console methods Write and WriteLine when they should position the screen cursor to the beginning of the next line in the console window. Like space characters and tab characters, newline characters are whitespace characters. The application of Fig. 3.15 outputs four lines of text, using newline characters to indicate when to begin each new line.

Fig. 3.15. Displaying multiple lines with a single statement.

image

Most of the application is identical to the applications of Fig. 3.1 and Fig. 3.14, so we discuss only the changes here. Line 2 is a comment stating the purpose of this application. Line 5 begins the Welcome3 class declaration.

Line 10 displays four separate lines of text in the console window. Normally, the characters in a string are displayed exactly as they appear in the double quotes. Note, however, that the two characters and n (repeated three times in the statement) do not appear on the screen. The backslash () is called an escape character. It indicates to C# that a “special character” is in the string. When a backslash appears in a string of characters, C# combines the next character with the backslash to form an escape sequence. The escape sequence represents the newline character. When a newline character appears in a string being output with Console methods, the newline character causes the screen cursor to move to the beginning of the next line in the console window. Figure 3.16 lists several common escape sequences and describes how they affect the display of characters in the console window.

Fig. 3.16. Some common escape sequences.

image

3.5 Formatting Text with Console.Write and Console.WriteLine

Console methods Write and WriteLine also have the capability to display formatted data. Figure 3.17 outputs the strings "Welcome to" and "C# Programming!" with WriteLine.

Fig. 3.17. Displaying multiple lines of text with string formatting.

image

Line 10 calls method Console.WriteLine to display the application’s output. The method call specifies three arguments. When a method requires multiple arguments, the arguments appear in a comma-separated list.

Good Programming Practice 3.7

image

Place a space after each comma (,) in an argument list to make applications more readable.

Most statements end with a semicolon (;). Therefore, line 10 represents only one statement. Large statements can be split over many lines, but there are some restrictions.

Common Programming Error 3.4

image

Splitting a statement in the middle of an identifier or a string is a syntax error.

Method WriteLine’s first argument is a format string that may consist of fixed text and format items. Fixed text is output by WriteLine, as in Fig. 3.1. Each format item is a placeholder for a value. Format items also may include optional formatting information.

Format items are enclosed in curly braces and contain a sequence of characters that tell the method which argument to use and how to format it. For example, the format item {0} is a placeholder for the first additional argument (because C# starts counting from 0), {1} is a placeholder for the second, and so on. The format string in line 10 specifies that WriteLine should output two arguments and that the first one should be followed by a newline character. So this example substitutes "Welcome to" for the {0} and "C# Programming!" for the {1}. The output shows that two lines of text are displayed. Because braces in a formatted string normally indicate a placeholder for text substitution, you must type two left braces ({{) or two right braces (}}) to insert a single left or right brace into a formatted string, respectively. We introduce additional formatting features as they’re needed in our examples.

3.6 Another C# Application: Adding Integers

Our next application reads (or inputs) two integers (whole numbers, like –22, 7, 0 and 1024) typed by a user at the keyboard, computes the sum of the values and displays the result. This application keeps track of the numbers supplied by the user in variables. The application of Fig. 3.18 demonstrates these concepts. In the sample output, we highlight data the user enters at the keyboard in bold.

Fig. 3.18. Displaying the sum of two numbers input from the keyboard.

image

Lines 1–2 state the figure number, file name and purpose of the application. Line 5 begins the declaration of class Addition. Remember that the body of each class declaration starts with an opening left brace (line 6) and ends with a closing right brace (line 26).

The application begins execution with Main (lines 8–25). The left brace (line 9) marks the beginning of Main’s body, and the corresponding right brace (line 25) marks the end of Main’s body. Method Main is indented one level within the body of class Addition and the code in the body of Main is indented another level for readability.

Line 10 is a variable declaration statement (also called a declaration) that specifies the name and type of a variable (number1) used in this application. Variables are typically declared with a name and a type before they’re used. The name of a variable can be any valid identifier. (See Section 3.2 for identifier naming requirements.) Declaration statements end with a semicolon (;).

The declaration in line 10 specifies that the variable named number1 is of type int—it will hold integer values. The range of values for an int is –2,147,483,648 (int.Min-Value) to +2,147,483,647 (int.MaxValue). We’ll soon discuss types float, double and decimal, for specifying real numbers, and type char, for specifying characters. Real numbers contain decimal points, as in 3.4, 0.0 and –11.19. Variables of type float and double store approximations of real numbers in memory. Variables of type decimal store real numbers precisely (to 28–29 significant digits), so decimal variables are often used with monetary calculations. Variables of type char represent individual characters, such as an uppercase letter (e.g., A), a digit (e.g., 7), a special character (e.g., * or %) or an escape sequence (e.g., the newline character, ). Types such as int, float, double, decimal and char are called simple types. Simple-type names are keywords and must appear in all lowercase letters. Appendix B summarizes the characteristics of the simple types (bool, byte, sbyte, char, short, ushort, int, uint, long, ulong, float, double and decimal).

The variable declaration statements at lines 11–12 similarly declare variables number2 and sum to be of type int. Variable declaration statements can be split over several lines, with the variable names separated by commas (i.e., a comma-separated list of variable names). Several variables of the same type may be declared in one declaration or in multiple declarations. For example, lines 10–12 can also be written as follows:

int number1, // declare first number to add
    number2, // declare second number to add
    sum; // declare sum of number1 and number2

Good Programming Practice 3.8

image

Declare each variable on a separate line. This format allows a comment to be easily inserted next to each declaration.

Good Programming Practice 3.9

image

Choosing meaningful variable names helps code to be self-documenting (i.e., one can understand the code simply by reading it rather than by reading documentation manuals or viewing an excessive number of comments).

Good Programming Practice 3.10

image

By convention, variable-name identifiers begin with a lowercase letter, and every word in the name after the first word begins with a capital letter. This naming convention is known as camel casing.

Line 14 uses Console.Write to display the message "Enter first integer: ". This message is a prompt—it directs the user to take a specific action. Line 16 first calls the Console’s ReadLine method. This method waits for the user to type a string of characters at the keyboard and press the Enter key. As we mentioned, some methods perform a task, then return the result of that task. In this case, ReadLine returns the text the user entered. Then, the string is used as an argument to class Convert’s ToInt32 method, which converts this sequence of characters into data of type int. In this case, method ToInt32 returns the int representation of the user’s input.

Technically, the user can type anything as the input value. ReadLine will accept it and pass it off to the ToInt32 method. This method assumes that the string contains a valid integer value. In this application, if the user types a noninteger value, a runtime logic error called an exception will occur and the application will terminate. C# offers a technology called exception handling that will help you make your applications more robust by enabling them to handle exceptions and continue executing. This is also known as making your application fault tolerant. Chapter 13, Exception Handling, discusses how to make your applications more robust by enabling them to handle such errors and continue executing.

In line 16, the result of the call to method ToInt32 (an int value) is placed in variable number1 by using the assignment operator, =. The statement is read as “number1 gets the value returned by Convert.ToInt32.” Operator = is a binary operator, because it works on two pieces of information. These are known as its operands—in this case, the operands are number1 and the result of the method call Convert.ToInt32. This statement is called an assignment statement, because it assigns a value to a variable. Everything to the right of the assignment operator, =, is always evaluated before the assignment is performed.

Good Programming Practice 3.11

image

Place spaces on either side of a binary operator to make it stand out and make the code more readable.

Line 18 prompts the user to enter the second integer. Line 20 reads a second integer and assigns it to the variable number2.

Line 22 calculates the sum of number1 and number2 and assigns the result to variable sum. In the preceding statement, the addition operator is a binary operator—its two operands are number1 and number2. Portions of statements that contain calculations are called expressions. In fact, an expression is any portion of a statement that has a value associated with it. For example, the value of the expression number1 + number2 is the sum of the numbers. Similarly, the value of the expression Console.ReadLine() is the string of characters typed by the user. After the calculation has been performed, line 24 uses method Console.WriteLine to display the sum. The format item {0} is a placeholder for the first argument after the format string. Other than the {0} format item, the remaining characters in the format string are all fixed text. So method WriteLine displays "Sum is ", followed by the value of sum (in the position of the {0} format item) and a newline.

Calculations can also be performed inside output statements. We could have combined the statements in lines 22 and 24 into the statement

Console.WriteLine( "Sum is {0}", ( number1 + number2 ) );

3.7 Arithmetic

The arithmetic operators are summarized in Fig. 3.19. Note the various special symbols not used in algebra. The asterisk (*) indicates multiplication, and the percent sign (%) is the remainder operator (called modulus in some languages), which we’ll discuss shortly. The arithmetic operators in Fig. 3.19 are binary operators—for example, the expression f + 7 contains the binary operator + and the two operands f and 7.

Fig. 3.19. Arithmetic operators.

image

Integer division yields an integer quotient—for example, the expression 7 / 4 evaluates to 1, and the expression 17 / 5 evaluates to 3. Any fractional part in integer division is simply discarded (i.e., truncated)—no rounding occurs. C# provides the remainder operator, %, which yields the remainder after division. The expression x % y yields the remainder after x is divided by y. Thus, 7 % 4 yields 3, and 17 % 5 yields 2. This operator is most commonly used with integer operands but can also be used with floats, doubles, and decimals. We will consider several interesting applications of the remainder operator, such as determining whether one number is a multiple of another.

Arithmetic expressions must be written in straight-line form to facilitate entering applications into the computer. Thus, expressions such as “a divided by b” must be written as a / b, so that all constants, variables and operators appear in a straight line. The following algebraic notation is generally not acceptable to compilers:

image

Parentheses are used to group terms in C# expressions in the same manner as in algebraic expressions. For example, to multiply a times the quantity b + c, we write

a * ( b + c )

If an expression contains nested parentheses, such as

( ( a + b ) * c)

the expression in the innermost set of parentheses (a + b in this case) is evaluated first.

C# applies the operators in arithmetic expressions in a precise sequence determined by the following rules of operator precedence, which are generally the same as those followed in algebra (Fig. 3.20).

Fig. 3.20. Precedence of arithmetic operators.

image

When we say that operators are applied from left to right, we’re referring to their associativity. You’ll see that some operators associate from right to left. Figure 3.20 summarizes these rules of operator precedence. We expand this table as additional operators are introduced. Appendix A provides the complete precedence chart.

3.8 Decision Making: Equality and Relational Operators

This section introduces a simple version of C#’s if statement that allows an application to make a decision based on the value of a condition. For example, the condition “grade is greater than or equal to 60” determines whether a student passed a test. If the condition in an if statement is true, the body of the if statement executes. If the condition is false, the body does not execute. We’ll see an example shortly.

Conditions in if statements can be formed by using the equality operators (== and !=) and relational operators (>, <, >= and <=) summarized in Fig. 3.21. The two equality operators (== and !=) each have the same level of precedence, the relational operators (>, <, >= and <=) each have the same level of precedence, and the equality operators have lower precedence than the relational operators. They all associate from left to right.

Fig. 3.21. Equality and relational operators.

image

Common Programming Error 3.5

image

Confusing the equality operator, ==, with the assignment operator, =, can cause a logic error or a syntax error. The equality operator should be read as “is equal to,” and the assignment operator should be read as “gets” or “gets the value of.” To avoid confusion, some people read the equality operator as “double equals” or “equals equals.”

Figure 3.22 uses six if statements to compare two integers entered by the user. If the condition in any of these if statements is true, the assignment statement associated with that if statement executes. The application uses class Console to prompt for and read two lines of text from the user, extracts the integers from that text with the ToInt32 method of class Convert, and stores them in variables number1 and number2. Then the application compares the numbers and displays the results of the comparisons that are true.

Fig. 3.22. Comparing integers using if statements, equality operators and relational operators.

image

image

The declaration of class Comparison begins at line 6. The class’s Main method (lines 9–39) begins the execution of the application.

Lines 11–12 declare the int variables used to store the values entered by the user. Lines 14–16 prompt the user to enter the first integer and input the value. The input value is stored in variable number1. Lines 18-20 perform the same task, except that the input value is stored in variable number2.

Lines 22–23 compare the values of the variables number1 and number2 to determine whether they’re equal. An if statement always begins with keyword if, followed by a condition in parentheses. An if statement expects one statement in its body. The indentation of the body statement shown here is not required, but it improves the code’s readability by emphasizing that the statement in line 23 is part of the if statement that begins in line 22. Line 23 executes only if the numbers stored in variables number1 and number2 are equal (i.e., the condition is true). The if statements in lines 25–26, 28–29, 31–32, 34–35 and 37–38 compare number1 and number2 with the operators !=, <, >, <= and >=, respectively. If the condition in any of the if statements is true, the corresponding body statement executes.

Common Programming Error 3.6

image

Forgetting the left and/or right parentheses for the condition in an if statement is a syntax error—the parentheses are required.

Common Programming Error 3.7

image

Reversing the operators !=, >= and <=, as in =!, => and =<, can result in syntax or logic errors.

Common Programming Error 3.8

image

It’s a syntax error if the operators ==, !=, >= and <= contain spaces between their symbols, as in = =, ! =, > = and < =, respectively.

Good Programming Practice 3.12

image

Indent an if statement’s body to make it stand out and to enhance application readability.

There is no semicolon (;) at the end of the first line of each if statement. Such a semicolon would result in a logic error at execution time. For example,

if ( number1 == number2 ); // logic error
   Console.WriteLine( "{0} == {1}", number1, number2 );

would actually be interpreted by C# as

if ( number1 == number2 )
   ; // empty statement
Console.WriteLine( "{0} == {1}", number1, number2 );

where the semicolon in the line by itself—called the empty statement—is the statement to execute if the condition in the if statement is true. When the empty statement executes, no task is performed in the application. The application then continues with the output statement, which always executes, regardless of whether the condition is true or false, because the output statement is not part of the if statement.

Common Programming Error 3.9

image

Placing a semicolon immediately after the right parenthesis of the condition in an if statement is normally a logic error.

Note the use of whitespace in Fig. 3.22. Recall that whitespace characters, such as tabs, newlines and spaces, are normally ignored by the compiler. So statements may be split over several lines and may be spaced according to your preferences without affecting the meaning of an application. It’s incorrect to split identifiers, strings, and multicharacter operators (like >=). Ideally, statements should be kept small, but this is not always possible.

Good Programming Practice 3.13

image

Place no more than one statement per line in an application. This format enhances readability.

Good Programming Practice 3.14

image

A lengthy statement can be spread over several lines. If a single statement must be split across lines, choose breaking points that make sense, such as after a comma in a comma-separated list, or after an operator in a lengthy expression. If a statement is split across two or more lines, indent all subsequent lines until the end of the statement.

Figure 3.23 shows the precedence of the operators introduced in this chapter. The operators are shown from top to bottom in decreasing order of precedence. All these operators, with the exception of the assignment operator, =, associate from left to right. Addition is left associative, so an expression like x + y + z is evaluated as if it had been written as ( x + y ) + z. The assignment operator, =, associates from right to left, so an expression like x = y = 0 is evaluated as if it had been written as x = ( y = 0 ), which, as you’ll soon see, first assigns the value 0 to variable y then assigns the result of that assignment, 0, to x.

Fig. 3.23. Precedence and associativity of operations discussed so far.

image

Good Programming Practice 3.15

image

Refer to the operator precedence chart (the complete chart is in Appendix A) when writing expressions containing many operators. Confirm that the operations in the expression are performed in the order you expect. If you’re uncertain about the order of evaluation in a complex expression, use parentheses to force the order, as you would do in algebraic expressions. Observe that some operators, such as assignment, =, associate from right to left rather than from left to right.

3.9 Wrap-Up

You learned many important features of C# in this chapter, including displaying data in a Command Prompt, inputting data from the keyboard, performing calculations and making decisions. The applications presented here introduced you to basic programming concepts. As you’ll see in Chapter 4, C# applications typically contain just a few lines of code in method Main—these statements normally create the objects that perform the work of the application. In Chapter 4, you’ll learn how to implement your own classes and use objects of those classes in applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset