Square Matrix multiplication using Java - java

I'm trying to write a simple square matrix multiplication method using multidimensional arrays.
package matrixmultiplication;
import java.util.Scanner;
public class Matrixmultiplication
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int [][] a,b,c;
int size;
System.out.print("Enter the Size of the matrix :");
size = scan.nextInt();
a=b=c=new int[size][size];
System.out.println("Enter the elements of the First matrix");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
System.out.print("Enter the element a[" + i +"]["+ j + "] : ");
a[i][j] = scan.nextInt();
}
}
System.out.println("Enter the elements of the Second matrix");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
System.out.print("Enter the element b[" + i +"]["+ j + "] : ");
b[i][j] = scan.nextInt();
}
}
System.out.println("The Product of the two matrix is : ");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
int sum = 0;
for(int k=0;k<size;k++)
{
sum +=(a[i][k] * b[k][j]);
}
c[i][j] = sum;
System.out.print(c[i][j] + "\t");
}
System.out.println();
}
}
}
When I run this program in Netbeans ,I get the following output:
Enter the Size of the matrix :2
Enter the elements of the First matrix
Enter the element a[0][0] : 1
Enter the element a[0][1] : 1
Enter the element a[1][0] : 1
Enter the element a[1][1] : 1
Enter the elements of the Second matrix
Enter the element b[0][0] : 1
Enter the element b[0][1] : 1
Enter the element b[1][0] : 1
Enter the element b[1][1] : 1
The Product of the two matrix is :
2 3
3 10
The Correct output of this program should be :
2 2
2 2
Can someone tell me what is wrong with this code.

The problem is here:
a=b=c=new int[size][size];
This creates just one array, and makes all of the variables point to it. So, updating the elements of c is also updating the elements of a and b.
Create 3 arrays instead:
a=new int[size][size];
b=new int[size][size];
c=new int[size][size];
Ideone demo

Related

Matrix Multiplication, Index Out of Bounds Exception

I have try to create a code that can solve a matrix.
import java.util.Scanner;
public class Pratical_8 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking A Matrix
System.out.println("Enter number of Rows and Column for first Matrix");
System.out.print("Enter Rows ");
int aRLen=sc.nextInt();
System.out.print("Enter Columns ");
int aCLen=sc.nextInt();
int [][] a = new int [aRLen][aCLen];
System.out.println("Enter Matrix");
for(int i=0;i<aRLen;i++)
{
for(int j=0;j<aCLen;j++)
{
a[i][j]=sc.nextInt();
}//End of j loop
}//End of I loop
// Taking B Matrix
System.out.println("Enter number of Rows and Column for second Matrix");
System.out.print("Enter Rows ");
int bRLen=sc.nextInt();
System.out.print("Enter Columns ");
int bCLen=sc.nextInt();
int [][] b = new int [bRLen][bCLen];
System.out.println("Enter Matrix");
for(int i=0;i<bRLen;i++)
{
for(int j=0;j<bCLen;j++)
{
b[i][j]=sc.nextInt();
}//End of j loop
}//End of I loop
// Creating resulting Matrix
int [][] r = new int [aRLen][bCLen];
// Check for Valid input
if(aCLen!=bRLen)
{
System.out.println("Error invalid input");
System.out.println("Multiplication of this matrix is not possible");
}
else
{
for(int i=0;i<aCLen;i++)
{
for(int j=0;j<bRLen;j++)
{
for(int k=0; k<bRLen;k++)
{
r[i][j] += a[i][k] * b[k][j]; // LINE 57 ERROR
}//End of k Loop
System.out.print(r[i][j]+" ");
}//End of j loop
System.out.println();
}//End of I loop
}//End of if-else
}//End of main
}//End of class
it have an error after sucessfully give an output
Output:-
Enter number of Rows and Column for first Matrik
Enter Rows 1
Enter Columns 3
Enter Matrix
1
2
3
Enter number of Rows and Column for second Matrix
Enter Rows 3
Enter Columns 1
Enter Matrix
1
2
3
14
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at Pratical_8.main(Pratical_8.java:57)
Process finished with exit code 1
This Error only ocure in non Sysmetrix Matrix
What is the PROBLEM?
Since the final matrix is of order aRLen x bCLen the last for loops needs to be modified.
for(int i=0;i<aRLen;i++) // Instead of aClen
{
for(int j=0;j<bCLen;j++) //Instead of bRlen
{
for(int k=0; k<bRLen;k++)
{
r[i][j] += a[i][k] * b[k][j]; // LINE 57 ERROR
}//End of k Loop
System.out.print(r[i][j]+" ");
}//End of j loop
System.out.println();
}//End of I loop
This will work properly.

