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.
Step 2-> Declare a Method which is declared with static modifiers and a "int" return type.
- private static int Get_Set() {
- return x;
- }
Step 3-> Create Main() class.
- static void Main(String[] a)
- {
-
- }
Now, our program modules are ready. We can now write our logic inside that.
Step 4-> Inside Main() , write the following:
- 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.
- x = Convert.ToInt32(Console.ReadLine());
Step 6-> Display the value of x variable.
- Console.WriteLine("Sum of ttwo nos is - "+x);
Step 7-> End
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();
- }
- }
I hope this will help you.