Our next application (Fig. 3.11) inputs two integers (whole numbers) typed by a user at the
keyboard, computes the sum of these values and displays the result. As the user types each
integer and presses the Enter key, the integer is read into the program and added to the total.
Lines 1–2 are single-line comments stating the figure number, file name and purpose of the
program.
As stated previously, every C# program consists of at least one class definition. Line
6 begins the definition of class Addition. Lines 7–37 define the body of the class. Recall
that all class definitions start with an opening left brace ({) and end with a closing right
brace (}).
keyboard, computes the sum of these values and displays the result. As the user types each
integer and presses the Enter key, the integer is read into the program and added to the total.
Lines 1–2 are single-line comments stating the figure number, file name and purpose of the
program.
As stated previously, every C# program consists of at least one class definition. Line
6 begins the definition of class Addition. Lines 7–37 define the body of the class. Recall
that all class definitions start with an opening left brace ({) and end with a closing right
brace (}).
The program begins execution with method Main on line 8. The left brace (line 9)
begins Main’s body and the corresponding right brace (line 35) terminates Main’s body.
Lines 10–11 are a declaration. The words firstNumber and secondNumber are
the names of variables. A variable is a location in the computer’s memory where a value
can be stored for use by a program. All variables must be declared with a name and a data
type before they can be used in a program. This declaration specifies that the variables
firstNumber and secondNumber are data of type string, which means that these variables store strings of characters. There are certain data types already defined in the
.NET Framework, known as built-in data types or primitive data types. Types such as
string, int, double and char are examples of primitive data types. Primitive type
names are keywords. The 15 primitive types are summarized in Chapter 4, Control Struc-
tures: Part 1.
A variable name can be any valid identifier. Declarations end with a semicolon (;) and
can be split over several lines with each variable in the declaration separated by a comma
(i.e., a comma-separated list of variable names). Several variables of the same type may be
declared in one or in multiple declarations. We could have written two declarations, one for
each variable, but the preceding declaration is more concise. Notice the single-line com-
ments at the end of each line. This is a common syntax used by programmers to indicate
the purpose of each variable in the program.
Good Programming Practice 3.7
Choosing meaningful variable names helps a program to be “self-documenting” (i.e., easier
to understand simply by reading it, rather than having to read manuals or use excessive com-
ments).
Good Programming Practice 3.8
By convention, variable-name identifiers begin with a lowercase letter. As with class names,
every word in the name after the first word should begin with a capital letter. For example,
identifier firstNumber has a capital N in its second word, Number.
Good Programming Practice 3.9
Some programmers prefer to declare each variable on a separate line. This format allows for
easy insertion of a comment that describes each variable.
Lines 13–15 declare that variables number1, number2 and sum are of data type
int, which means that these variables will hold integer values (i.e., whole numbers such
as –11, 7, 0 and 31914). In contrast, the data types float and double specify real num-
bers (i.e., floating-point numbers with decimal points, such as 3.4, 0.0 and –11.19) and vari-
ables of type char specify character data. A char variable may hold only a single
lowercase letter, a single uppercase letter, a single digit or a single character, such as x, $,
7, * and escape sequences (like as the newline character \n). Oftentimes in programs,
characters are denoted in single quotes, such as 'x', '$', '7', '*' and '\n', to differ-
entiate between a value and a variable name. C# is also capable of representing all Unicode
characters. Unicode is an extensive international character set (collection of characters)
that enables the programmer to display letters in different languages, mathematical sym-
bols and much more. For more information on this topic, see Appendix G, Unicode.
Lines 18–19 prompt the user to input an integer and read from the user a string rep-
resenting the first of the two integers that the program will add. The message on line 18 is
called a prompt, because it directs the user to take a specific action. Method ReadLine
(line 19) causes the program to pause and wait for user input. The user inputs characters
from the keyboard, then presses the Enter key to return the string to the program. Unfortu-
nately, the .NET Framework does not provide a simple input dialog. For this reason, the
examples in these early chapters receive user input through the command prompt.
Technically, the user can send anything to the program as input. For this program, if
the user types a noninteger value, a run-time logic error (an error that has its effect at execution time) occurs. Chapter 11, Exception Handling, discusses how to make your pro-
grams more robust by handling such errors.
When the user enters a number and presses Enter, the program assigns the string rep-
resentation of this number to variable firstNumber (line 19) with the assignment oper-
ator =. The statement is read as, “firstNumber gets the value returned by method
ReadLine.” The = operator is a binary operator, because it has two operands—first-
Number, and the result of the expression Console.ReadLine. The entire statement is
an assignment statement, because it assigns a value to a variable. In an assignment state-
ment, first the right side of the assignment is evaluated, then the result is assigned to the
variable on the left side of the assignment. So, line 19 executes method ReadLine, then
assigns the string value to firstNumber.
Good Programming Practice 3.10
Place spaces on either side of a binary operator. This makes the operator stand out and
makes the program more readable.
Lines 22–23 prompt the user to enter a second integer and read from the user a string
representing the value. Lines 26–27 convert the two strings input by the user to int values
that can be used in a calculation. Method Int32.Parse (a static method of class Int32)
converts its string argument to an integer. Class Int32 is part of the System
namespace. Line 26 assigns the integer that Int32.Parse returns to variable number1.
Any subsequent references to number1 in the program use this integer value. Line 27
assigns the integer that Int32.Parse returns to variable number2. Any subsequent ref-
erences to number2 in the program use this integer value. You can eliminate the need for
string variables firstNumber and secondNumber by combining the input and
conversion operations as follows:
int number1;
number1 = Int32.Parse( Console.ReadLine() );
In C#, users input data as strings. We convert these strings to perform integer arith-
metic. Arithmetic operations, as we will discuss in Section 3.5, do not work with strings
the same way operations work with integers. To add numbers and get the proper sum, we
must convert the strings to integers. The preceding statements do not make use of the
string variable (firstNumber). This variable is required only to store the string
temporarily until the program converts it. Reading the string and converting it on one
line makes the variable unnecessary.
The assignment statement on line 30 calculates the sum of the variables 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 plus number2.” Most calculations
are performed in assignment statements.
After performing the calculation, line 33 displays the result of the addition. In this
example, we want to output the value in a variable using method WriteLine. Let us dis-
cuss how this is done.
The comma-separated arguments to Console.WriteLine
"\nThe sum is {0}.", sum
use {0} to indicate a placeholder for a variable’s value. If we assume that sum contains
the value 117, the expression evaluates as follows: Method WriteLine encounters a number in curly braces, {0}, known as a format. This indicates that the variable found after
the string in the list of arguments (in this case, sum) will be evaluated and incorporated into
our string, in place of the format. The resulting string will be “The sum is 117.” Simi-
larly, in the statement
Console.WriteLine(
"The numbers entered are {0} and {1}", number1, number2 );
the value of number1 would replace {0} (because it is the first variable) and the value of
number2 would replace {1} (because it is the second variable). The resulting string
would be "The numbers entered are 45 and 72". More formats can be used ({2},
{3} etc.) if there are more variables to display in the string.
Good Programming Practice 3.11
Place a space after each comma in a method’s argument list to make programs more read-
able.
Some programmers find it difficult, when reading or writing a program, to match the
left and right braces ({ and }) that delimit the body of a class or method definition. For this
reason, some programmers include a single-line comment after each closing right brace that
ends a method or class definition, as we do in lines 35 and 37.
Good Programming Practice 3.12
Follow the closing right brace (}) of the body of a method or class definition with a single-
line comment. This comment should indicate the method or class that the right brace termi-
nates.
0 comments:
Post a Comment