Another Simple Program: Adding Integers Our next application inputs two integers (whole numbers) typed by a user at the keyboard, compute...
Another Simple Program: Adding Integers
Our next application 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.
Addition C# Programming
1// Addition.
2 // An addition program.
3
4 using System;
5
6 class Addition
7 {
8 static void Main( string[] args )
9 {
10 string firstNumber, // first string entered by user
11 secondNumber; // second string entered by user
12
13 int number1, // first number to add
14 number2, // second number to add
15 sum; // sum of number1 and number2
16
17 // prompt for and read first number from user as string
18 Console.Write( "Please enter the first integer: " );
19 firstNumber = Console.ReadLine();
20
21 // read second number from user as string
22 Console.Write( "\nPlease enter the second integer: " );
23 secondNumber = Console.ReadLine();
24
25 // convert numbers from type string to type int
26 number1 = Int32.Parse( firstNumber );
27 number2 = Int32.Parse( secondNumber );
28
29 // add numbers
30 sum = number1 + number2;
31
32 // display results
33 Console.WriteLine( "\nThe sum is {0}.", sum );
34
35 } // end method Main
36
37 } // end class Addition
output:-
Please enter the first integer: 45
Please enter the second integer: 72
The sum is 117.
No comments