void ArrayDiagonal(double Array[4][4])
{
//declare local variables//
int i,j=0;
double dSum = 0;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(i==j)
{
dSum=dSum+Array[i][j];
}
}
}
printf("The sum of the main diagonal elements is = %.2f\n", dSum);
OffArrayDiagonal(Array);
}
void OffArrayDiagonal(double Array[4][4])
{
//declare local variables//
int i,j=0;
double dOff= 0;
for(i=0;i<4;i++)
{
for(j=4;j=0;j++)
{
if(i==j)
{
dOff=dOff+Array[i][j];
}
}
}
printf("The sum of the off diagonal elemets is = %.2f\n", dOff);
}
So for a project i'm doing I have to add the diagonal elements of the array together. The first function work properly but I cant get the other direction to work properly. Any ideas?
One problem is that j
starts at 4 and then increments (increases) to 5, 6, ... You also want to start at 3 instead of 4. And you don't want to assign anything to j
in the conditional. So use for(j=3;j>=0;j--)
.
You don't really need a two-dimensional iteration though, since the diagonal is one-dimensional. So a simpler and more efficient solution would be
for (i = 0 ; i < 4 ; i++)
dOff += Array[i][3-i];
and similarly for the first diagonal.