Print Summation of Numbers in Java



Suppose you are given a set of numbers, your task is to write a Java program to print their summation. To find summation, you need to add all the given numbers with the help of addition operator. In Java, a set of numbers can be represented by an array.

Let's understand the problem with an example ?

Example Scenario:

Input: number_set = 34, 11, 78, 40, 66, 48;
Output: summation = 277 

Sum of all the numbers is 277 as 34 + 11 + 78 + 40 + 66 + 48 = 277.

Using Iteration

The most simplest way of printing summation is by iterating over the set of numbers by using either for loop or while loop and adding them together.

Example

In this Java program, we use for loop to print summation of numbers.

public class newarr {
   public static void main(String[] args) {
      int[] arrayofNum = {23, 101, 58, 34, 76, 48};
      int summ = 0;
      System.out.println("Given numbers are:: ");
      for(int i = 0; i < arrayofNum.length; i++) {
          System.out.print(arrayofNum[i] + " ");
      }
      
      // adding Numbers
      for (int m = 0; m < arrayofNum.length; m++) {
          summ += arrayofNum[m];    
      }
      
      // printing the sum
      System.out.println("\nSummation of given numbers is:: " + summ);
   }
}

On running, this code will produce the following result ?

Given numbers are:: 
23 101 58 34 76 48 
Summation of given numbers is:: 340

Using recursion

The another way of printing summation of numbers is by recursion, which is a programming practice where a function call itself until it finds the solution.

Example

In this Java program, the summation() is a recursive function. It call itself within its body and add the numbers during each call.

public class newarr {
   public static void main(String[] args) {
      int[] arrayofNum = {19, 21, 58, 34, 76, 48};
      System.out.println("Given numbers are:: ");
      for (int num : arrayofNum) {
          System.out.print(num + " ");
      }
      
      // method call
      int summ = summation(arrayofNum, arrayofNum.length);
      
      // Printing the sum
      System.out.println("\nSummation of given numbers is:: " + summ);
   }
   
   // recursive method 
   public static int summation(int[] array, int n) {
      if (n <= 0) {
         return 0;
      }
      return array[n - 1] + summation(array, n - 1);
   }
}

When you execute the above code, it will give the following result ?

Given numbers are:: 
19 21 58 34 76 48
Summation of given numbers is:: 256
Updated on: 2024-09-30T15:46:44+05:30

726 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements