Showing posts with label Array Sum and Passing. Show all posts
Showing posts with label Array Sum and Passing. Show all posts

Friday, October 22, 2021

Sum Arrays And Passing Arrays

 In this task, we perform code of Sum of Arrays And Passing Arrays through java code.

Code:

import java.util.Scanner;
public class SumArray{
  public static void main(String[] args){

       Scanner input = new Scanner(System.in);
       int size;

      // Size of Array
      System.out.print("Enter size of Array: ");
      size = input.nextInt();
      System.out.println("\n\n");

      //Declaring and creating an array of specified size
      int[] numbers = new int[size];


      //Take Array elements from user
      for(int i=0; i<size; i++){
         System.out.print("Enter value for numbers[" + i + "] = ");
         numbers[i] = input.nextInt();
         System.out.println("\n\n");
      }

      // Calling method to get sum of elements
      int sum = sumArray(numbers);  


      System.out.print("\nSum of Array Elements: " + sum);  
   
  }//main

  public static int sumArray(int[] array){
      
      //Get the size of array
      int sum = 0;

      //iterate over each element and print it
      for(int i = 0; i < array.length; ++i){
            sum = sum + array[i];
      }

    return sum;
  }
}//class

String Array and passing method in java

 In this task, we pass a method and also cover the passing String Array to the method. Code:   import java.util.Scanner; public class String...