Chapter 3. Introduction to C# Applications

 

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
<feature> <supertitle>Objectives</supertitle>

In this chapter you’ll learn:

<objective>

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

</objective>
<objective>

To input data from the keyboard and output data to the screen.

</objective>
<objective>

To declare and use data of various types.

</objective>
<objective>

To store and retrieve data from memory.

</objective>
<objective>

To use arithmetic operators.

</objective>
<objective>

To determine the order in which operators are applied.

</objective>
<objective>

To write decision-making statements.

</objective>
<objective>

To use relational and equality operators.

</objective>
</feature>
<feature> <supertitle>Outline</supertitle> </feature>

Introduction

We now introduce C# application programming. Most of the C# applications you’ll study in this book process information and display results. In this chapter, we introduce console applications—these input and output text in a console window, which in Windows is known as the Command Prompt.

We begin with several examples that simply display messages on the screen. We then demonstrate an application that obtains two numbers from a user, calculates their sum and displays the result. You’ll perform various arithmetic calculations and save the results for later use. Many applications contain logic that makes decisions—the last example in this chapter demonstrates decision-making fundamentals by showing you how to compare numbers and display messages based on the comparison results. For example, the application displays a message indicating that two numbers are equal only if they have the same value. We analyze each example one line at a time.

A Simple C# Application: Displaying a Line of Text

Let’s consider a simple application that displays a line of text. The application and its output are shown in Fig. 3.1, which illustrates several important C# language features. 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 consider each line of the application—this is called a code walkthrough.

Example 3.1. Text-displaying application.

 1   // Fig. 3.1: Welcome1.cs
 2   // Text-displaying application.
 3   using System;
 4
 5   public class Welcome1
 6   {
 7      // Main method begins execution of C# application
 8      public static void Main( string[] args )
 9      {
10         Console.WriteLine( "Welcome to C# Programming!" );
11      } // end Main
12   } // end class Welcome1

Welcome to C# Programming!

Line 1

// Fig. 3.1: Welcome1.cs

begins with //, indicating that the remainder of the line is a comment. Programmers insert comments to document applications and improve their readability. The C# compiler ignores comments, so they do not cause the computer to perform any action when the application is run. 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.

Common Programming Error 3.1

Common Programming Error 3.1

Forgetting one of the delimiters of a delimited comment is a syntax error. The syntax of a programming language specifies the rules for creating a proper application in that language. A syntax error occurs when the compiler encounters code that violates C#’s language rules. In this case, the compiler does not produce an executable file. Instead, it issues one or more error messages to help you identify and fix the incorrect code. Syntax errors are also called compiler errors, compile-time errors or compilation errors, because the compiler detects them during the compilation phase. You’ll be unable to execute your application until you correct all the syntax errors in it.

Line 2

// Text-displaying application.

is a single-line comment that describes the purpose of the application.

Line 3

using System;

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

Error-Prevention Tip 3.1

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

This can also be accessed via the Help menu. 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 and space characters make code easier to read. Together, blank lines, space characters and tab characters are known as whitespace. Space characters and tabs are known specifically as whitespace characters. Whitespace is ignored by the compiler.

Line 5

public class Welcome1

begins a class declaration for the class Welcome1. Every application consists of at least one class declaration that is defined by you—the programmer. These are known as user-defined classes. The class keyword introduces a class declaration and is immediately followed by the class name (Welcome1). Keywords (sometimes 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.

Table 3.2. C# keywords and contextual keywords.

C# Keywords and contextual keywords

abstract

as

base

bool

break

byte

case

catch

char

checked

class

const

continue

decimal

default

delegate

do

double

dynamic

else

enum

event

explicit

extern

false

finally

fixed

float

for

foreach

goto

if

implicit

in

int

interface

internal

is

lock

long

namespace

new

null

object

operator

out

override

params

private

protected

public

readonly

ref

return

sbyte

sealed

short

sizeof

stackalloc

static

string

struct

switch

this

throw

true

try

typeof

uint

ulong

unchecked

unsafe

ushort

using

virtual

void

volatile

while

  

Contextual Keywords

add

alias

ascending

by

descending

equals

from

get

global

group

into

join

let

on

orderby

partial

remove

select

set

value

var

where

yield

  

By convention, all class names begin with a capital letter and capitalize the first letter of each word they include (e.g., SampleClassName). This convention is known as upper camel 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

Good Programming Practice 3.1

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

Common Programming Error 3.2

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

Good Programming Practice 3.2

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 you and other programmers 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

Error-Prevention Tip 3.2

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

Good Programming Practice 3.3

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

Good Programming Practice 3.4

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

Common Programming Error 3.3

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

Line 7

// Main method begins execution of C# application

is a comment indicating the purpose of lines 8–11 of the application. Line 8

public static void Main( string[] args )

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

Good Programming Practice 3.5

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.

Line 10

Console.WriteLine( "Welcome to C# Programming!" );

instructs the computer to perform an action—namely, to display the string of characters between the double quotation marks. A string is sometimes called a character string, a message or a string literal. We refer to characters between double quotation marks simply as strings. 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 performs its task by displaying (also called outputting) its argument in the console window. When Console.WriteLine completes its task, it positions the screen cursor (the blinking symbol indicating where the next character will be displayed) at the beginning of the next line in the console window. (This movement of the cursor is similar to what happens when a user presses the Enter key while typing in a text editor—the cursor moves to the beginning of the next line in the file.)

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 message 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

Error-Prevention Tip 3.3

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. To help, you can 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

  } // end Main

