0% found this document useful (0 votes)
3 views2 pages

Java Programs: Matrix, Rectangle, Even/Odd

Uploaded by

Mmk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Java Programs: Matrix, Rectangle, Even/Odd

Uploaded by

Mmk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programs - Clean, runnable versions

1) Matrix Multiply (generic sizes)


---------------------------------
public class MatrixMultiply {
public static int[][] multiply(int[][] A, int[][] B) {
int r1 = [Link], c1 = A[0].length;
int r2 = [Link], c2 = B[0].length;
if (c1 != r2) throw new IllegalArgumentException("Incompatible sizes");
int[][] R = new int[r1][c2];
for (int i=0;i<r1;i++)
for (int j=0;j<c2;j++)
for (int k=0;k<c1;k++)
R[i][j] += A[i][k]*B[k][j];
return R;
}
public static void main(String[] args) {
int[][] a = {{1,1,1},{2,2,2},{3,3,3}};
int[][] b = {{1,0,0},{0,1,0},{0,0,1}};
int[][] r = multiply(a,b);
for (int[] row : r) {
for (int v : row) [Link](v + " ");
[Link]();
}
}
}

2) Area & Perimeter of Rectangle (simple)


-----------------------------------------
public class RectangleDemo {
public static void main(String[] args) {
double length = 5.0, width = 3.0;
[Link]("Area: " + (length*width));
[Link]("Perimeter: " + (2*(length+width)));
}
}

3) Even/Odd checker
-------------------
import [Link];
public class EvenOdd {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number: ");
if (![Link]()) { [Link]("Not an integer"); return; }
int n = [Link]();
[Link](n + ((n & 1) == 0 ? " is Even." : " is Odd."));
[Link]();
}
}

4) Shape & Circle (inheritance example)


---------------------------------------
class Shape {
public double getArea() { return 0.0; }
public double getPerimeter() { return 0.0; }
}
class Circle extends Shape {
private double r;
public Circle(double r){ this.r = r; }
@Override public double getArea(){ return [Link]*r*r; }
@Override public double getPerimeter(){ return 2*[Link]*r; }
}
public class ShapeDemo {
public static void main(String[] args){
Circle c = new Circle(8.0);
[Link]("Radius=8.0 Perimeter=" + [Link]() + " Area=" +
[Link]());
}
}

--- End of file ---

You might also like