Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

3.6 Another C# Application: Adding Integers

Our next application reads (or inputs) two integers (whole numbers, like –22, 7, 0 and 1024) typed by a user at the keyboard, computes the sum of the values and displays the result. This application keeps track of the numbers supplied by the user in 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.

Fig. 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 state the figure number, file name and purpose of the application. Line 5 begins the declaration of class Addition. Remember that the body of each class declaration starts with an opening left brace (line 6) and ends with a closing right brace (line 26).

The application begins execution with Main (lines 8–25). The left brace (line 9) marks the beginning of Main's body, and the corresponding right brace (line 25) marks the end of Main's body. Method Main is indented one level within the body of class Addition and the code in the body of Main is indented another level for readability.

Line 10 is a variable declaration statement (also called a declaration) that specifies the name and type of a variable (number1) used in this application. Variables are typically declared with a name and a type before they're used. The name of a variable can be any valid identifier. (See Section 3.2 for identifier naming requirements.) 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 . The range of values for an int is –2,147,483,648 (int.Min-Value) 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 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 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

Line 14 uses Console.Write to display the message "Enter first integer: ". This message is a prompt—it directs the user to take a specific action. Line 16 first 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. Chapter 13, Exception Handling, discusses how to make your applications more robust by enabling them to handle such errors and continue executing.

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.

Line 18 prompts the user to enter the second integer. Line 20 reads a second integer and assigns it to the variable number2.

Line 22 calculates the sum of number1 and number2 and assigns the result to variable sum. In the preceding statement, 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 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 ) );

  • + Share This
  • 🔖 Save To Your Account