how to find sum of each value of column in multidimensional array - arrays

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;
}

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'.

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");
}

Related

how to continously scan for the amount of numbers inside of an array

I currently am having a small trouble in my code, I am supposed to make a program that adds / sums all numbers inside of an array, while I have no problem in doing that, I currently have a problem with the part in which you are supposed to scan the numbers to be put in the array, here are the example of the input
3
5
1 2 3 4 5
8
1 2 3 4 5 6 7 8
9
1 2 3 4 5 6 7 8 9
What this means is that, the user inputs number "3" as it means to create 3 arrays, the number "5" afterward means to put 5 numbers inside of the array (1 2 3 4 5), after the user has inputted the numbers inside of an array, the user inputs "8" which means to make another array consisting of 8 numbers, and then putting numbers into the array again, and so on.
However I am having a problem in which after inputting all the numbers in the array that consists of 5 number, the program instead inputs 5 number into another array again (instead of asking the amount of numbers to be put inside of another array), so instead the number "8 1 2 3 4" gets inputted in another array, and I did not know which part I did wrong.
Here are my C code :
#include <stdio.h>
int main(){
int x, y;
int i;
int n;
int c=1;
int count=0;
int sum=0;
scanf("%d", &y); //this determines the amount of array to be inputted
scanf("%d", &x); //this determines the amount of numbers to be inputted inside of an array
int line[x];
for(int i=0; i<y; i++){
sum=0;
for(int i=0; i<x; i++){
scanf("%d", &line[i]); //scan number for the array
sum += line[i];
}
printf("Case #%d: %d\n", c, sum);//output of all sum
c++;
}
}
You need to read the size for each array - currently you only read it once.
e.g.:
int numLines;
scanf("%d", &numLines);
for(int lineIdx = 0; lineIdx < numLines; lineIdx++) {
// read the number of elements for each array
int numNumbers;
scanf("%d", &numNumbers);
int line[numNumbers];
for(int i = 0; i < numNumbers; i++) {
scanf("%d", &line[i]);
}
}
Additionally you can avoid storing the individual numbers, since you're only interested in the sum, e.g.:
int sum = 0;
for(int i = 0; i < numNumbers; i++) {
int number;
scanf("%d", &number);
sum += number;
}
Also you could defer outputting the sums until all inputs have been processed, so it doesn't visually get interleaved into the input.
This would be a possible way to write that program: godbolt
#include <stdio.h>
int main() {
// get the number of arrays we need to read
int numLines;
scanf("%d", &numLines);
// The sums of each array
int sums[numLines];
for(int lineIdx = 0; lineIdx < numLines; lineIdx++) {
// read the number of elements for each array
int numNumbers;
scanf("%d", &numNumbers);
// sum up all the numbers of the array
sums[lineIdx] = 0;
for(int i = 0; i < numNumbers; i++) {
int number;
scanf("%d", &number);
sums[lineIdx] += number;
}
}
// after all arrays have been entered,
// output the sums for each case:
for(int lineIdx = 0; lineIdx < numLines; lineIdx++) {
printf("Case #%d: %d\n", lineIdx, sums[lineIdx]);
}
}

transpose square matrix with pointer in C. wrong output

The goal is to print the transpose of the 'Matrix'.
To create square matrix, I got 'row' from the keyboard.
row is same with column so I only declared 'row'.
the problem I need help is right below ↓
/*input*/
5 4 1
9 0 1
6 5 7
/*output I want*/
5 9 6
4 0 5
1 1 7
/*wrong output I get*/
0 4 -30838770
0 7 2
0 5 7
And here is my code. Matrix in each function must be called by reference. I also want to know if I got it right.
//code start
int Generate(int row, int (*Matrix)[row])
{
srand(time(NULL)); //make random number
int i, j;
printf("Matrix = ");
for(i=0; i<row; i++){
for(j=0; j<row; j++){
Matrix[i][j] = (rand() % 10); //insert random number from 0 to 10
printf("%d ", Matrix[i][j]); //print matrix before transposing
}
printf("\n");
}
return 0;
}
void Transpose(int row, int (*Matrix)[row])
{
int i, j;
for(i=0; i<row; i++){
for(j=0; j<row; j++){
int transpose[i][j];
transpose[i][j] = Matrix[j][i];
printf("%d ", transpose[i][j]);
}
printf("\n");
}
}
int main() {
int input; //for switch case
int row = 0; //row has to be 2 or 3
int Matrix[row][row]; //2d array. largest index should be Matrix [row-1][row-1]
while(1){
scanf("%d", &input);
switch(input){
case 1: // Generate random square matrix
scanf("%d", &row); //insert row
Generate(row, Matrix);
break;
case 2: //transpose matrix
Transpose(row, Matrix);
break;
default:
return 0;
}
}
}
//code end
I'm new to this community so I'm not sure I gave you all the information needed.
Please let me know the lines you don't understand because I really want to get this code work.
I'm waiting for your help!
Your program is trying to print the transpose, so you don't need to store anything. remove all the stuff with transpose[i][j], and just print Matrix[j][i]. As pointed out in the comments, you are allocating (on the stack) a new matrix of shape ixj at each iteration, which makes no sense.