How can I print the sum of the columns as well?

package Matrix;
import java.util.Scanner;
public class Matrix
{
public static void main(String[] args) {
System.out.print("Enter 2D array size : ");
Scanner sc=new Scanner(System.in);
int rows=sc.nextInt();
int columns=sc.nextInt();
System.out.println("Enter array elements : ");
int twoD[][]=new int[rows][columns];
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=sc.nextInt();
}
}
System.out.print("\n \n");
for(int []x:twoD){
for(int y:x){
System.out.print(y+" ");
}
System.out.println();
}
System.out.println("");
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum=sum+twoD[i][j];
}
System.out.print(sum+" ");
sum=0;
System.out.print(" ");
}
}
}
how can I print the sum of the columns as well?
here is what I have so far
My expected output must be :
5 9 8 = 22
3 8 2 = 13
4 3 9 = 16
___________
12 20 19
how can I print the sum of the columns as well? here is what I have so far, And it seems like there is a problem with my code as well. Hope you can help me. I've been working on this for days and I'm new to java.
how can I print the sum of the columns as well? here is what I have so far, And it seems like there is a problem with my code as well. Hope you can help me. I've been working on this for days and I'm new to java.
You already have added up the elements in the row. Now to add up the columns instead of trying to change the row in your for loop change the columns to add up.
Change
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum=sum+twoD[i][j];
}
System.out.print(sum+" ");
sum=0;
System.out.print(" ");
To
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum+=twoD[j][i];
}
System.out.print(sum+" ");
System.out.print(" ");
Therefore you will have a loop that runs effectively for every column and has the sum at 0 in the beginning and at the accurate sum at the end of going through each column and all that is left is just to print it out.
If you want to have this implemented in JOption than instead of using Scanner in Java, you would have to import the JOption Library with this import statement
import javax.swing.JOptionPane;
Then you would change your input of 2D Array Size to using the method of showInputDialog. Remember that showInputDialog returns a String and so you would need to use parseInt to turn it to a Integer. Here is an example
int rows;
rows = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D Array
Rows : "));
int columns;
columns = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D
Array Columns : "));
int twoD[][]=new int[rows][columns];
Next change the input of the Array to also use this method. Like this
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter
Array Elements for Row "+(i+1)+" Column "+(j+1)));
}
}
Resulting in the Final Code being
import javax.swing.JOptionPane;
public class Matrix{
public static void main(String[] args) {
int rows;
rows = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D
Array Rows : "));
int columns;
columns = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D
Array Columns : "));
int twoD[][]=new int[rows][columns];
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter
Array Elements for Row "+(i+1)+" Column "+(j+1)));
}
}
System.out.print("\n \n");
for(int []x:twoD){
int cSum = 0;
for(int y:x){
System.out.print(y+" ");
cSum+=y;
}
System.out.println(" = "+cSum);
}
System.out.println("");
System.out.println("___________");
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum+=twoD[j][i];
}
System.out.print(sum+" ");
System.out.print(" ");
}
}
}

Can someone teach me how to get this output

