sorry, im still try to figure out about multiple repetition and array and i need help to find sum of each value of column in multidimensional array.
so i have this input :
2 -> number of tc
3 -> size of array
1 2 3
4 5 6 -> all value of array
7 8 9
4 -> size of array
1 2 3 4
5 6 7 8 -> value of array
9 0 1 2
3 4 5 6
and the output will be :
Case#1: 12 15 18
Case#2: 18 12 16 20
and here is my code :
int n,m;
scanf("%d",&n);
for(int i=1;i<=n;i ){
scanf("%d",&m);
int o[m][m],sum[m][m];
for(int i=1;i<=m;i ){
for(int j=1;j<=m;j ){
scanf("%d",&o[i][j]);
sum[i][j]=o[i][j] o[i 1][j 1];
}
}
for(int i=1;i<=m;i ){
for(int j=1;j<=m;j ){
printf("Case #%d: %d ",i,sum[i][j]);
}
printf("\n");
}
}
return 0;
}
CodePudding user response:
I have a few suggestions to help you along. First, the first, second, and fourth for
loops use the same indexing variable i
. This will cause issues with the first for
loop as the variable i
is being changed by the others. I suggest you first create a program that only works with a single matrix then, once it works correctly, expand it to handle multiple matrices. This will reduce the number of for
loops you have to manage while figuring out the indexing. Second, the sum
array doesn't have the correct size. It looks like it should be sum[n][m]
instead of sum[m][m]
. Lastly, to get the output you want, you should move the output for
loop outside of the first for
loop. Like this:
int n,m;
scanf("%d",&n);
for(int i=1;i<=n;i ){
...
for(int i=1;i<=m;i ){
...
}
}
for(int i=1;i<=m;i ){
for(int j=1;j<=m;j ){
printf("Case #%d: %d ",i,sum[i][j]);
}
printf("\n");
}
CodePudding user response:
First the code :
#include <stdio.h>
int main () {
int cases;
printf ("\nCases Count? : ");
scanf ("%d", &cases);
for (int cid = 0; cid < cases; cid) {
int size;
printf ("\nMatrix Size : ");
scanf ("%d", &size);
long sum [size]; // if long has more space than int on your machine, else use long long
for (int col = 0; col < size; col) // reset sums before next case
sum[col] = 0;
// we don't need to store matrix, as we're not re-using it
for (int row = 0; row < size; row) {
for (int col = 0; col < size; col) {
int value;
scanf ("%d", &value);
sum[col] = value; // add the value to respective column total
}
}
printf ("Case #%d: ", cid 1);
for (int col = 0; col < size; col)
printf ("%ld ", sum[col]);
printf ("\n");
}
return 0;
}
Warning: scanf()
fails if you input a string instead of numbers. scanf() usage. Lookup how to use fgets()
& parse inputs to have more control.
- There is no prize for using bare minimum variable names. Use concise yet meaningful variable names, even if you're testing something.
- Enable all compiler warnings. For GCC an alias something like
alias mygcc='gcc -Wall -Wextra -pedantic -g3 -O2 -fsanitize=address,undefined,leak -Wshadow'
.