3.6 Another C# App: Adding Integers

Our next app 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 app must keep track of the numbers supplied by the user for the calculation later in the app, so once again we’ll use variables. The app of Fig. 3.14 demonstrates these concepts. In the sample output, we highlight data the user enters at the keyboard in bold.

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

Alternate View

  1   // Fig. 3.14: Addition.cs
  2   // Displaying the sum of two numbers input from the keyboard.
  3   using System;
  4
  5   class Addition
  6   {
  7      // Main method begins execution of C# app
  8      static void Main()
  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 = int.Parse(Console.ReadLine());
 17
 18         Console.Write("Enter second integer: "); // prompt user
 19         // read second number from user
 20         number2 = int.Parse(Console.ReadLine());
 21
 22         sum = number1 + number2; // add numbers
 23
 24         Console.WriteLine($"Sum is {sum}"); // display sum
 25      } // end Main
 26   } // end class Addition

Enter first integer: 45
Enter second integer: 72
Sum is 117

Comments

Lines 1–2


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

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

Class Addition

Line 5


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

Function Main

The app 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 class Addition’s body, and the code in the Main’s body is indented another level for readability.

3.6.1 Declaring the int Variable number1

Line 10


int number1; // declare first number to add

is a variable declaration statement specifying that number1 has 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 numbers with decimal points (as in 3.4, 0.0 and –11.19), and type char, for specifying characters. Variables of type float and double store approximations of real numbers in memory. Variables of type decimal store numbers with decimal points precisely (to 28–29 significant digits3), so decimal variables are often used with monetary calculations—we use type decimal to represent the balance in our Account class in Chapter 4. Variables of type char represent individual characters, such as an uppercase letter (e.g., A), a digit (e.g., 7), a special character (e.g., * or %) or an escape sequence (e.g., the newline character, ). Types such as int, float, double, decimal and char are called simple types. Simple-type names are keywords and must appear in all lowercase letters. Appendix B summarizes the characteristics of the simple types (bool, byte, sbyte, char, short, ushort, int, uint, long, ulong, float, double and decimal), including the amount of memory required to store a value of each type.

3.6.2 Declaring Variables number2 and sum

The variable declaration statements at lines 11–12


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

declare variables number2 and sum to be of type int.

Good Programming Practice 3.6

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

Good Programming Practice 3.7

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

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 (e.g., firstNumber). This naming convention is known as camel case.

3.6.3 Prompting the User for Input

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.

3.6.4 Reading a Value into Variable number1

Line 16


number1 = int.Parse(Console.ReadLine());

works in two steps. First, it calls the Console’s ReadLine method, which 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 re-turns the text the user entered. Then the returned string is used as an argument to type int’s Parse method, which converts this sequence of characters into data of type int.

Possible Erroneous User Input

Technically, the user can type anything as the input value. ReadLine will accept it and pass it off to int’s Parse method. This method assumes that the string contains a valid integer value. In this app, if the user types a noninteger value, a runtime logic error called an exception will occur and the app will terminate. The string processing techniques you’ll learn in Chapter 16 can be used to check that the input is in the correct format before attempting to convert the string to an int. C# also offers a technology called exception handling that will help you make your apps more robust by enabling them to handle exceptions and continue executing. This is also known as making your app 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 and throughout the book.

Assigning a Value to a Variable

In line 16, the result of the call to int’s Parse method (an int value) is placed in variable number1 by using the assignment operator, =. The statement is read as “number1 gets the value returned by int.Parse.” 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 int.Parse. 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.9

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

3.6.5 Prompting the User for Input and Reading a Value into number2

Line 18


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

prompts the user to enter the second integer. Line 20


number2 = int.Parse(Console.ReadLine());

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

3.6.6 Summing number1 and 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.” 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.

3.6.7 Displaying the sum with string Interpolation

After the calculation has been performed, line 24


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

uses method Console.WriteLine to display the sum. C# replaces the interpolation expression {sum} with the calculated sum from line 22. So method WriteLine displays "Sum is ", followed by the value of sum and a newline.

3.6.8 Performing Calculations in Output Statements

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


Console.WriteLine($"Sum is {number1 + number2}");
..................Content has been hidden....................

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