Custom Search

Add Two Numbers in C#


This tutorial will demonstrate how to read from the input console (console line) to answer the prompts. The prompts will need to be a integer value to add the two inputs together.

I am using the System.Console object to read from the console and then converting the string inputs into integers with the Convert.ToInt32 function (the System.Convert has many methods and ToInt32 is one of these).

  1. Start Visual Studio.
  2. On the File menu, point to New, and then click Project.
  3. In the Templates Categories pane, expand Visual C#, and then click Windows.
  4. In the Templates pane, click Console Application.
  5. Type a name for your project in the Name field.
  6. Click OK.

    The new project appears in Solution Explorer.
  7. If Program.cs is not open in the Code Editor, right-click Program.cs in Solution Explorer and then click View Code.

  8. Replace the contents of Program.cs with the following code.
The code:

using System;       // for the console object
 
class addtwonumbers
{
       public static void Main()
       {
              try 
              {
                     // output to the console
                     Console.Write("Please enter value 1 : ");
                     // readin the console input, and then convert to a integer value
                     int val1 = Convert.ToInt32(Console.ReadLine());
                     Console.Write("Please enter value 2 : ");
                     int val2 = Convert.ToInt32(Console.ReadLine());
                     // write out the answer 
                     Console.WriteLine("Answer = " + (val1 + val2));
              }
              catch (Exception e)
              {
                     // any errors. Like converting a string to a integer value
                     Console.WriteLine("Error : " + e.ToString());
              }
       }
}

save that as addtwonumbers.cs.


Once compiled  and executed(press F5 will using visual studio) the output will be:


Please enter value 1 : 50
Please enter value 2: 25
Answer = 75

1 comments:

MaHi 11 November 2011 at 01:09  

it is the same code without using try block


class addtwonumbers
{
public static void Main(string[] args)
{
int a,b,c;
System.Console.WriteLine(“Enter the value of a=”);
a=int.Parse(System.Console.ReadLine());
System.Console.WriteLine(“Enter the value of b=”);
b=int.Parse(System.Console.ReadLine());
c=a+b;
System.Console.WriteLine(“Sum is “+c);
}
}

Post a Comment

Back to TOP