Arrays
· An array is an object that is a named set of variables of the same type. Each variable in the array is called an array element.
· All elements in the array must be of the same data type
· Arrays in Java are objects and can be of primitive data types or reference variable type
To reference a particular element in an array, you use the array name combined with an integer value of type int, called an index.
int marks[6]=new int[]{50,80,85,95.80};
Example marks [4]
Here marks is an array and [4] indicates the 4 element of array
50 80 85 90 95 80
marks[0] marks[1] marks[2] marks[3] marks[4] marks[5]
The index value does not need to be an integer literal. It can be any expression that results in a value of type int that is equal to or greater than zero.
arr[(low+high)/2]
An Array index starts with 0 and ends with the size-1
Declaration of the array
int[] marks=new int[5];
String[] names=new String[5 ];
Student[] name=new Student[5];
Note: Array size shouldn't be negative number, if specify negative number it leads to the runtime exception. java.lang.NegativeArraySizeException
Initilization of the array
int[] numbers=new int[]{1,2,3,4,5,6}
Here the integer array is created with numbers and size with 6 and array will be initilized with 1,2,3,4,5,6 values.
int[] num={10,20,30,40,60,70};
Here the integer array is created with name num and initialized with 10,20,30,40,60,70
Length of an array
The number of elements contains in the array can be find using length. Here length is field
Example:
int[] a=new int[]{1,5,10,15};
int len=a.length (which returns the length is 4 )
Storing Array elements
We can store the elements into the array by using index or by running the for loop
Example
int[] a=new int[3]
a[0]=10;
a[1]=20;
a[2]=30;
(or)
for(int i=0;i<a.length;i++){
a[i]=i;
}
ArrayElements can be accessed:
int a[]=new int[3];
System.out.print(a[0]);
System.out.print(a[1]);
System.out.print(a[2]);
(or)
for(int i=0;i<a.length;i++){
System.out.print(a[i]);
}
Array elements can be processed by using the for-each loops
for(int i : a)
System.out.print(i);
In java Arrays are created dynamic memory, that is allocated at runtime by the JVM.
int[] a;
Here just we created reference variable a and its not holding any object later we can initialize this a reference variable with integer array object.
int[] a=new int[]{10,20,30,40};
int[] b=a;
int[] input[]=new int[]{1,2,3,4};
int[] output=new int[4];
int[] temp;
When you want to switch the array referenced by output array to be the new input array, we can write
temp=input;
input=output;
output=temp;
Example:
public class ArrayDemo {
public static void main(String[] args) {
int[] input=new int[]{1,2,3,4};
int[] output=new int[4];
int[] temp;
for(int i=0;i<input.length;i++){
output[i]=input[i]*5;
}
temp=input;
input=output;
output=temp;
for(int i=0;i<input.length;i++)
System.out.println(output[i]);
}
}
Multidimensional Arrays:
Multidimensional arrays are implemented as arrays of arrays.
Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name.
Declaration
int a[][]=new int[3][3]
Initialization of the multidimensional array can be done in this way
int a[][]=new int[][]{ {2,3,4},{3,4,5},{4,5,6}};
Anonymous Arrays
Sometimes we can declare an array without name also such type of arrays are called anonymous arrays. Normally these arrays will be created for temporary usage.
/* program to find the biggest of the four numbers*/
Example:
import java.util.Scanner;
public class ArraysDemo {
public static void main(String[] args) {
int a,b,c,d,big;
System.out.println("Enter the a,b,c");
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
d=sc.nextInt();
big=biggestElement(new int[]{a,b,c,d});
System.out.println("The biggest element is : "+big);
}
private static int biggestElement(int[] a) {
private static int biggestElement(int[] a) {
int big;
big=a[0];
for(int i=1;i<a.length;i++){
if(a[i]>big)
big=a[i];
}
return big;
}
}
/*Program to Accept N number from the user,create an array with size N and accpt the numbers and storing into array. Find the biggest and smallest elements int the given array */
package com.jsl.array;
import java.util.Scanner;
public class BiggestAndSmallest {
public static void main(String[] args) {
int big,small,array[];
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of the array ");
/* Creating new Array with the user given size */
array=new int[sc.nextInt()];
for(int i=0;i<array.length;i++){
System.out.println("Enter the element "+(i+1)+" value ");
array[i]=sc.nextInt();
}
/* initilizing big and small elements with the initial values */
big=array[0];
small=array[0];
/* Accessing array elements by using for-each loop */
for(int ele:array){
if(ele>big)
big=ele;
if(ele<small)
small=ele;
}
System.out.println("The biggest element is :"+big);
System.out.println("The smallest element is :"+small);
}
}
/*program to search the element in the given array */
package com.jsl.array;
import java.util.Scanner;
public class SearchingElement {
public static void main(String[] args) {
int[] arr=new int[10];
int ele;
Scanner sc=new Scanner(System.in);
for(int i=0;i<arr.length;i++){
System.out.print("Enter the value of "+(i+1)+" value ");
arr[i]=sc.nextInt(); }
System.out.println("Enter the element to search ");
ele=sc.nextInt();
int pos=serarchElement(arr,ele);
if(pos==-1)
System.out.println("The element is not found ");
else
System.out.println("The element is found at loaction : " + pos);
}
private static int serarchElement(int[] arr, int ele) {
int pos=-1;
for(int i=0;i<arr.length;i++){
if(arr[i]==ele){
pos=i;
break;
}
}
return pos;
}
}
/*Program to find the result,grade,average marks of given students marks list*/
package com.jsl.arrays;
public class ArrayDemo {
public static void main(String[] args) {
int marks[][]=new int[][]{
{23,45,56,34},
{45,23,67,78},
{78, 89,90,80},
{53,45,78,61}
};
for(int i=0;i<marks.length;i++){
int sum=0;
float aveg=0.0f;
String result="Pass";
String grade=" ";
System.out.println("\n The student "+(i+1)+" Details are \n");
System.out.println("Sub1\tSub2\tSub3\t Sub4 \t Total\t Average\tResult\tGrade");
for(int j=0;j<marks[i].length;j++){
System.out.print(" "+marks[i][j]+"\t");
if(marks[i][j]<35)
result="Fail";
sum=sum+marks[i][j];
}
aveg=sum/4;
if(result.equals("Pass")){
if(aveg>=70)
grade="Distinction";
else if(aveg>=60 && aveg<70)
grade="First Class";
else if(aveg<60)
grade="Second Class";
else
grade="Third Class";
}
else{
grade=" Sorry Study Well";
}
System.out.print(sum+" \t "+aveg+"\t \t"+result+"\t "+grade);
System.out.println("\n________________________________________");
}
}
}
/* Binary Search Examples */
package com.jsl.core.array;
import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
int size;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size");
size = sc.nextInt();
int a[] = new int[size];
for (int i = 0; i < a.length; i++) {
System.out.println("Enter the no " + (i + 1) + " Value");
int no = sc.nextInt();
a[i] = no;
}
int s[] = sort(a);
System.out.println("Enter the key to search ");
int key = sc.nextInt();
if (getElement(s, key) == -1) {
System.out.println("The element is not found");
} else {
System.out.println("The element is found");
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1]) {
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
return a;
}
public static int getElement(int a[], int key) {
int low = 0, high = a.length - 1, mid, pos = -1;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) {
pos = mid;
return pos;
} else if (key > a[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}
private int pid;
this.pid = pid;
System.out.println("The Product Details are :");
for (Product pro : product) {
System.out.print(pro.pid + "\t" + pro.pname + "\t" + pro.price);
public class ArraysWithReference {
public static void main(String[] args) {
Product p = new Product();
private int a[];
public ArrayContainer() {
a=new int[2];
public void addElement(int ele){
if(icount<a.length){
a[icount++]=ele;
}else{
public void display(){
if(a.length==0 ||icount==0){
System.out.println("There is no elements");
for(int i=0;i<icount;i++){
System.out.println(a[i]);
ArrayContainer obj=new ArrayContainer();
for(;;){
if(ch==1){
System.out.println("Enter the elment to add");
}else if(ch==2){
obj.display();
}else{
break;
/*Java Example with Arrays */
package com.jsl.core.array;
public class ArrayDemo {
public static void main(String[] args) {
int size;
System.out.print("[");
System.out.print(a[i] + " ");
int key = sc.nextInt();
if (getElement(a, key) == -1) {
int big = a[0];
if (big < a[i])
if (small > a[i])
/* Binary Search Examples */
package com.jsl.core.array;
import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
int size;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size");
size = sc.nextInt();
int a[] = new int[size];
for (int i = 0; i < a.length; i++) {
System.out.println("Enter the no " + (i + 1) + " Value");
int no = sc.nextInt();
a[i] = no;
}
int s[] = sort(a);
System.out.println("Enter the key to search ");
int key = sc.nextInt();
if (getElement(s, key) == -1) {
System.out.println("The element is not found");
} else {
System.out.println("The element is found");
}
}
private static int[] sort(int[] a) {for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1]) {
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
return a;
}
public static int getElement(int a[], int key) {
int low = 0, high = a.length - 1, mid, pos = -1;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) {
pos = mid;
return pos;
} else if (key > a[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}
/* Arrays with reference Type */
package com.jsl.core.array;
class Product {
private int pid;
private String pname;
private double price;
private Product product[];
private Product(int pid, String pname, double price) {
this.pid = pid;
this.pname = pname;
this.price = price;
}
public Product() {
product = new Product[] { new Product(1001, "Laptop", 45000),
new Product(1002, "DVDROM", 4000),
new Product(1003, "Mouse", 500),
new Product(1005, "PenDriver", 450)
};
};
}
public void productInfo() {
System.out.println("The Product Details are :");
System.out.println("-----------------------------------");
for (Product pro : product) {
System.out.print(pro.pid + "\t" + pro.pname + "\t" + pro.price);
System.out.println("\n-----------------------------------------\n");
}
}
}
public class ArraysWithReference {
public static void main(String[] args) {
Product p = new Product();
p.productInfo();
}
}
/* Dynamic growing array Example */
package com.jsl.core.array;
import java.util.Scanner;
class ArrayContainer{
private int a[];
private int icount=0;
private int count=0;
public ArrayContainer() {
a=new int[2];
}
public void addElement(int ele){
if(icount<a.length){
a[icount++]=ele;
}else{
int b[]=new int[a.length+a.length];
System.arraycopy(a, 0, b, 0, a.length);
b[icount++]=ele;
a=b;
}
}
public void display(){
if(a.length==0 ||icount==0){
System.out.println("There is no elements");
}
if(count<a.length){
for(int i=0;i<icount;i++){
System.out.println(a[i]);
}
}
}
}
public class ArraySwaping {
public static void main(String[] args) {
ArrayContainer obj=new ArrayContainer();
for(;;){
System.out.println("Enter the choice 1.add 2.display 3.exit");
Scanner sc=new Scanner(System.in);
int ch=sc.nextInt();
if(ch==1){
System.out.println("Enter the elment to add");
int ele=sc.nextInt();
obj.addElement(ele);
}else if(ch==2){
obj.display();
}else{
break;
}
}
}
}
package com.jsl.core.array;
import java.util.Scanner;
public class ArrayDemo {
public static void main(String[] args) {
int size;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size");
size = sc.nextInt();
int a[] = new int[size];
for (int i = 0; i < a.length; i++) {
System.out.println("Enter the no " + (i + 1) + " Value");
int no = sc.nextInt();
a[i] = no;
}
System.out.println("The Array elements are :");
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.print("]");
System.out.println("The biggest element is :" + biggest(a));
System.out.println("The biggest element is :" + smallest(a));
System.out.println("The elements sum is :" + sumOfArrayElements(a));
System.out.println("Enter the key to search ");
int key = sc.nextInt();
if (getElement(a, key) == -1) {
System.out.println("The element is not found");
} else {
System.out.println("The element is found");
}
}
public static int biggest(int a[]) {
int big = a[0];
for (int i = 1; i < a.length; i++) {
if (big < a[i])
big = a[i];
}
return big;
}
public static int smallest(int a[]) {
int small = a[0];
for (int i = 1; i < a.length; i++) {
if (small > a[i])
small = a[i];
}
return small;
}
public static int getElement(int a[], int key) {
int pos = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] == key) {
pos = i;
break;
}
}
return pos;
}
public static int sumOfArrayElements(int a[]) {
int sum = 0;
for (int ele : a)
sum = sum + ele;
return sum;
}
}
Task:
1. Write a program to accept N value and create the array size N. Find the sum of elements in the array.
2. Write a program to accept N value and create the array size N. Find the biggest and the smallest elements in the array
3. Write a program that allows you to create an integer array of 18 elements with the following values: int A[]={3,2,4,5,6,4,5,7,3,2,3,4,7,2,0,0,0,}. The program computes the sum of element 0 to 14 and stores it at element 15, computes the average and stores it at element 16 and identifies the smallest value from the array and stores it at element 17.
4. Write a program that accepts two numbers in the range from 1 to 50 from the user. It then compares these numbers against the single dimension array of 5 integer elements ranging in value from 1 to 50. The program displays the message success if the two inputted values are found in the array element. Otherwise print it as fail.
5. Write a program that accepts M x N matrix and
1. Find the sum of elements in the matrix
2. Biggest element in the matrix
3. Diagonal sum of the matrix
4. Transpose of the given matrix
No comments:
Post a Comment