I'm new to java. I'm trying to make my program output this [5,4] [3] [2,1] but instead I get [5,5] [4,4] [3,3] [2,2] [1,1].. what am I missing? I tried to answer it on my own but I just can't think of the answer.
Here's my full code:
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter Array Size:");
int arrSize = sc.nextInt();
System.out.println("The Size of your Array is "+ arrSize);
int arr[] = new int[arrSize];
System.out.println("Enter "+arrSize+" Elements of your Array: ");
for(int i=0;i<arr.length;i++){
arr[i] = sc.nextInt();
}
for(int i=0; i<arr.length;i++){
System.out.print(arr[i] + " ");
}
System.out.println(" ");
for(int i=arr.length-1; i>=0;i--){
System.out.print(Arrays.asList(arr[i]+","+arr[i]));
}
}
try this code
Scanner sc=new Scanner(System.in);
System.out.print("Enter Array Size:");
int f,midd=0;
int arrSize = sc.nextInt();
System.out.println("The Size of your Array is "+ arrSize);
int arr[] = new int[arrSize];
System.out.println("Enter "+arrSize+" Elements of your Array: ");
for(int i=0;i<arr.length;i++){
arr[i] = sc.nextInt();
}
if(arrSize%2==0){
f=0;
}
else {
f=1;
midd=(int)(arrSize/2/2)+1;
}
for(int i=arrSize-1; i>=0;){
if(f==0)
{
System.out.print(Arrays.asList(arr[i]+","+arr[i-1]));
i-=2;
}
else{
if(midd==i){
System.out.print(Arrays.asList(arr[i]));
i--;
}
else {
System.out.print(Arrays.asList(arr[i]+","+arr[i-1]));
i-=2;
}
}
}
provide this program inside main method
Output:
Enter Array Size:5
The Size of your Array is 5
Enter 5 Elements of your Array:
1
2
3
4
5
[5,4][3][2,1]
.
Enter Array Size:4
The Size of your Array is 4
Enter 4 Elements of your Array:
1
2
3
4
[4,3][2,1]
.
Enter Array Size:7
The Size of your Array is 7
Enter 7 Elements of your Array:
1
2
3
4
5
6
7
[7,6][5,4][3][2,1]
YOu can try the following. I think what you need is to split the array as a pair.
I am assuming you will have middle pair with one element in case of odd length and all pairs will have two elements in case of even length of the array.
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter Array Size:");
int arrSize = sc.nextInt();
System.out.println("The Size of your Array is "+ arrSize);
int arr[] = new int[arrSize];
System.out.println("Enter "+arrSize+" Elements of your Array: ");
for(int i=0;i<arr.length;i++){
arr[i] = sc.nextInt();
}
for(int i=0; i<arr.length;i++){
System.out.print(arr[i] + " ");
}
System.out.println(" ");
int i=arr.length-1;
for(; i>arr.length/2;i-=2){
System.out.print(Arrays.asList(arr[i]+","+arr[i-1]));
}
if(arr.length %2 == 0){
System.out.print(Arrays.asList(arr[i]+","+arr[i-1]));
i-=2;
}else{
System.out.print(Arrays.asList(arr[i]));
i-=1;
}
for(; i>0;i-=2){
System.out.print(Arrays.asList(arr[i]+","+arr[i-1]));
}
}

Printing a Square Matrix and Transposing it with Java

I need to write a program that will take a number n from the user and create an nxn matrix that counts up, then I need to transpose it. I've tried multiple methods of coding, but nothing displays correctly.
import java.util.Scanner;
public class SquareMatrix {
public static void main(String[] args)
{
//Variables
int size;
int value;
//Scanner
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Prompt
System.out.println("Enter the size of the Square Matrix: ");
size = input.nextInt();
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = i+j;
System.out.print(value);
}
}
}
}
The result I'm currently getting is:
Enter the size of the Square Matrix:
3
123
234
345
I need it to look more like this:
Enter the Size of the Square Matrix:
3
Square Matrix:
1 2 3
4 5 6
7 8 9
Transpose:
1 4 7
2 5 8
3 6 9
The nxn matrix counting up is
for(int i=0; i<size; i++) {
System.out.println();
for(int j=1; j<=size; j++) {
value = j + i*size;
System.out.print(value);
}
}
The transponse is
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = j*size + i;
System.out.print(value);
}
}
I wrote a code that does exactly what you need. It may seem overcomplicated but i think it grasp the idea that you would do with pencil and paper. You need to put the scanning user input part in though.
int n=10;
int[][] matrix =new int[n][n]; // a 2D array as one would imagine a matrix
int num=0;
int temp=0;// used in transposing
//initializing the arrays of the second dimension
for (int init=0;init<n;init++){
matrix[init]=new int[n];
}
System.out.println("filling and printing matrix");
for (int fill_row=0;fill_row<n;fill_row++){
for(int columns=0;columns<n;columns++){
matrix[fill_row][columns]=++num;
if(columns==n-1){
System.out.println(Arrays.toString(matrix[fill_row]));
}
}
}
System.out.println("Transposed matrix");
for (int transp_row=0;transp_row<n;transp_row++){
for(int columns=transp_row;columns<n;columns++){
//store actual value to temp,
temp=matrix[transp_row][columns];
//by switching the order of the indicies assign new value to current position
matrix[transp_row][columns]=matrix[columns][transp_row];
//assgin temp value to what we used as replacement
matrix[columns][transp_row]=temp;
if(columns==n-1){
System.out.println(Arrays.toString(matrix[transp_row])); // print each rows of the array
}
}
}
}
I hope it helps.

