Java Lab 3
Java Lab 3
Java Lab 3
Arrays
1. Program to print the given one dimentional array and the sorted array using enhanced for loop.
class Demo {
public static void main(String args[]) {
int A[] = { 5, 8, 2, 9, 1, 4, 7, 56, 15 };
System.out.println("The given array is ");
//for (int i = 0; i < A.length; i++) {
for (int i : A) {
System.out.print(i);
System.out.print("\t");
}
Arrays.sort(A);
System.out.println();
System.out.println("The sorted array is");
//for (int i = 0; i < A.length; i++) {
for (int i: A) {
System.out.print(i);
System.out.print("\t");
}
}
}
2. Program to print Reverse of an Array
import java.io.*;
class RevArray {
public static void main(String S[]) throws IOException {
int a[] = new int[5];
int i, temp;
DataInputStream ins = new DataInputStream(System.in);
System.out.println("Enter 5 elements");
for (i = 0; i < 5; i++) {
a[i] = Integer.parseInt(ins.readLine());
}
System.out.println("The given Array is");
for (int j:a)
System.out.print(j + " ");
System.out.println();
for (i = 0; i <2; i++) {
temp = a[i];
a[i] = a[4 - i];
a[4 - i] = temp;
}
System.out.println("The reverse of the given Array is");
for (int k:a)
System.out.print(k + " ");
}
}
3. Program for Passing Arrays in methods
public class PassingArray {
public static void main(String args[]) {
int kk[]={1,2,3,4,5};
System.out.println("The original array is");
for (int i:kk)
{
DataInputStream ins = new DataInputStream(System.in);
c[i][j] = Integer.parseInt(ins.readLine());
}
}
System.out.println("result");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
for (k = 0; k < 2; k++) {
d[i][j] += (b[i][k] * c[k][j]);
}
System.out.print(d[i][j] + " ");
d[i][j] = 0;
}
System.out.println("");
}
}
}
5. Program to delete an element from array
import java.io.*;
class DelArray {
public static void main(String arg[]) throws IOException {
int a[] = new int[10];
DataInputStream ins = new DataInputStream(System.in);
int i, n = 0, q = 0;
int ctr = 0;
System.out.print("Enter no. of elements ");
Best of luck
Advanced Programming Using Java - Prepared by: Krishna Kumari Ganga