Sorting inputted integers into odd and even arrays

I'm a beginner to C, and am trying to sort user inputted numbers into odd and even arrays. I don't understand why my code isn't working.
Cheers.
This is my code, I don't understand my mistake.
int x[]= {};
int i=0;
int d=0;
int j=0;
int even[12]={};
int odd[12]={};
printf("Enter amount of numbers: "); // asking user for amount of numbers
scanf("%d", &d);
for (j=0; j<d; j++){
printf("Enter number %d: ", i+1); // scanning input into 'x' array
scanf("%d", x[i]);
}
printf("Even numbers: ");
for (i=0; i<d; i++) {
if (x[i] % 2 == 0) { // sorting into even array
even[i]=x[i];
printf("%d \n", even[i]);
}
}
printf("\n Odd numbers: ");
for (i=0; i<d;i++){
if (x[i] % 2 != 0) { // sorting into odd array
odd[i]=x[i];
printf("%d \n", odd[i]);
}
}
This error message keeps coming up:
$ ./main
Enter amount of numbers: 4
Enter number 1: 6
Segmentation fault (core dumped)
int x[]= {}; doesn't work because it would hold no elements. But initializing it with {} doesn't work in C anyway, do this instead:
int x[24] = {0}; // first element explicitely set to 0, the rest default-initialized to 0
You also need to put {0} for even and odd. If it's compiling for you with {} then it's possible that you're compiling it as a C++ program, or perhaps your compiler just tolerates it anyway (but it won't work on every C compiler).
scanf needs the address of the int, so instead of scanf("%d", x[i]); you need scanf("%d", &x[i]);. But i is the wrong iterator for this for (j = 0; j < d; j++) loop. Instead do this:
for (j = 0; j < d; j++) {
printf("Enter number %d: ", j + 1); // scanning input into 'x' array
scanf("%d", &x[j]);
}
Also note that the way you're doing this, half the array will be left at 0. So for instance if I imputted the values 1 through 6, then odd contains the values 1 0 3 0 5 0.

C: How to read in multiple values using scanf in a matrix

Hi I'm trying to write a code for user input matrix size and values. I got the bit about setting the matrix size and value, but I want to read in one row at a time so that I don't have to press enter every time after a single value input. This is my code so far. Thanks.
int row, col, i, j;
int mat[10][10];
printf("Enter number of rows: ");
scanf("%d", &row);
printf("Enter number of columns: ");
scanf("%d", &col);
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
scanf("%d", &mat[i][j]);
}
}
printf("\nHere is your matrix:\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
I want to read in one row at a time so that I don't have to press enter every time
The code you listed can work this way! That's how scanf works.
You CAN press an Enter once each number or once each row(you should use space or tab to delimit numbers) or even after you input the whole matrix, just try it!
In C Memory is allocated continuously
The values will be stored in the array row wise so use space instead of new line it will work
Even if you type all elements on one line separated by space it will store row wise
so if
rows=3 col=3
i/p= 1 2 3 4 5 6 7 8 9
matrix will be
1 2 3
4 5 6
7 8 9

Using Scanf for Storing Input in 2d Arrays

I want to scan input and save it in a square 2d array.
The first two digits are saved in seperate variables, the first digit is a target number (irrelevant here), the second digit gets saved in variable m, i.e. m = 5 in this case. m is the number of rows/colums of the square matrix. The rest of the input should be saved in the array.
For this particular input, I get a segmentation-fault and random numbers are printed on the screen.
I used some printf statements to trace where things go wrong, and I noticed that the index i in the first loop jumped from 2 to 11 in one scenario, for other input it jumped to 33.
Thanks for your help! I hope I am not missing an obvious mistake.
Input: (each row is seperated by the previous by pressing enter.)
42 5
0 3 7 9 10
9 13 20 5 20
12 11 33 0 12
17 39 22 3 18
My code:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* arv[]){
int target; // for later processing, irrelevant here
int m; // m = #rows and #columns of array
int array[m][m];
scanf("%d %d", &target, &m);
int i, k;
for(i = 0; i < m; i++){
for(k = 0; k < m; k++){
scanf("%d", &(array[i][k])); // save value in array.
}
}
// the problem occurs before this point.
for(i = 0; i < m; i++){
for(k = 0; k < m; k++){
printf("%2d", array[i][k]); // print array.
}
printf("\n");
}
return 0;
}
You have not initialized the value of m before creating array[m][m]. Without initializing, the value of m can be anything.
Change:
int array[m][m];
scanf("%d %d", &target, &m);
to
scanf("%d %d", &target, &m);
int array[m][m];
This is the place where you messed up.
int m;
int array[m][m];
Here ,m is uninitialized and you are creating an array of m*m elements. You need m initialized before the declaration of the array. So move the array declaration after the scanf just after it so that m gets initialized before you declare the array.
#innclude <stdio.h>
int i, j;
int t[5][5];
i=0;
j=0;
while(i < 5)
{
j = 0;
while (j < 5)
{
scanf("%d", &(t[i][j++]));
}
i++;
}

Resources