You are on page 1of 2

Array in java

Example program1

Write a program that inputs size of one dimensional array from user. Input numbers in array and
display those numbers. Also display the sum and product of array elements

import java.util.Scanner;
class MyArray
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int size, sum=0, product=1;
System.out.println("enter the size of array");
size=in.nextInt();
int arr[]=new int[size];
for(int i=0;i<size;i++)
{
System.out.println("enter the array element");
arr[i]=in.nextInt();
}
for(int i=0;i<size;i++)
{
sum=sum+arr[i];
product=product*arr[i];
System.out.println("array element="+arr[i]);
}
System.out.println("the sum of array element="+sum);
System.out.println("the product of array element="+product);
}
}

Example programs of 2-D Array

Program-1:
Write a program that declares integer type 2-D array. The program should take number of rows and
columns of 2-D array from user. Input the array elements and then display them.
import java.util.Scanner;
class TwoDArray
{
public static void main(String[] args)
{
Scanner a=new Scanner(System.in);
int row, col;
System.out.println("enter number of rows of TwoDarray");
row=a.nextInt();
System.out.println("enter number of columns of TwoDarray");
col=a.nextInt();
int[][] myArray=new int[row][col];
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
System.out.println("enter array element");
myArray[i][j]=a.nextInt();
}
}
System.out.println("the array elements are given bellow:");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
System.out.print(myArray[i][j]);
}
System.out.println("\n");
}
}
}

You might also like