How to perform various operations on array in java.

In this program we are going to perform various operations on array such as printing the elements  of array it’s sum maximum value and it’s position.

Before performing all these operations we have to first know what is array? 

Array is the collection of elements of same type(such as int,char,string,double..etc) which stored in continuous memory location.

Code for performing operations such as printing elements of array,sum of it’s elements,maximum value and it’s position.

import java.util.Scanner;
public class array {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n,sum=0,max=0,pos=0;
System.out .print(“Enter the size of array=”);
n=s.nextInt();
int [ ]a=new int[n];                                                           / / Declaration of array
for(int i=0;i<=a.length -1;i++)
{
a[i]=s.nextInt();                                                            / / Take values of array from user and stored in a[i]
}
System.out.print(“The outputs are=”);
for(int j=0;j<=a.length-2;j++){                                      / / loop to produce output
max=a[0];                                                                   / / Store the maximum value in max.
pos=0;                                                                       / / taking position from zero.
for(int k=1;k<=a.length-1;k++)
{
if(a[k]>max)                                                             / / condition to compare the next value to max(previous one).
{
max=a[k];                                                               / /store the maximum value in max.
pos=k;                                                                   / / store the position of maximum value.
}
}
System.out.print(a[j]+”,”);

sum=sum+a[j];                                                      / / store the sum of all elements in temp variable i.e sum.

}
sum+=a[a.length-1];
System.out.println(a[a.length-1] + “.”);
System.out.print(“\nThe sum of elements=”);
System.out.print(sum);                                        / /print the sum of all elements in array
System.out.println();
System.out.println(“max=”+max);                      / / print the maximum value
System.out.println(“pos=”+pos);                        / /print the position of maximum value.

}

}

 

2 thoughts on “How to perform various operations on array in java.”

Leave a Reply