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 |
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>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.
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
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).
/* 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.
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.
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.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| ||
Contextual Keywords | ||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.
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.
C# is case sensitive. Not using the proper uppercase and lowercase letters for an identifier normally causes a compilation error.
In Chapters 3–9, 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
.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 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.]
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.
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.
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 button on the IDE’s toolbar).
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.
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.
This section continues our introduction to C# programming with two examples that modify the example of Fig. 3.1.
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
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.
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 ( |
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
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.
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.
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.
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.
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 |
Declare each variable on a separate line. This format allows a comment to be easily inserted next to each declaration.
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).
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.
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.
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.
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.
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.
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
.
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 float
s, double
s, and decimal
s. 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:
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:
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
The following is an example of the equation of a straight line:
Algebra: | y = mx + b |
C#: |
|
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:
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):
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.
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; |
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.
C# equality or relational operator | Sample C# condition | Meaning of C# condition | |
---|---|---|---|
Relational operators | |||
> |
|
|
|
< |
|
|
|
≥ |
|
|
|
≤ |
|
|
|
Equality operators | |||
= |
|
|
|
≠ |
|
|
|
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.
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.
Omitting the left and/or right parentheses for the condition in an if
statement is a syntax error—the parentheses are required.
Reversing the operators !=
, >=
and <=
, as in =!
, =>
and =<
, can result in syntax or logic errors.
It is a syntax error if the operators ==
, !=
, >=
and <=
contain spaces between their symbols, as in = =
, ! =
, > =
and < =
, respectively.
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
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.
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.
Place no more than one statement per line in an application. This format enhances readability.
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
.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
assembly
member of a class
precedence of operators
self-documenting program
3.1 | Fill in the blanks in each of the following statements:
|
3.1 |
|
3.2 | State whether each of the following is true or false. If false, explain why.
|
3.2 |
|
3.3 | Write statements to accomplish each of the following tasks:
|
3.3 |
|
3.4 | Identify and correct the errors in each of the following statements:
|
3.4 |
|
3.5 | Write declarations, statements or comments that accomplish each of the following tasks:
|
3.5 |
|
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 |
3.7 | Fill in the blanks in each of the following statements:
| |
3.8 | Write C# statements that accomplish each of the following tasks:
| |
3.9 | State whether each of the following is true or false. If false, explain why.
| |
3.10 | Assuming that
| |
3.11 | Which of the following C# statements contain variables whose values are modified?
| |
3.12 | Given that y = ax3 + 7, which of the following are correct C# statements for this equation?
| |
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
| |
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:
| |
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 | |
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
Don’t store each calculation’s result in a variable. Rather, specify each calculation as the value to be output in a | |
3.27 | (Integer Equivalent of a Character) Here’s another peek ahead. In this chapter, you have learned about integers and the type You can determine the integer equivalent of a character by preceding that character with (int) 'A' The keyword Console.WriteLine( "The character {0} has the value {1}", 'A', ( ( int ) 'A' ) ); When the preceding statement executes, it displays the character 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: | |
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
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
| |
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. |
[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.