specifies the closing right brace of method Main, and line 12

} // end class Welcome1

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.

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 create, compile and execute it using Visual C# Express.

Creating the Console Application

After opening Visual C# 2010 Express, 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.

Creating a Console Application with the New Project dialog.

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

IDE with an open console application.

Figure 3.4. IDE with an open console application.

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

Modifying the IDE settings.

Figure 3.5. Modifying the IDE settings.

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. This will display a dialog asking whether you’d like to rename all of the references in the project to the code element Program. Clicking Yes renames the class from Program to Welcome1 and ensures that the project is configured properly to execute the program.

Renaming the program file in the Properties window.

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

Writing Code and Using IntelliSense

In the editor window (Fig. 3.4), replace the code generated by the IDE with the code from Fig. 3.1. As you begin typing the class name Console (line 10), an IntelliSense window is displayed (Fig. 3.7, part 1). As you type, IntelliSense lists various items that start with or contain the letters you’ve typed so far. IntelliSense also filters the list to show only the members that match what you’ve typed, then displays a tool tip containing a description of the first matching item. 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.

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

Figure 3.7. IntelliSense feature of Visual C# Express.

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

Parameter Info window.

Figure 3.8. Parameter Info window.

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 created and chose the directory MyProjects on the C: drive. Ensure that the Create directory for solution checkbox is checked to create a subdirectory containing all of the files for your program and click Save.

Save Project dialog.

Figure 3.9. Save Project dialog.

Compiling and Running the Application

You’re now ready to compile and execute your application. Depending on the project’s type, the compiler may compile the code into files with the .exe (executable) extension, the .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: The console window normally has a black background and white text. We reconfigured it to have a white background and black text for readability. To do this, click the Compiling and Running the Application icon in the upper-left corner of the console window, then select Properties. You can change the colors in the Colors tab of the dialog that appears.]

Executing the application shown in Fig. .

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

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. On your machine, the folder name Paul Deitel will be replaced with your username.

Command Prompt window when it’s initially opened.

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

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.

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

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

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 customers. In the complete Visual Studio 2010, 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 (or by pressing F5 or the Executing the application shown in Fig. from a Command Prompt window. button on the IDE’s toolbar).

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.

Syntax errors indicated by the IDE.

Figure 3.13. Syntax errors indicated by the IDE.

Error-Prevention Tip 3.4

Error-Prevention Tip 3.4

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.

Modifying Your Simple C# Application

This section continues our introduction to C# programming with two examples that modify the example of Fig. 3.1.

Displaying a Single Line of Text with Multiple Statements

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.

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

 1   // Fig. 3.14: Welcome2.cs
 2   // Displaying one line of text with multiple statements.
 3   using System;
 4
 5   public class Welcome2
 6   {
 7      // Main method begins execution of C# application
 8      public static void Main( string[] args )
 9      {
10         Console.Write( "Welcome to " );        
11         Console.WriteLine( "C# Programming!" );
12      } // end Main
13   } // end class Welcome2

Welcome to C# Programming!

The application is almost identical to Fig. 3.1. We discuss the changes here. Line 2

// Displaying one line of text with multiple statements.

states the purpose of this application. Line 5 begins the Welcome2 class declaration.

Lines 10–11 of method Main

Console.Write( "Welcome to " );
Console.WriteLine( "C# Programming!" );

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.