Trouble merging two sorted user-inputed arrays

Writing a code that should read two already sorted arrays from a user of the user's defined length, then sort them into one still-sorted list. For some reason I can't get it to sort past the first three digits? It looks like it might be something really simple that I'm missing but I've been fiddling with it for a while and not finding anything. Any ideas?
Sample Run:
How long are the lists?: 3
Enter list A:
1: 1.0
2: 2.0
3: 3.0
Enter list B:
1: 2.0
2: 3.0
3: 4.0
Merged List: 1.0, 2.0, 2.0, 3.0, 3.0, 4.0
code:
import java.util.Scanner; //import scanner
public class project2 {
public static void main (String[] args){
Scanner input = new Scanner(System.in); //scanner for input
int a = 0;
System.out.println("How long are the lists? ");
System.out.print("(The lists should be the same length): ");
a = input.nextInt();
double [] lista = new double [a]; //create array
double [] listb = new double [a]; //create array
int count=1;
System.out.println("Enter numbers for list A:");
for(int j = 0; j < a ; j++){ //user input numbers loop into array "list"
System.out.print(count + ": ");
lista[j] = input.nextDouble();
count++;
}
int acount = 1;
System.out.println("Enter numbers for list B:");
for(int j = 0; j < a ; j++){ //user input numbers loop into array "list"
System.out.print(acount + ": ");
listb[j] = input.nextDouble();
acount++;
}
System.out.println(); // print the original lista inputed by user
System.out.print("Your list A: ");
for(int j=0; j<a; j++){
System.out.print(lista[j] + " ");
}
System.out.println(); // print the original listb inputed by user
System.out.print("Your list B: ");
for(int j=0; j<a; j++){
System.out.print(listb[j] + " ");
}
project2.merge(lista, listb);
System.out.println(); // print the new merged listc
System.out.print("Merged List: ");
for(int j=0; j<a; j++){
System.out.print(project2.merge(lista, listb)[j] + ", ");
}
}
public static double [] merge ( double [] list1, double [] list2){
double [] listc = new double [list1.length + list2.length]; //create array
int i = 0, j = 0, k = 0;
while (i < list1.length && j < list2.length)
{
if (list1[i] < list2[j])
{
listc[k] = list1[i];
i++;
}
else
{
listc[k] = list2[j];
j++;
}
k++;
}
while (i < list1.length)
{
listc[k] = list1[i];
i++;
k++;
}
while (j < list2.length)
{
listc[k] = list2[j];
j++;
k++;
}
return listc;
}
}
You are merging two arrays of length a, into an array of length 2 * a, but you only print out the first a numbers. Modify your for loop condition that prints out the merged array:
for(int j=0; j< 2*a; j++){
Also, every time you call merge, you merge the arrays again. Just merge it once, then refer to the array when printing the contents. This version uses the new merged array's length to stop the loop.
double[] listc = project2.merge(lista, listb);
System.out.println(); // print the new merged listc
System.out.print("Merged List: ");
for(int j=0; j < listc.length; j++){
System.out.print(merged[j] + ", ");
}
Hint: Since you are merging two sorted lists into one (output) sorted list, consider a loop that you execute for the size of the output list .. and put into the next output slot the next appropriate value from each of the two input lists.
Inside that loop, what would you want to compare to see which value you get next?
How would you handle exhausting one list before the other?
How can you generalize your program so the two input lists do not need to be the same length?
(no code for homework)
Why do you not just use the JDK-method java.util.Arrays#sort(double[]) instead of reinventing the wheel?

Categories