Sum Of Two Numbers Using a Single Variable

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.

  1. static int x = 0;   
Step 2-> Declare a Method  which is declared with static modifiers and a "int" return type.
  1. private static int Get_Set() {  
  2.     return x;  
  3. }  
Step 3-> Create Main() class.
  1. static void Main(String[] a)  
  2. {  
  3.   
  4. }  
Now, our program modules are ready. We can now write our logic inside that.

Step 4-> Inside Main() , write the following:
  1. x = Get_Set() + Get_Set();  
This will call the Get_Set() twice and store the value in x.

Step 5-> Inside Get_Set(), we need to take input from user. 
  1. x = Convert.ToInt32(Console.ReadLine());   
Step 6-> Display the value of x variable.
  1. Console.WriteLine("Sum of ttwo nos is - "+x);  
Step 7-> End

Now , our program will look like the below code: 
  1. class Program {  
  2.     static int x = 0;  
  3.     private static int Get_Set() {  
  4.         Console.WriteLine("Enter numbers");  
  5.         x = Convert.ToInt32(Console.ReadLine());  
  6.         return x;  
  7.     }  
  8.     static void Main(String[] a) {  
  9.         x = Get_Set() + Get_Set();  
  10.         Console.WriteLine("Sum of ttwo nos is - " + x);  
  11.         Console.ReadKey();  
  12.     }  
  13. }  
I hope this will help you.