In this article, we will learn how to add two numbers using a single variable. A sample code is written below that is using function call, and assigning the value to a single variable, and then it is performing an arithmetic operation on that.
This sample code will help you to learn how we can begin to learn to develop optimized code. We will learn how to calculate the sum of two numbers using a single variable here.
Step 1 -> Declare a global variable in your class.
- static int x = 0;
- private static int Get_Set() {
- return x;
- }
- static void Main(String[] a)
- {
- }
Step 4-> Inside Main() , write the following:
- x = Get_Set() + Get_Set();
Step 5-> Inside Get_Set(), we need to take input from user.
- x = Convert.ToInt32(Console.ReadLine());
- Console.WriteLine("Sum of ttwo nos is - "+x);
Now , our program will look like the below code:
- class Program {
- static int x = 0;
- private static int Get_Set() {
- Console.WriteLine("Enter numbers");
- x = Convert.ToInt32(Console.ReadLine());
- return x;
- }
- static void Main(String[] a) {
- x = Get_Set() + Get_Set();
- Console.WriteLine("Sum of ttwo nos is - " + x);
- Console.ReadKey();
- }
- }

Join the conversation! Your thoughts help the community grow.