C# PROGRAM TO ADD TWO NUMBERS / INTEGERS USING METHOD
Program :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
using System; namespace AddTwoNumsUsingFunc { class Program { static void Main(string[] args) { int x, y, result = 0; Console.WriteLine("*** www.ProgrammingPosts.blogspot.com *** "); Console.WriteLine(">>>C# PROGRAM TO ADD TWO NUMBERS USING METHOD <<< "); Console.Write("\n Enter the first number to be added: "); x = Convert.ToInt32(Console.ReadLine()); // taking x value from keyboard Console.Write("\n Enter the second number to be added: "); y = Convert.ToInt32(Console.ReadLine()); // taking y value from keyboard result = Sum(x, y); //calling function Console.WriteLine("\n The sum of two numbers is: {0} ", result); /*printing the sum.*/ Console.ReadLine(); } static public int Sum(int a, int b) { int result = a + b; return result; } } } |
Sample Output :
Explanation :
In the above program the method static public int Add(int a,int b) , we are declaring method Sum method as Static because Main method is static and we are calling Sum method in Main method without creating object.
C# is a Object Oriented Programming Language. And in OOP language, a method can be called using object of a class. And if we want to call method without creating object, we have to declare it as static to Call it with its class name.