❮ Previous Next ❯

One-Dimensional Array

The array taking one subscript is known as one-dimensional array.


Declaration

The general form   to declare an array is:
Type[] var-name;
here type declares the element type of the array. The element type determines the data type of each element. For example, the following declares an array named silan will the type array of int :
Example;
int[] arr;
here arr is an array(variable), but no array actually exists. That means the value of array is set to null which represents an array having no value. So java concept is saying that to link arr with an actual, physical array of integers, you must allocate using new operator(special operator for allocating memory) and assign it to arr. The general form of new for allocating one-dimensional array is :
Syntax:
array-name=new type[size];
where,

Example;

int[]=arr=new int[5];
when this statement is executed, 20(4bytes*5) of memory will be allocated dynamically named as arr having capability to contain maximum 5 integer data items.
Array Initialization
When the values are assigned to an array is known as array initialization,
Example;
int[] arr={10,20,30,40,50};
here, arr[0]=10;
          arr[1]=20;
          arr[2]=30;
          arr[3]=40;
          arr[4]=50;


one dimensional array

Let’s see a simple array program:
Average.java
import java.util.Scanner;
class Average
{
public static void main(String[] args)
{
int sum=0, size;
double avg;
Scanner s=new Scanner(System.in);
System.out.println("enter the size of the array:");
size=s.nextInt( );
int a[]=new int[size];
System.out.println("enter the elements the array elements:");
for(int i=0;i<a.length;i++)
{
a[i]=s.nextInt( );
sum=sum+a[i];
}
avg=(double)(sum/a.length);
System.out.println("sum is: "+sum);
System.out.println("average is: "+avg);
}
}
Output
enter the size of the array
5
enter the array elements
1
2
3
4
5
sum is 15
average is 3.0



❮ Previous Next ❯

Follow Us




  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved