Wednesday, February 14, 2018

Arrays in java



Arrays: - 

    Arrays are linear data Structure. Used to Store Similar Type Of elements/ values in continuous memory location.                                                                                                                                  Array is index based, first element of the array is stored at 0 index.                                                                                                          

Types of Array: -

1:- Single dimensional Array
2:- Multidimensional Array

Syntax of Single Dimensional Array :- 

DataType   Ref.Var [ ]  = new DataType[Size]  

Example:- 

1:-

public class EX1 {
public static void main(String[] args) {
   int arr []= new int [3];

  int arr [0]=5;
  int arr [1]=6;
  int arr [2]=8;

System.out.println(arr[0]+” ”+arr[1]+” “+arr[2]);

}
  }

2:-

public class AR2 {


public static void main(String[] args) {

   int arr []= {1,2,5,6,8};
   for (int i=0;i<arr.length;i++){
   System.out.println(arr[i]);
 }   
   }
  }

 Syntax of MultiDimensional Array :- 

 DataType   Ref.Var [ ] [ ]  = new DataType [Size]   [Size] 


Example:-

  import java.util.Scanner;
  public class AR2 {
  public static void main(String[] args) {
   Scanner na = new Scanner(System.in);
  System.out.println("Enter Element:- ")
     int arr [] [] = new int [3][3];

   for (int i=0;i<3;i++){
       for (int j=0;j<3;j++){
          arr[i][j]=na.nextInt();
       }
   }

   for (int i=0;i<3;i++){
       for (int j=0;j<3;j++){
          System.out.print(arr[i][j]+"\t");
       }
       System.out.println( );

   } 
  } 
  }








0 comments:

Post a Comment