Array:
- An array is a collection of similar data items, that are stored under a common name.
- It is denoted by index or subscript enclosed in square brackets, i.e. [].
- Array value is starting with 0.
It is similar to the table structure.
It is used to reduce memory space.
- Single dimensional arrays
- Multidimensional arrays
- The collection of items can be stored under one variable name using only one subscript, such a variable is called ‘one-dimensional array or single dimensional array’.
Declaring array:
Data_type array_name[];
Allocate memory:
Array_name = new data_type[size];
Example:
int a[];
a=new int[3];//There are three value can store
here.
Initialize array:
Data_type []={values};
Example:
int a[]={5,8,7};
Data_type array_name[];
Allocate memory:
Array_name = new data_type[size];
Example:
int a[];
a=new int[3];//There are three value can store
here.
Initialize array:
Data_type []={values};
Example:
int a[]={5,8,7};
import java.util.Scanner;
public class One_Dimenstional_Array {
public
static void main(String args[])
{
int
a[];
a=new
int[3];
Scanner sc = new Scanner(System.in);
System.out.println("Enter two number : ");
a[0]=sc.nextInt();
a[1]=sc.nextInt();
a[2]=a[0]+a[1];
System.out.println("Additions of two number is : "+a[2]);
}
}
import java.util.Scanner;
public class One_Dimenstional_Array {
public
static void main(String args[])
{
int
a[];
a=new
int[3];
Scanner sc = new Scanner(System.in);
System.out.println("Enter two number : ");
a[0]=sc.nextInt();
a[1]=sc.nextInt();
a[2]=a[0]+a[1];
System.out.println("Additions of two number is : "+a[2]);
}
}
- Multidimensional arrays are used in a situation where a table of value needs to be stored in an array.
Data_type array_variable [row size][column size];
import java.util.Scanner;
public class Two_Dimensional_array {
public
static void main(String args[]) {
int
std[][] = new int[4][2];
int
i, j;
for
(i = 0; i < std.length - 1; i++) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter " + i + " student roll number
and mark: ");
std[i][0] = sc.nextInt();
std[i][1] = sc.nextInt();
}
for
(i = 0; i < std.length - 1; i++) {
System.out.println("Student " + i + " roll number "
+ std[i][0] +
" and mark " + std[i][1]);
}
}
}
import java.util.Scanner;
public class Two_Dimensional_array {
public
static void main(String args[]) {
int
std[][] = new int[4][2];
int
i, j;
for
(i = 0; i < std.length - 1; i++) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter " + i + " student roll number
and mark: ");
std[i][0] = sc.nextInt();
std[i][1] = sc.nextInt();
}
for
(i = 0; i < std.length - 1; i++) {
System.out.println("Student " + i + " roll number " + std[i][0] +
" and mark " + std[i][1]);
}
}
}
No comments:
Post a Comment