Object Oriented Programming: Unit I: Introduction to OOP and Java

Arrays Example Java Programs

Arrays Example Programs Write a Java program to perform matrix addition, subtraction and multiplication.

Arrays Example Programs

Ex. 1.13.1 : Write a Java program to perform matrix addition, subtraction and multiplication.

Java Program[Matrix.java]

/*

This is a Java program which performs matrix operations

*/

class Matrix

{

public static void main(String args[])

throws java.io.IOException

{

int a[][]={

{10,20,30},

{40,50,60},

{70,80,90}

};

int b[ ][ ] = {

{1,2,3},

{4,5,6},

{7,8,9}

};

int c[ ][ ]=new int [3][3];

char choice;

System.out.println("\n Main Menu");

System.out.println("1. Addition");

System.out.println("2. Subtraction");

System.out.println("3. Multiplication");

System.out.println("Enter your choice");

choice == (char)System.in.read();

switch(choice)

{

case '1':for(int i=0;i<3;i++)

{

for(int j=0;j<3;j++)

{

c[i][j]=a[i][j]+b[i][j];

}

}

System.out.println("The Addition is...");

for(int i=0;i<3;i++)

{

for(int j=0;j<3;j++)

{

System.out.print(" "+c[i][j]);

}

System.out.println();

}

break;

case '2':for(int i=0;i<3;i++)

{

for(int j=0;j<3;j++)

{

c[i][j]=a[i][j]-b[i][j];

}

}

System.out.println("The Subtraction is...");

for(int i=0;i<3;i++)

{

for(int j=0;j<3;j++)

{

System.out.print(" "+c[i][j]);

}

System.out.println();

}

break;

case '3':for(int i=0;i<3;i++)

{

for(int j=0;j<3;j++)

{

c[i][j]=0;

for(int k=0;k<3;k++)

{

c[i][j]=c[i][j]+a[i][k]*b[k][j];

}

}

}

System.out.println("The Multiplication is...");

for(int i=0;i<3;i++)

{

for(int j=0;j<3;j++)

{

System.out.print(" "+c[i][j]);

}

System.out.println();

}

break;

}

}

}

Output (Run1)

Main Menu

1. Addition

2. Subtraction

3. Multiplication

Enter your choice

1

The Addition is...

11 22 33

44 55 66

77 88 99

Output (Run2)

Main Menu

1. Addition

2. Subtraction

3. Multiplication

Enter your choice

2

The Subtraction is...

9 18 27

36 45 54

63 72 81

Output (Run3)

Main Menu

1. Addition

2. Subtraction

3. Multiplication

Enter your choice

3

The Multiplication is...

300 360 420

660 810 960

1020 1260 1500

Ex. 1.13.2: Write a Java Program to implement Linear Search.

Sol. :

public class LinearSearch

{

public static void main(String args[]) {

int[] a={1,5,-2,8,7,11,40,32};

System.out.println("The elementis at location "+Find(a,7));

System.out.println("The element is at location "+Find(a,11));

}

public static int Find(int[] a,int key)

{

int i;

for(i=0;i<a.length;i++)

{

if(a[i]==key)

return i+1;

}

return -1;

}

}

Output

The element is at location 5

The element is at location 6

arraycopy Command

Using array copy we can copy entire an to another array. The arraycopy command is applicable to one dimensional array. The syntax of arraycopy command is

public static void arraycopy(Object src,

int srcPos,

Object dest,

int destPos,

int length)

But it can be extended to copy two dimensional array as well. Following example illustrates this idea.

Ex. 1.13.3: Write a program for transposition of matrix using arraycopy command.

Sol.:

Java Program [ArrayTranspose.java]

public class ArrayTranspose

{

public static void main(String args[])

{

int A[][]={{1,2,3},{4,5,6}, {7,8,9}};

int B[][] = new int[3][3];

int i,j,From[],Toll;

From = new int[9];

To = new int[9];

int k=0;

System.out.println("The original matrix is...");

for(i=0;i<3;i++)

{

for(j=0;j<3;j++)

System.out.print(A[i][j]+" ");

System.out.println();

}

for(i=0,k=0;i<3;i++)

for(j=0;j<3;j++)

From[k++]=A[i][j];//making it 1-D

for(i=0,j=0,k=0;i<9;i++)

{

System.arraycopy(From,j,To,i,1);//copying it to another 1-D array

j=j+3;

if(j>=9)//first row completion

j=++k;

}

System.out.println("The Transposed Matrix is...");

for(i=0,k=0;i<3;i++)

{

for(j=0;j<3;j++)

{

B[i][j]=To[k];

k=k+1;

System.out.print(B[i][j]+" ");

}

System.out.println();

}

}

}

