 • Print
This chapter is from the book

## 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. Apps remember numbers and other data in the computer’s memory and access that data through app elements called 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.

``` `1`   `// Fig. 3.14: 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# app`
`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````

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.

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

### 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 the body of class Addition and the code in the body of Main is indented another level for readability.

### Declaring Variable number1

Line 10

``int number1; // declare first number to add``

is a variable declaration statement that specifies the name (number1) and type of a variable (int) used in this app. Variables are typically declared with a name and a type before they’re used. A variable’s name can be any valid identifier. A variable’s type specifies what kind of information is stored at that location in memory and how much space should be set aside to store that value. Like other statements, declaration statements end with a semicolon (;).

### Type int

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, \n). 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).

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

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

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

### Reading a Value into Variable number1

Line 16

``number1 = Convert.ToInt32( 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 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.

### Possible Erroneous User 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 app, if the user types a noninteger value, a runtime logic error called an exception will occur and the app will terminate. C# offers a technology called exception handling that will help you make your apps more robust by enabling them to handle exceptions and continue executing. 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.

### Assigning a Value to a Variable

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. Everything to the right of the assignment operator, =, is always evaluated before the assignment is performed.

### Prompting the User for Input and Reading a Value into Variable number2

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.

### Summing the 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.” 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.

### Displaying the sum

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.

### Performing Calculations in Output Statements

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 for clarity to emphasize that the value of the expression number1 + number2 is output in the position of the {0} format item.