One Dimensional Array

One Dimensional Array – Using Standard Method


class OnedimensionalStandard
{
public static void main(String args[])
{    
int[] a=new int[3];//declaration  
a[0]=10;//initialization  
a[1]=20;  
a[2]=30;  
//printing array  
System.out.println("One dimensional array elements are");    
System.out.println(a[0]);    
System.out.println(a[1]);    
System.out.println(a[2]);    
}
}


Using Scanner

  1. Read the array length as sc.nextInt() and store it in the variable len and declare an array int[len].
2) To store elements in to the array for i=0 to i<length of an array read the element using sc.nextInt() and store the element at the index a[i].
3) Display the elements of an array for loop iterates from i=0 to i<length of an array print the array element a[i].
class OnedimensionalScanner
{
   public static void main(String args[])
   {    
int len;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Array length : ");
len=sc.nextInt();
int a[]=new int[len];//declaration    
System.out.print("Enter " + len + " Element to Store in Array :\n");
        for(int i=0; i<len; i++)
        {
           a[i] = sc.nextInt();
        }  
        System.out.print("Elements in Array are :\n");
        for(int i=0; i<len; i++)
        {
           System.out.print(a[i] + "  ");
        }  
   }
}

Using For Loop – One Dimensional Array


1
2
3
4
5
6
7
8
9
10
11
12
class OnedimensionalLoop
{
public static void main(String args[])
{    
   int a[]={10,20,30,40,50};//declaration and initialization     
   System.out.println("One dimensional array elements are :\n");    
   for(int i=0;i<a.length;i++)  
   {
System.out.println("a["+i+"]:"+a[i]);    
   }
}
}


Using String
  1. We declared one-dimensional string array with the elements strings.
2) To print strings from the string array. for i=0 to i<length of the string print string which is at the index str[i].

class OneDimensionString
{
    public static void main(String[] args)
    {
        //declare and initialize one dimension array
        String[] str = new String[]{"one", "two", "three", "four"};
        System.out.println("These are elements of one Dimensional array.");
        for (int i = 0; i < str.length; i++)
{
            System.err.println(str[i] + "   ");
        }
   }
}

Comments