Output

The original matrix is...

1 2 3

4 5 6

7 8 9

The Transposed Matrix is...

147

258

369

Ex. 1.13.4: Write a program to find the transpose of a given matrix.

Sol.:

import java.util.Scanner;

class Transpose

{

public static void main(String args[])

{

int m, n, i,j;

Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of matrix");

m = in.nextInt();

n = in.nextInt();

int A[ ][ ] = new int[m][n];//original matrix

int B[ ][ ] = new int[n][m];//transpose matrix

System.out.println("Enter the elements of matrix");

for (i=0;i<m;i++)

for (j=0;j< n;j++)

A[i][j] = in.nextInt();//enter matrix elements throu keyboard

for (i=0;i<m;i++)

{

for (j=0;j< n;j++)

B[j][i] = A[i][j];

}

System.out.println("Transpose of matrix is ");

for (i=0;i<n;i++)

{

for (j=0;j<m;j++)

System.out.print(" "+B[i][j]);

System.out.print("\n");

}

}

}

Output

Enter the number of rows and columns of matrix

34

Enter the elements of matrix

1234

5678

9 10 11 12

Transpose of matrix is

1 5 9

2 6 10

3 7 11

4 8 12

Ex. 1.13.5 Write a program to perform the following functions on a given matrix

i) Find the row and column sum ii) Interchange the rows and columns.

Sol. :

i)class RowColSum

