Addition Program in Java
We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand how the + operator works. In this section, we will create Java programs that add two or more numbers.
Using Command-Line Arguments
Filename: AdditionExample1.java
Output:
Explanation: In the above example, a point to be noted that we have not initialized any number. Instead of initializing the number, we will pass the numbers as argument at the time when we specify the java command.
java AdditionExample1 8 9
The first argument will be store in the variable x and the second argument will be store in the variable y. Remember that the numbers that we have parsed as an argument in String and we cannot perform the addition. So, we need to convert these arguments in the integer by using the parseInt() method of the Integer class.
Let’s see another program.
Filename: AdditionExample2.java
Output:
The addition operation is not only confined to two operands. We can have n numbers of operands on which we can perform the addition operation. In such a scenario, we either take the help of Java for loop (iterative approach), or we choose the recursive approach. Let’s discuss the iterative approach first.
Iterative approach
The following program demonstrates how to add array elements.
Filename: AdditionExample3.java
Output:
Explanation: In the above example, we have created an array arr[] and inserted some numbers into it. We have taken another variable add and initialized it to 0. It stores the sum of numbers that array contains. We have used a Java for loop that iterate over the array and fetch the numbers. After that, we are finding the cumulative sum and storing the sum in the addvariable.
We can achieve the same result using the recursion, also.
Recursive Approach
Filename: AdditionExample4.java
Output:
Explanation: The approach is similar to the iterative one. The only difference is instead of Java-for loop, we have used the recursion for doing the iteration.
Designed by Elegant Themes | Powered by WordPress