Example 3.15. Displaying multiple lines with a single statement.

 1   // Fig. 3.15: Welcome3.cs
 2   // Displaying multiple lines with a single statement.
 3   using System;
 4
 5   public class Welcome3
 6   {
 7      // Main method begins execution of C# application
 8      public static void Main( string[] args )
 9      {
10         Console.WriteLine( "Welcome
to
C#
Programming!" );
11      } // end Main
12   } // end class Welcome3
Welcome
to
C#
Programming!

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

// Displaying multiple lines with a single statement.

states the purpose of this application. Line 5 begins the Welcome3 class declaration.

Line 10

Console.WriteLine( "Welcome
to
C#
Programming!" );

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.

Table 3.16. Some common escape sequences.

Escape sequence

Description

Newline. Positions the screen cursor at the beginning of the next line.

Horizontal tab. Moves the screen cursor to the next tab stop.

Carriage return. Positions the screen cursor at the beginning of the current line—does not advance the cursor to the next line. Any characters output after the carriage return overwrite the characters previously output on that line.

\

Backslash. Used to place a backslash character in a string.

"

Double quote. Used to place a double-quote character (") in a string—e,g., Console.Write( ""in quotes"" ); displays "in quotes".

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.

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

 1   // Fig. 3.17: Welcome4.cs
 2   // Displaying multiple lines of text with string formatting.
 3   using System;
 4
 5   public class Welcome4
 6   {
 7      // Main method begins execution of C# application
 8      public static void Main( string[] args )
 9      {
10         Console.WriteLine( "{0}
{1}", "Welcome to", "C# Programming!" );
11      } // end Main
12   } // end class Welcome4

Welcome to
C# Programming!

Line 10

Console.WriteLine( "{0}
{1}", "Welcome to", "C# Programming!" );

calls method Console.WriteLine to display the application’s output. The method call specifies three arguments. When a method requires multiple arguments, the arguments are separated with commas (,)—this is known as a comma-separated list.

Good Programming Practice 3.6

Good Programming Practice 3.6

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

Common Programming Error 3.4

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

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 must keep track of the numbers supplied by the user for the calculation later in the application. Applications remember numbers and other data in the computer’s memory and access that data through application elements called 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.

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

 1   // Fig. 3.18: Addition.cs
 2   // Displaying the sum of two numbers input from the keyboard.
 3   using System;
 4
 5   public class Addition
 6   {
 7      // Main method begins execution of C# application
 8      public static void Main( string[] args )
 9      {
10         int number1; // declare first number to add   
11         int number2; // declare second number to add  
12         int sum; // declare sum of number1 and number2
13
14         Console.Write( "Enter first integer: " ); // prompt user
15         // read first number from user
16         number1 = Convert.ToInt32( Console.ReadLine() );
17
18         Console.Write( "Enter second integer: " ); // prompt user
19         // read second number from user
20         number2 = Convert.ToInt32( Console.ReadLine() );
21
22         sum = number1 + number2; // add numbers
23
24         Console.WriteLine( "Sum is {0}", sum ); // display sum
25      } // end Main
26   } // end class Addition
Enter first integer: 45
Enter second integer: 72
Sum is 117

Lines 1–2

// Fig. 3.18: Addition.cs
// Displaying the sum of two numbers input from the keyboard.

state the figure number, file name and purpose of the application.

Line 5

public class Addition

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

int number1; // declare first number to add

is a variable declaration statement (also called a declaration) that specifies the name (number1) and type of a variable (int) used in this application. A variable is a location in the computer’s memory where a value can be stored for use later in an application. Variables are typically declared with a name and a type before they’re used. A variable’s name enables the application to access the value of the variable in memory—the name can be any valid identifier. (See Section 3.2 for identifier naming requirements.) A variable’s type specifies what kind of information is stored at that location in memory. Like other statements, 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 (whole numbers such as 7, –11, 0 and 31914). The range of values for an int is −2,147,483,648 (int.MinValue) 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 often 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

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

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

Good Programming Practice 3.7

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

Good Programming Practice 3.8

Good Programming Practice 3.8

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

Good Programming Practice 3.9

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 lower camel casing.

Line 14

Console.Write( "Enter first integer: " ); // prompt user

uses Console.Write to display the message "Enter first integer: ". This message is called a prompt because it directs the user to take a specific action.

Line 16

number1 = Convert.ToInt32( Console.ReadLine() );

works in two steps. First, it 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. We introduce exception handling in Section 8.4, then use it again in Chapter 10. We take a deeper look at exception handling in Chapter 13.

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

Good Programming Practice 3.10

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

Line 18

Console.Write( "Enter second integer: " ); // prompt user

prompts the user to enter the second integer. Line 20

number2 = Convert.ToInt32( Console.ReadLine() );

reads a second integer and assigns it to the variable number2.

Line 22

sum = number1 + number2; // add numbers

calculates the sum of number1 and number2 and assigns the result to variable sum by using the assignment operator, =. The statement is read as “sum gets the value of number1 + number2.” Most calculations are performed in assignment statements. When number1 + number2 is encountered, the values stored in the variables are used in the calculation. 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

Console.WriteLine( "Sum is {0}", sum ); // display sum

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

The parentheses around the expression number1 + number2 are not required—they’re included to emphasize that the value of the expression number1 + number2 is output in the position of the {0} format item.

Memory Concepts

Variable names such as number1, number2 and sum actually correspond to locations in the computer’s memory. Every variable has a name, a type, a size (determined by the type) and a value.

In the addition application of Fig. 3.18, when the statement (line 16)

number1 = Convert.ToInt32( Console.ReadLine() );

executes, the number typed by the user is placed into a memory location to which the name number1 has been assigned by the compiler. Suppose that the user enters 45. The computer places that integer value into location number1, as shown in Fig. 3.19. Whenever a value is placed in a memory location, the value replaces the previous value in that location, and the previous value is lost.

Memory location showing the name and value of variable number1.

Figure 3.19. Memory location showing the name and value of variable number1.

When the statement (line 20)

number2 = Convert.ToInt32( Console.ReadLine() );

executes, suppose that the user enters 72. The computer places that integer value into location number2. The memory now appears as shown in Fig. 3.20.

Memory locations after storing values for number1 and number2.

Figure 3.20. Memory locations after storing values for number1 and number2.

After the application of Fig. 3.18 obtains values for number1 and number2, it adds the values and places the sum into variable sum. The statement (line 22)

sum = number1 + number2; // add numbers

performs the addition, then replaces sum’s previous value. After sum has been calculated, memory appears as shown in Fig. 3.21. The values of number1 and number2 appear exactly as they did before they were used in the calculation of sum. These values were used, but not destroyed, as the computer performed the calculation—when a value is read from a memory location, the process is nondestructive.

Memory locations after calculating and storing the sum of number1 and number2.

Figure 3.21. Memory locations after calculating and storing the sum of number1 and number2.

Arithmetic

Most applications perform arithmetic calculations. The arithmetic operators are summarized in Fig. 3.22. 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.22 are binary operators—for example, the expression f + 7 contains the binary operator + and the two operands f and 7.

Table 3.22. Arithmetic operators.

C# operation

Arithmetic operator

Algebraic expression

C# expression

Addition

+

f + 7

f + 7

Subtraction

pc

p - c

Multiplication

*

b · m

b * m

Division

/

x / y or Arithmetic operators. or x ÷ y

x / y

Remainder

%

r mod s

r % s

If both operands of the division operator (/) are integers, integer division is performed and the result is an integer—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. In this chapter’s exercises and in later chapters, we 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:

Arithmetic operators.

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.23). These rules enable C# to apply operators in the correct order.[1]

Table 3.23. Precedence of arithmetic operators.

Operators

Operations

Order of evaluation (associativity)

Evaluated first

  

*

Multiplication

If there are several operators of this type, they’re evaluated from left to right.

/

Division

%

Remainder

Evaluated next

  

+

Addition

If there are several operators of this type, they’re evaluated from left to right.

-

Subtraction

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.23 summarizes these rules of operator precedence. The table will be expanded as additional operators are introduced. Appendix A provides the complete precedence chart.

Now let us consider several expressions in light of the rules of operator precedence. Each example lists an algebraic expression and its C# equivalent. The following is an example of an arithmetic mean (average) of five terms:

Precedence of arithmetic operators.

The parentheses are required because division has higher precedence than addition. The entire quantity ( a + b + c + d + e ) is to be divided by 5. If the parentheses are erroneously omitted, we obtain a + b + c + d + e / 5, which evaluates as

Precedence of arithmetic operators.

The following is an example of the equation of a straight line:

Algebra:

y = mx + b

C#:

y = m * x + b;

No parentheses are required. The multiplication operator is applied first, because multiplication has a higher precedence than addition. The assignment occurs last, because it has a lower precedence than multiplication or addition.

The following example contains remainder (%), multiplication, division, addition and subtraction operations:

Precedence of arithmetic operators.

The circled numbers under the statement indicate the order in which C# applies the operators. The multiplication, remainder and division operations are evaluated first in left-to-right order (i.e., they associate from left to right), because they have higher precedence than addition and subtraction. The addition and subtraction operations are evaluated next. These operations are also applied from left to right.

To develop a better understanding of the rules of operator precedence, consider the evaluation of a second-degree polynomial (y = ax2 + bx + c):

Precedence of arithmetic operators.

The circled numbers indicate the order in which C# applies the operators. The multiplication operations are evaluated first in left-to-right order (i.e., they associate from left to right), because they have higher precedence than addition. The addition operations are evaluated next and are applied from left to right. There’s no arithmetic operator for exponentiation in C#, so x2 is represented as x * x. Section 6.4 shows an alternative for performing exponentiation in C#.

Suppose that a, b, c and x in the preceding second-degree polynomial are initialized (given values) as follows: a = 2, b = 3, c = 7 and x = 5. Figure 3.24 illustrates the order in which the operators are applied.

Order in which a second-degree polynomial is evaluated.

Figure 3.24. Order in which a second-degree polynomial is evaluated.

As in algebra, it’s acceptable to place unnecessary parentheses in an expression to make the expression clearer. These are called redundant parentheses. For example, the preceding assignment statement might be parenthesized to highlight its terms as follows:

y = ( a * x * x ) + ( b * x ) + c;

Decision Making: Equality and Relational Operators

A condition is an expression that can be either true or false. 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.25. 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.

Table 3.25. Relational and equality operators.

Standard algebraic equality and relational operators

C# equality or relational operator

Sample C# condition

Meaning of C# condition

Relational operators

>

>

x > y

x is greater than y

<

<

x < y

x is less than y

>=

x >= y

x is greater than or equal to y

<=

x <= y

x is less than or equal to y

Equality operators

=

==

x == y

x is equal to y

!=

x != y

x is not equal to y

Common Programming Error 3.5

Common Programming Error 3.5

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 programmers read the equality operator as “double equals” or “equals equals.”

Figure 3.26 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.

Example 3.26. Comparing integers using if statements, equality operators and relational operators.

 1   // Fig. 3.26: Comparison.cs
 2   // Comparing integers using if statements, equality operators,
 3   // and relational operators.
 4   using System;
 5
 6   public class Comparison
 7   {
 8       // Main method begins execution of C# application
 9       public static void Main( string[] args )
10       {
11           int number1; // declare first number to compare
12           int number2; // declare second number to compare
13
14           // prompt user and read first number
15           Console.Write( "Enter first integer: " );
16           number1 = Convert.ToInt32( Console.ReadLine() );
17
18           // prompt user and read second number
19           Console.Write( "Enter second integer: " );
20           number2 = Convert.ToInt32( Console.ReadLine() );
21
22           if ( number1 == number2 )                               
23               Console.WriteLine( "{0} == {1}", number1, number2 );
24
25           if ( number1 != number2 )                               
26               Console.WriteLine( "{0} != {1}", number1, number2 );
27
28           if ( number1 < number2 )                               
29               Console.WriteLine( "{0} < {1}", number1, number2 );
30
31           if ( number1 > number2 )                               
32               Console.WriteLine( "{0} > {1}", number1, number2 );
33
34           if ( number1 <= number2 )                               
35               Console.WriteLine( "{0} <= {1}", number1, number2 );
36
37           if ( number1 >= number2 )                               
38               Console.WriteLine( "{0} >= {1}", number1, number2 );
39       } // end Main
40   } // end class Comparison
Enter first integer: 42
Enter second integer: 42
42 == 42
42 <= 42
42 >= 42
Enter first integer: 1000
Enter second integer: 2000
1000 != 2000
1000 < 2000
1000 <= 2000
Enter first integer: 2000
Enter second integer: 1000
2000 != 1000
2000 > 1000
2000 >= 1000

The declaration of class Comparison begins at line 6

public class Comparison

The class’s Main method (lines 9–39) begins the execution of the application.

Lines 11–12

int number1; // declare first number to compare
int number2; // declare second number to compare

declare the int variables used to store the values entered by the user.

Lines 14–16

// prompt user and read first number
Console.Write( "Enter first integer: " );
number1 = Convert.ToInt32( Console.ReadLine() );

prompt the user to enter the first integer and input the value. The input value is stored in variable number1. Lines 18–20

// prompt user and read second number
Console.Write( "Enter second integer: " );
number2 = Convert.ToInt32( Console.ReadLine() );

perform the same task, except that the input value is stored in variable number2.

Lines 22–23

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

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

Common Programming Error 3.6

Omitting 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

Common Programming Error 3.7

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

Common Programming Error 3.8

Common Programming Error 3.8

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

Good Programming Practice 3.11

Good Programming Practice 3.11

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

There’s 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

Common Programming Error 3.9

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.26. 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.12

Good Programming Practice 3.12

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

Good Programming Practice 3.13

Good Programming Practice 3.13

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

Table 3.27. Precedence and associativity of operations discussed.

Operators

Associativity

Type

*

/

%

 

left to right

multiplicative

+

-

  

left to right

additive

<

<=

>

>=

left to right

relational

==

!=

  

left to right

equality

=

   

right to left

assignment

Good Programming Practice 3.14

Good Programming Practice 3.14

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.

Wrap-Up

You learned many important features of C# in this chapter, including displaying data on the screen 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.

Summary

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

  • Programmers insert comments to document applications and improve their readability. The C# compiler ignores comments.

  • A comment that begins with // is called a single-line comment, because it terminates at the end of the line on which it appears.

  • Comments delimited by /* and */ can be spread over several lines.

  • A programming language’s syntax specifies rules for creating a proper application in that language.

  • A using directive helps the compiler locate a class that is used in an application.

  • C# provides a rich set of predefined classes that you can reuse rather than “reinventing the wheel.” These classes are grouped into namespaces—named collections of classes.

  • Collectively, C#’s predefined namespaces are referred to as the .NET Framework Class Library.

  • Programmers use blank lines and space characters to make applications easier to read. Together, blank lines, space characters and tab characters are known as whitespace. Space characters and tabs are known specifically as whitespace characters. Whitespace is ignored by the compiler.

  • Every application in C# consists of at least one class declaration that is defined by the programmer (also known as a user-defined class).

  • Keywords are reserved for use by C# and are always spelled with all lowercase letters.

  • Keyword class introduces a class declaration and is immediately followed by the class name.

  • By convention, all class names in C# begin with a capital letter and capitalize the first letter of each word they include (e.g., SampleClassName). The is known as upper camel casing.

  • A C# 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.

  • C# is case sensitive—that is, uppercase and lowercase letters are distinct.

  • The body of every class declaration is delimited by braces, { and }.

  • Method Main is the starting point of every C# application and is typically defined as:

    public static void Main( string[] args )
  • Methods are able to perform tasks and can return information when they complete their tasks. Keyword void indicates that a method will perform a task but will not return any information.

  • Statements instruct the computer to perform actions.

  • A sequence of characters in double quotation marks is called a string, a character string, a message or a string literal.

  • The Console class allows C# applications to read and display characters in the console window.

  • Method Console.WriteLine displays its argument in the console window, followed by a newline character to position the screen cursor to the beginning of the next line.

  • Most statements end with a semicolon.

Section 3.3 Creating a Simple Application in Visual C# Express

  • Visual C# Express provides many ways to personalize your coding experience. You can modify the editor settings to display line numbers or set code indentation.

  • As you type characters, in some contexts Visual C# Express highlights the first member that matches all the characters typed, then displays a tool tip containing a description of that member. This IDE feature is called IntelliSense.

  • To execute an application, select Debug > Start Without Debugging.

  • When you type a line of code and press Enter, the IDE either applies syntax-color highlighting or generates a syntax error.

Section 3.4 Modifying Your Simple C# Application

  • Console.Write displays its argument and positions the screen cursor immediately after the last character displayed.

  • C# combines a backslash () in a string with the next character in the string to form an escape sequence. The escape sequence (newline) positions the cursor on the next line.

Section 3.5 Formatting Text with Console.Write and Console.WriteLine

  • The Console.Write and Console.WriteLine methods can also display formatted data.

  • When a method requires multiple arguments, the arguments are separated with commas (,)—this is known as a comma-separated list.

  • Method Console.Write’s first argument can be a format string that may consist of fixed text and format items. Fixed text is displayed normally. Each format item is a placeholder for a value.

  • Format items are enclosed in curly braces and begin with a number that specifies an argument. The format item {0} is a placeholder for the first additional argument after the format string (because we start counting from 0), {1} is a placeholder for the second, and so on.

Section 3.6 Another C# Application: Adding Integers

  • Integers are whole numbers, like −22, 7, 0 and 1024.

  • A variable declaration statement specifies the name and type of a variable.

  • A variable is a location in the computer’s memory where a value can be stored for use later in an application. Variables are typically declared with a name and a type before they’re used.

  • A variable’s name enables the application to access the value of the variable in memory. A variable name can be any valid identifier.

  • Like other statements, variable declaration statements end with a semicolon (;).

  • Type int is used to declare variables that will hold integer values. The range of values for an int is −2,147,483,648 to +2,147,483,647.

  • Types float, double, and decimal specify real numbers, and type char specifies character data. Real numbers are numbers that may contain decimal points, such as 3.4, 0.0 and −11.19. Variables of type char data 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 often called simple types. Simple-type names are keywords; thus, they must appear in all lowercase letters.

  • A prompt directs the user to take a specific action.

  • Console method ReadLine obtains a line of text for use in an application.

  • Convert method ToInt32 extracts an integer from a string of characters.

  • The assignment operator, =, enables the application to give a value to a variable. Operator = is called a binary operator because it has two operands. An assignment statement uses an assignment operator to assign a value to a variable.

  • Portions of statements that have values are called expressions.

Section 3.7 Memory Concepts

  • Variable names correspond to locations in the computer’s memory. Every variable has a name, a type, a size and a value.

  • Whenever a value is placed in a memory location, the value replaces the previous value in that location. The previous value is lost.

Section 3.8 Arithmetic

  • Most applications perform arithmetic calculations. The arithmetic operators are + (addition), - (subtraction), * (multiplication), / (division) and % (remainder).

  • If both operands of the division operator (/) are integers, the result is an integer

  • The remainder operator, %, yields the remainder after division.

  • Arithmetic expressions in C# must be written in straight-line form.

  • If an expression contains nested parentheses, the innermost set of parentheses is evaluated first.

  • C# applies the operators in arithmetic expressions in a precise sequence determined by the rules of operator precedence.

  • Associativity determines whether operators are applied from left to right or right to left.

  • Redundant parentheses in an expression can make an expression clearer.

Section 3.9 Decision Making: Equality and Relational Operators

  • A condition is an expression that can be either true or false. C#’s if statement allows an application to make a decision based on the value of a condition.

  • Conditions in if statements can be formed by using the equality (== and !=) and relational (>, <, >= and <=) operators.

  • An if statement always begins with keyword if, followed by a condition in parentheses, and expects one statement in its body.

  • An empty statement is a statement that does not perform a task.

Terminology

Self-Review Exercises

3.1

Fill in the blanks in each of the following statements:

  1. A(n) ______ begins the body of every method, and a(n) ______ ends the body of every method.

  2. Most statements end with a(n) ______.

  3. The ______ statement is used to make decisions.

  4. ______ begins a single-line comment.

  5. ______, ______ and ______ are called whitespace characters. Newline characters are also considered whitespace characters.

  6. ___________ are reserved for use by C#.

  7. C# applications begin execution at method ______.

  8. Methods ______ and ______ display information in the console window.

3.1

  1. left brace ({), right brace (}).

  2. semicolon (;).

  3. if.

  4. //.

  5. Blank lines, space characters, tab characters.

  6. Keywords.

  7. Main.

  8. Console.WriteLine and Console.Write.

3.2

State whether each of the following is true or false. If false, explain why.

  1. Comments cause the computer to display the text after the // on the screen when the application executes.

  2. C# considers the variables number and NuMbEr to be identical.

  3. The remainder operator (%) can be used only with integer operands.

  4. The arithmetic operators *, /, %, + and - all have the same level of precedence.

3.2

  1. False. Comments do not cause any action to be performed when the application executes. They’re used to document applications and improve their readability.

  2. False. C# is case sensitive, so these variables are distinct.

  3. False. The remainder operator also can be used with noninteger operands in C#.

  4. False. The operators *, / and % are on the same level of precedence, and the operators + and - are on a lower level of precedence.

3.3

Write statements to accomplish each of the following tasks:

  1. Declare variables c, thisIsAVariable, q76354 and number to be of type int.

  2. Prompt the user to enter an integer.

  3. Input an integer and assign the result to int variable value.

  4. If the variable number is not equal to 7, display "The variable number is not equal to 7".

  5. Display "This is a C# application" on one line in the console window.

  6. Display "This is a C# application" on two lines in the console window. The first line should end with C#. Use method Console.WriteLine.

  7. Display "This is a C# application" on two lines in the console window. The first line should end with C#. Use method Console.WriteLine and two format items.

3.3

  1. int c, thisIsAVariable, q76354, number;

    or

    int c;
    int thisIsAVariable;
    int q76354;
    int number;
  2. Console.Write( "Enter an integer: " );
  3. value = Convert.ToInt32( Console.ReadLine() );
  4. if ( number != 7 )
       Console.WriteLine( "The variable number is not equal to 7" );
  5. Console.WriteLine( "This is a C# application" );
  6. Console.WriteLine( "This is a C#
    application" );
  7. Console.WriteLine( "{0}
    {1}", "This is a C#", "application" );

3.4

Identify and correct the errors in each of the following statements:

  1. if ( c < 7 );
       Console.WriteLine( "c is less than 7" );
  2. if ( c => 7 )
       Console.WriteLine( "c is equal to or greater than 7" );

3.4

  1. Error: Semicolon after the right parenthesis of the condition ( c < 7 ) in the if statement.

    Correction: Remove the semicolon after the right parenthesis. [Note: As a result, the output statement will execute regardless of whether the condition in the if is true.]

  2. Error: The relational operator => is incorrect.

    Correction: Change => to >=.

3.5

Write declarations, statements or comments that accomplish each of the following tasks:

  1. State that an application will calculate the product of three integers.

  2. Declare the variables x, y, z and result to be of type int.

  3. Prompt the user to enter the first integer.

  4. Read the first integer from the user and store it in the variable x.

  5. Prompt the user to enter the second integer.

  6. Read the second integer from the user and store it in the variable y.

  7. Prompt the user to enter the third integer.

  8. Read the third integer from the user and store it in the variable z.

  9. Compute the product of the three integers contained in variables x, y and z, and assign the result to the variable result.

  10. Display the message "Product is", followed by the value of the variable result.

3.5

  1. // Calculating the product of three integers
  2. int x, y, z, result;

    or

    int x;
    int y;
    int z;
    int result;
  3. Console.Write( "Enter first integer: " );
  4. x = Convert.ToInt32( Console.ReadLine() );
  5. Console.Write( "Enter second integer: " );
  6. y = Convert.ToInt32( Console.ReadLine() );
  7. Console.Write( "Enter third integer: " );
  8. z = Convert.ToInt32( Console.ReadLine() );
  9. result = x * y * z;
  10. Console.WriteLine( "Product is {0}", result );

3.6

Using the statements you wrote in Exercise 3.5, write a complete application that calculates and displays the product of three integers.

3.6

The solution to Self-Review Exercise 3.6 is as follows:

 1   // Exercise 3.6: Product.cs
 2   // Calculating the product of three integers.
 3   using System;
 4
 5   public class Product
 6   {
 7      public static void Main( string[] args )
 8      {
 9         int x; // stores first number to be entered by user
10         int y; // stores second number to be entered by user
11         int z; // stores third number to be entered by user
12         int result; // product of numbers
13
14         Console.Write( "Enter first integer: " ); // prompt for input
15         x = Convert.ToInt32( Console.ReadLine() ); // read first integer
16
17         Console.Write( "Enter second integer: " ); // prompt for input
18         y = Convert.ToInt32( Console.ReadLine() ); // read second integer
19
20         Console.Write( "Enter third integer: " ); // prompt for input
21         z = Convert.ToInt32( Console.ReadLine() ); // read third integer
22
23         result = x * y * z; // calculate the product of the numbers
24
25         Console.WriteLine( "Product is {0}", result );
26      } // end Main
27   } // end class Product

Answers to Self-Review Exercises

Exercises

3.7

Fill in the blanks in each of the following statements:

  1. _______ are used to document an application and improve its readability.

  2. A decision can be made in a C# application with a(n) _______.

  3. Calculations are normally performed by _______ statements.

  4. The arithmetic operators with the same precedence as multiplication are _______ and _______.

  5. When parentheses in an arithmetic expression are nested, the _______ set of parentheses is evaluated first.

  6. A location in the computer’s memory that may contain different values at various times throughout the execution of an application is called a(n) _______.

3.8

Write C# statements that accomplish each of the following tasks:

  1. Display the message "Enter an integer: ", leaving the cursor on the same line.

  2. Assign the product of variables b and c to variable a.

  3. State that an application performs a simple payroll calculation (i.e., use text that helps to document an application).

3.9

State whether each of the following is true or false. If false, explain why.

  1. C# operators are evaluated from left to right.

  2. The following are all valid variable names: _under_bar_, m928134, t5, j7, her_sales, his_account_total, a, b, c, z and z2.

  3. A valid C# arithmetic expression with no parentheses is evaluated from left to right.

  4. The following are all invalid variable names: 3g, 87, 67h2, h22 and 2h.

3.10

Assuming that x = 2 and y = 3, what does each of the following statements display?

  1. Console.WriteLine( "x = {0}", x );
  2. Console.WriteLine( "Value of {0} + {0} is {1}", x, ( x + x ) );
  3. Console.Write( "x =" );
  4. Console.WriteLine( "{0} = {1}", ( x + y ), ( y + x ) );

3.11

Which of the following C# statements contain variables whose values are modified?

  1. p = i + j + k + 7;
  2. Console.WriteLine( "variables whose values are modified" );
  3. Console.WriteLine( "a = 5" );
  4. value = Convert.ToInt32( Console.ReadLine() );

3.12

Given that y = ax3 + 7, which of the following are correct C# statements for this equation?

  1. y = a * x * x * x + 7;
  2. y = a * x * x * ( x + 7 );
  3. y = ( a * x ) * x * ( x + 7 );
  4. y = ( a * x ) * x * x + 7;
  5. y = a * ( x * x * x ) + 7;
  6. y = a * x * ( x * x + 7 );

3.13

(Order of Evaluation) State the order of evaluation of the operators in each of the following C# statements and show the value of x after each statement is performed:

  1. x = 7 + 3 * 6 / 2 - 1;
  2. x = 2 % 2 + 2 * 2 - 2 / 2;
  3. x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) );

3.14

(Printing) Write an application that displays the numbers 1 to 4 on the same line, with each pair of adjacent numbers separated by one space. Write the application using the following techniques:

  1. Use one Console.WriteLine statement.

  2. Use four Console.Write statements.

  3. Use one Console.WriteLine statement with four format items.

3.15

(Arithmetic) Write an application that asks the user to enter two integers, obtains them from the user and displays their sum, product, difference and quotient (division). Use the techniques shown in Fig. 3.18.

3.16

(Comparing Integers) Write an application that asks the user to enter two integers, obtains them from the user and displays the larger number followed by the words "is larger". If the numbers are equal, display the message "These numbers are equal." Use the techniques shown in Fig. 3.26.

3.17

(Arithmetic, Smallest and Largest) Write an application that inputs three integers from the user and displays the sum, average, product, and smallest and largest of the numbers. Use the techniques from Fig. 3.26. [Note: The average calculation in this exercise should result in an integer representation of the average. So, if the sum of the values is 7, the average should be 2, not 2.3333....]

3.18

(Displaying Shapes with Asterisks) Write an application that displays a box, an oval, an arrow and a diamond using asterisks (*), as follows:

*********     ***       *        *
*       *   *     *    ***      * *
*       *  *       *  *****    *   *
*       *  *       *    *     *     *
*       *  *       *    *    *       *
*       *  *       *    *     *     *
*       *  *       *    *      *   *
*       *   *     *     *       * *
*********     ***       *        *

3.19

What does the following code display?

Console.WriteLine( "*
**
***
****
*****" );

3.20

What does the following code display?

Console.WriteLine( "*" );
Console.WriteLine( "***" );
Console.WriteLine( "*****" );
Console.WriteLine( "****" );
Console.WriteLine( "**" );

3.21

What does the following code display?

Console.Write( "*" );
Console.Write( "***" );
Console.Write( "*****" );
Console.Write( "****" );
Console.WriteLine( "**" );

3.22

What does the following code display?

Console.Write( "*" );
Console.WriteLine( "***" );
Console.WriteLine( "*****" );
Console.Write( "****" );
Console.WriteLine( "**" );

3.23

What does the following code display?

Console.WriteLine( "{0}
{1}
{2}", "*", "***", "*****" );

3.24

(Odd or Even) Write an application that reads an integer, then determines and displays whether it’s odd or even. [Hint: Use the remainder operator. An even number is a multiple of 2. Any multiple of 2 leaves a remainder of 0 when divided by 2.]

3.25

(Multiples) Write an application that reads two integers, determines whether the first is a multiple of the second and displays the result. [Hint: Use the remainder operator.]

3.26

(Diameter, Circumference and Area of a Circle) Here’s a peek ahead. In this chapter, you have learned about integers and the type int. C# can also represent floating-point numbers that contain decimal points, such as 3.14159. Write an application that inputs from the user the radius of a circle as an integer and displays the circle’s diameter, circumference and area using the floating-point value 3.14159 for π. Use the techniques shown in Fig. 3.18. [Note: You may also use the predefined constant Math.PI for the value of π. This constant is more precise than the value 3.14159. Class Math is defined in namespace System]. Use the following formulas (r is the radius):

  • diameter = 2r

  • circumference = 2πr

  • area = πr2

Don’t store each calculation’s result in a variable. Rather, specify each calculation as the value to be output in a Console.WriteLine statement. The values produced by the circumference and area calculations are floating-point numbers. You’ll learn more about floating-point numbers in Chapter 4.

3.27

(Integer Equivalent of a Character) Here’s another peek ahead. In this chapter, you have learned about integers and the type int. C# can also represent uppercase letters, lowercase letters and a considerable variety of special symbols. Every character has a corresponding integer representation. The set of characters a computer uses and the corresponding integer representations for those characters is called that computer’s character set. You can indicate a character value in an application simply by enclosing that character in single quotes, as in 'A'.

You can determine the integer equivalent of a character by preceding that character with (int), as in

(int) 'A'

The keyword int in parentheses is known as a cast operator, and the entire expression is called a cast expression. (You’ll learn about cast operators in Chapter 5.) The following statement outputs a character and its integer equivalent:

Console.WriteLine( "The character {0} has the value {1}",
   'A', ( ( int ) 'A' ) );

When the preceding statement executes, it displays the character A and the value 65 (from the Unicode® character set) as part of the string.

Using statements similar to the one shown earlier in this exercise, write an application that displays the integer equivalents of some uppercase letters, lowercase letters, digits and special symbols. Display the integer equivalents of the following: A B C a b c 0 1 2 $ * + / and the space character.

3.28

(Digits of an Integer) Write an application that inputs one number consisting of five digits from the user, separates the number into its individual digits and displays the digits separated from one another by three spaces each. For example, if the user types in the number 42339, the application should display

4   2   3   3   9

Assume that the user enters the correct number of digits. What happens when you execute the application and type a number with more than five digits? What happens when you execute the application and type a number with fewer than five digits? [Hint: It’s possible to do this exercise with the techniques you learned in this chapter. You’ll need to use both division and remainder operations to “pick off” each digit.]

3.29

(Table of Squares and Cubes) Using only the programming techniques you learned in this chapter, write an application that calculates the squares and cubes of the numbers from 0 to 10 and displays the resulting values in table format, as shown below. All calculations should be done in terms of a variable x. [Note: This application does not require any input from the user.]

number  square  cube
0       0       0
1       1       1
2       4       8
3       9       27
4       16      64
5       25      125
6       36      216
7       49      343
8       64      512
9       81      729
10      100     1000

3.30

(Counting Negative, Positive and Zero Values) Write an application that inputs five numbers and determines and displays the number of negative numbers input, the number of positive numbers input and the number of zeros input.

Making a Difference Exercises

3.31

(Body Mass Index Calculator) We introduced the body mass index (BMI) calculator in Exercise 1.19. The formulas for calculating the BMI are

Making a Difference Exercises

or

Making a Difference Exercises

Create a BMI calculator application that reads the user’s weight in pounds and height in inches (or, if you prefer, the user’s weight in kilograms and height in meters), then calculates and displays the user’s body mass index. The application should also display the following information from the Department of Health and Human Services/National Institutes of Health so the user can evaluate his/her BMI:

BMI VALUES
Underweight: less than 18.5
Normal:      between 18.5 and 24.9
Overweight:  between 25 and 29.9
Obese:       30 or greater

3.32

(Car-Pool Savings Calculator) Research several car-pooling websites. Create an application that calculates your daily driving cost, so that you can estimate how much money could be saved by car pooling, which also has other advantages such as reducing carbon emissions and reducing traffic congestion. The application should input the following information and display the user’s cost per day of driving to work:

  1. Total miles driven per day.

  2. Cost per gallon of gasoline (in cents).

  3. Average miles per gallon.

  4. Parking fees per day (in cents).

  5. Tolls per day (in cents).



[1] We discuss simple examples here to explain the order of evaluation of expressions. More subtle order of evaluation issues occur in the increasingly complex expressions you’ll encounter later in the book. For more information, see the following blog posts from Microsoft’s Eric Lippert: blogs.msdn.com/ericlippert/archive/2008/05/23/precedence-vs-associativity-vs-order.aspx and blogs.msdn.com/oldnewthing/archive/2007/08/14/4374222.aspx.

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

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