{

public static void main(String args[])throws java.io.IOException

{

int a[][] = {

{10,20,30},

{40,50,60},

{70,80,90}

};

int rsum[]=new int[3];

int csum[]=new int[3];

int i,j;

/* Sum of Rows */

for(i=0;i<3;i++)

{

rsum[i]=0;

for(j=0;j<3;j++)

rsum[i]=rsum[i]+a[i][j];

}

/* Sum of Column */

for(i=0;i<3;i++)

{

csum[i]=0;

for(j=0;j<3;j++)

csum[i]=csum[i]+a[j][i];

}

System.out.println("The sum or rows and columns of the matrix is :"); for(i=0;i<3;i++)

{

for(j=0;j<3;j++)

System.out.print(" '"+a[i][j]);/*displaying each row*/

System.out.print(" = "+rsum[i]);/* displaying row sum*/

System.out.println(""");

}

System.out.println("----------------------");

for(j=0;j<3;j++)

{

System.out.print(" "+csum[j]);/*displaying col sum*/

}

}

}

Output

The sum or rows and columns of the matrix is :

10 20 30 = 60

40 50 60 = 150

70 80 90 = 240

------------------------

120 180

ii) Refer example 1.13.4.

Ex. 1.13.6: Explain binary search method with necessary illustration and write a Java program to implement it.

Sol. The necessity of this method is that all the elements should be sorted. So let us take an array of sorted elements

So match is found at 7th position of array i.e. at array [6]

Thus by binary search method we can find the element 99 present in the given list at array [6]th location.

Java Program[BinSearch.java]

public class BinSearch {

public static void main(String args[]) {

int[] a={10,20,30,40,50,60};

int key=40;

Find(a,0,5,key);

}

public static void Find(int[] a,int low, int high,int key)

{

int mid;

if(low>high)

{

System.out.println("Error!!The element is not present in the list");

return;

}

mid=(low+high)/2;

if(key==a[mid])

System.out.println("\n The element is present at location "+(mid+1));

else if(key<a[mid])

Find(a,low,mid-1,key);

else if(key>a[mid])

Find(a,mid+1,high,key);

}

}

Output

F:\test>javac BinSearch.java

F:\test>java BinSearch

The element is present at location 4

Ex. 1.13.7: Develop a Java program to find a smallest number in the given array by creating a one dimensional array and two dimensional array using new operator.

Sol. :

import java.util.*;

public class SmallestElement

{

public static void main(String[] args)

{

int rows;

int columns;

Scanner scanner = new Scanner (System.in);

System.out.println("\t\t*****TWODIMENSIONALARRAY******");

System.out.println("Enter number of rows: ");

rows = scanner.nextInt();

System.out.println("Enter number of columns: ");

columns = scanner.nextInt();

//creating two dimensional array using new operator int[][] matrix = new int [row][columns];

//storing the elements in the two dimensional array System.out.println("Enter matrix numbers: ");

for (int i = 0; i < rows; i++)

{

for (int j = 0; j < columns; j++)

{

matrix[i][j] = scanner.nextInt();

}

}

// Displaying entered matrix

System.out.println("Matrix as entered");

for (int i = 0; i < matrix .length; i++)

{

System.out.println();

for (int j = 0; j < matrix[i].length; j++)

{

System.out.print(matrix[i][j] + " ");

}

}

System.out.println();

//finding smallest element from 2D array

findMin(matrix);

int size;

System.out.println("\t\t ***** ONE DIMENSIONAL ARRAY *****");

System.out.println("Enter total number of elements: ");

size = scanner.nextInt();

//creating one dimnesional array using new operator

int[] a = new int[size];

//storing the elements in one dimensional array

System.out.println("Enter the elements: ");

for(int i=0;i< size; i++)

{

a[i]=scanner.nextInt();

}

//displaying one dimensional array

System.out.println("The one dimemsional array which you have entered is");

for(int i =0;i< size; i++)

{

System.out.println(a[i]+" ");

}

System.out.println();

//finding smallest element from array

findSmall(a);

}

private static void findMin(int[][] matrix)

{

int minNum = matrix[0][0];

for (int i = 0; i < matrix.length; i++)

{

for (int j = 0; j < matrix[i].length; j++)

{                                                                                                                

if(minNum > matrix[i][j])

{

minNum = matrix[i][j]

}

}

}

System.out.println("Smallest number: " + minNum);

}

private static void findSmall(int[] a)

{

int smallNum=a[0];

for(int i = 0; i <a.length; i++)

 

{

if(smallNum > a[i])

{

smallNum = a[i];

}

}

System.out.println("Smallest number: + smallNum);

}

}

Output

***** TWO DIMENSIONAL ARRAY *****

Enter number of rows:

3

Enter number of columns:

3

Enter matrix numbers:

524

316

987

Matrix as entered

524

316

987

Smallest number: 1

***** ONE DIMENSIONAL ARRAY *****

Enter total number of elements:

5

Enter the elements:

30 10 20 50 40

The one dimemsional array which you have entered is

30

10

20

50

40

Smallest number: 10.

Ex. 1.13.8: Define Java classes of your own without using any library classes to represent linked lists of integers. Provide it with methods that can be used to reverse a list and to append two lists.

Sol.:

public class SinglyLinkedList{

Node head;

static class Node {

private int data;

private Node next;

Node(int data) {

this.data = data;

this.next = null;

}

}

public void insert(Node node) {

if (head==null) {

head = node;

} else {

Node temp = head;

while (temp.next!= null)

temp = temp.next;

temp.next = node;

}

}

public void display(Node head) {

Node temp = head;

while (temp != null) {

System.out.format("%d ", temp.data);

temp = temp.next;

}

System.out.println();

}

// Reverse linkedlist using this function

public static Node reverse (Node currentNode)

{

// For first node, previousNode will be null

Node previousNode=null;

Node nextNode;

while(currentNode!=null)

{

nextNode=currentNode.next;

// reversing the link

currentNode.next=previousNode;

// moving ahead currentNode and previousNode by 1 node

previousNode=currentNode;

currentNode=nextNode;

}

return previousNode;

}

public static Node Append(Node head1, Node head2) {

Node previousNode =null;

Node temp = head1;

while (temp != null) {

previousNode = temp;

temp = temp.next;//reaching to last node of first list

}

previousNode.next = head2;//appending second list

return head1;

}

public static void main(String[] args) {

SinglyLinkedList list = new SinglyLinkedList();

// Creating a linked list

Node head=new Node(10);

list.insert(head);

list.insert(new Node(20));

list.insert(new Node(30));

list.insert(new Node(40));

list.insert(new Node(50));

list.display(head);

//Reversing LinkedList

Node reverseHead-reverse(head)

System.out.println("After reversing");

list.display(reverseHead);

//Creating First LinkedList

Node head1= new Node(1);

list.insert(head1);

list.insert(new Node(2));

list.insert(new Node(3));

list.insert(new Node(4));

list.insert(new Node(5));

System.out.println("The first linked list is");

list.display(head1);

//Creating Second LinkedList

Node head2=new Node(6);

list.insert(head2);

list.insert(new Node(7));

list.insert(new Node(8));

list.insert(new Node(9));

list.insert(new Node(10));

System.out.println("The second linked list is");

list.display(head2);

System.out.println("The concatenated linked list is");

Node head3 = Append(head1, head2);

list.display(head3);

Object Oriented Programming: Unit I: Introduction to OOP and Java : Tag: : - Arrays Example Java Programs