Sunday 7 March 2010

Simple C# - Add Two Numbers and Print out its Sum

C# Code-Add Two Numbers and Print out its Sum

The following is the code using C# to Add two numbers and print out its Sum,
The code below consists of integer(int) data type with values specified.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class sum
{
static void Main(string[] args)
{
// defining the datatype int a and int b.

int a = 5;// datatype int a(integer) with value 5.

int b = 3;// similarly int b(integer) with value 3.

// now addition of a and b and printing out its sum.

Console.WriteLine("The Sum Is :{0}", a + b);

}
}
}

But if the programmer wishes to input values of his own or technical term userdefined values the code is as follows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class sum
{
static void Main(string[] args)
{
int a, b;
Console.WriteLine(" Enter the values to be added");

// provide user defined inputs

a=Convert.ToInt32(Console.ReadLine());
b=Convert.ToInt32(Console.ReadLine());

// print out the sum
Console.WriteLine("The Sum Is :{0}", a + b);

}
}
}

similarly other mathematical operations can be performed ,eg: subtraction,multiplication etc.

No comments:

Post a Comment