-
simplify this?
Code:
#include <stdio.h>
void main()
{
int matrix[100][100], n, k, l, bord, bord1, bord2, bord3, bord4;
do{
printf("Enter order of matrix between 1 and 100 \n");
scanf("%d",&n);
}while(n<1 || n>100);
for(k=0;k<n;k++){
printf("Enter values for Row %d\n",k);
for(l=0;l<n;l++){
printf("Enter values for row %d col %d\n",k,l);
scanf("%d",&matrix[k][l]);
}
}
bord=0;
for(k=0;k<1;k++){
for(l=0;l<n;++l){
bord=bord+matrix[k][l];
}
}
bord1=0;
for(k=n-1;k<n;k++){
for(l=0;l<n;++l){
bord1=bord1+matrix[k][l];
}
}
bord2=0;
for(l=0;l<1;l++){
for(k=0;k<n;k++){
bord2=bord2+matrix[k][l];
}
}
bord3=0;
for(l=n-1;l<n;l++){
for(k=0;k<n;k++){
bord3=bord3+matrix[k][l];
}
}
bord4=0;
bord4=bord+bord1+bord2+bord3;
printf("The sum of the border elements are: %d\n",bord4);
}
I'm supposed to make a square matrix n x n, and get the sum of all border elements. This program is what I came up with, it works well enough, I was just wondering if there was a way to use fewer iterative statements.
-
Forgetting the setup process, the addition of all the sides can be peformed using only one loop. For now, I'll leave it to you to figure out how ;)
Also, are you sure your program does what you want? I entered a 2x2 matrix, each cell containing the value 1, and it told me the sum was 6:
Code:
Enter order of matrix between 1 and 100
2
Enter values for Row 0
Enter values for row 0 col 0
1
Enter values for row 0 col 1
1
Enter values for Row 1
Enter values for row 1 col 0
1
Enter values for row 1 col 1
1
The sum of the border elements are: 6
-
Code:
bord2=0;
for(l=0;l<0;l++){ /*changed it to 1*/
for(k=0;k<n;k++){
bord2=bord2+matrix[k][l];
Thanks.