-3

I'am trying to write a program which can calculate determinant of 2x2 matrix entered by user. My code is as follows -

 //Program to calculate determinant of matrices

#include<iostream>
#include<conio.h>
using namespace std;

int main()
{
    int arr[1][1];
    int i,j,p,q,v,b,c,k,determinant;
    
    for(i=1;i<=2;i++)
    {
    for(j=1;j<=2;j++)
    {
    p=i;
    q=j;    
    cout<<"Enter element :- ";
    cin>>arr[p][q];
    cout<<"You are in "<<i<<j<<endl;
    }
    }
    v=arr[1][1];
    b=arr[1][2];
    c=arr[2][1];
    k=arr[2][2];
    cout<<"Entered elements are = "<<v<<" "<<b<<" "<<" "<<c<<" "<<k<<endl;
    determinant= ((v*k)-(c*b)); 
    cout<<"Determinant of given matrix is = "<<determinant; 
    getch();
}

And this is the error I'am facing with this program -

Enter element :- 4
You are in 11
Enter element :- 9
You are in 12
Enter element :- 8
You are in 21
Enter element :- 7
You are in 22
Entered elements are = 4 8  8 7
Determinant of given matrix is = -36

At the position arr[1][2] I have entered '9' as the element, but instead it is printing the element assigned to position arr[2][1]. So, if anybody can help me resolve this error then I will be very much grateful to you.

2 Answers2

1

The int arr[1][1] does not declare an matrix of two elements, it declares a 1x1 matrix.

Declare it instead as

int arr[2][2];

That being said, indices in C++ start at 0 so

v=arr[1][1];
b=arr[1][2];
c=arr[2][1];
k=arr[2][2];

should be

v=arr[0][0];
b=arr[0][1];
c=arr[1][0];
k=arr[1][1];

same goes for your for-loops

AndersK
  • 35,813
  • 6
  • 60
  • 86
0

Array starts from index 0. The size of array should be a[2][2] since it is a 2x2 matrix. Modify the loops accordingly for the array elements.

#include<iostream>

using namespace std;

int main()
{
    int arr[2][2];
    int i,j,p,q,v,b,c,k,determinant;
    
    for(i=0;i<=1;i++)
    {
    for(j=0;j<=1;j++)
    {
    p=i;
    q=j;    
    cout<<"Enter element :- ";
    cin>>arr[p][q];
    cout<<"You are in "<<i+1<<j+1<<endl;
    }
    }
    v=arr[0][0];
    b=arr[0][1];
    c=arr[1][0];
    k=arr[1][1];
    cout<<"Entered elements are = "<<v<<" "<<b<<" "<<" "<<c<<" "<<k<<endl;
    determinant= ((v*k)-(c*b)); 
    cout<<"Determinant of given matrix is = "<<determinant;
}

Kavya
  • 105
  • 1
  • 15