Storing matrix colum sums and comparing them to find the largest - c

How do I store 1,2,3...n columns sums to a variable and than compare them to find the largest sum?
#include <stdio.h>
#include <math.h>
#define NUM_ITEMS 1000
int array[NUM_ITEMS];
int main(){
FILE* file;
int a[10][10];
int i,j, count = 0;
int n=0;
file = fopen("Matrica.txt", "r");
while(count < NUM_ITEMS && fscanf(file, "%d", &array[count]) == 1)
count++;
n = sqrt(count);
printf("Dimenzije matrice: %dx%d ",n,n);
rewind(file);
for(i=0;i<n;i++)
for(j=0;j<n;j++){
fscanf(file,"%d",&a[i][j]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("\nElementi matrice: %d \n",a[i][j]);
}
}
int col[n];
for(j=0;j<n;j++){
for(i=0;i<n;i++){
col[i] += a[i][0];
}
}
printf("\nDBG:%d",col[0]);
fclose(file);
}
The task is to find dimensions of a[10][10], print out the elements of it and find the column that has biggest sum. What is the name for this var in English.
So far I've finished 2/3rds of the task.
Below is the code:
for(j=0;j<n;j++){
for(i=0;i<n;i++){
col[i] += a[i][0];
}
}
it is the code for calculating sum of the 1st column.
I don't know how to implement it to do what I want, because col[i] must have NULL values for sum to take it's place
or it will just print out a bunch a jibberish.
Note: col[0] was supposed to present column 1 , col[1] column 2 etc.

If I guessed correctly from the example you get only one 10x10 matrix from file, and now you want to sum elements in columns(vertically) not in rows(horizontally) try changing
col[i] += a[i][0]
to
col[i] += a[j][i]
Because with your code you were only adding first element of every row. First [] indicates row,second [] indicates column. What this slight change does is it sums every column element of row to its column index in col[i]. Because I don't know how your text file looks like I suppose you for sure get 10x10 matrix with valid elements.

Related

Input multiple values to multidimensional array C

I have an assignment where I have to make a program that takes in 3 sets of data of 5 values and adds them to a 3 * 5 array. I have already made a program where you type in each individual value, but I would rather want it to take in five values over 3 different inputs.
The code is not finished. I also have to do some operations on the data but I got that covered.
#include <stdio.h>
#include <stdlib.h>
#define THREE 3
#define FIVE 5
void totalArray(int, int, int set_numbers[][FIVE]);
void totalArray(int row, int column, int set_numbers[][FIVE]){
int total, subtotal;
printf("\tThe total of your 3-by-5 array is:\n");
for(row = 0, total = 0; row < THREE; row++){
// for each row, the numbers are summed
for(column = 0, subtotal = 0; column < FIVE; column++){
subtotal += set_numbers[row][column];
printf("%d %d", row, subtotal);
total += subtotal; // Total for entire array
}
}
}
int main(){
// 2D array of 15 numbers declaration
int set_numbers[THREE][FIVE] = {{}, {}, {}};
//counter variables for the loop
int i, j, column, row;
printf("\tYou're given an array which is a 3 by 5 array.\n");
printf("\tYou're going to put in each of the total 15 values.\n");
printf("\t___________________________________________________\n");
printf("\n\t\t\t--ATTENTION--\n");
for(i = 0; i < 3; i++){
for(j = 0; j < 5; j++){
printf("\n\t ******************************************");
printf("\n\t ** Array values have to be integers **");
printf("\n\t ******************************************");
printf("\n\tWhich values do you want in set_numbers[%d][%d]\n", i, j);
scanf("%d", &set_numbers[i][j]);
}
}
totalArray(row, column, set_numbers);
printf("The average of your three sets of numbers are: \n\n");
for(i = 0; i < 3; i++){
for(j = 0; j < 5; j++){
printf("%d", set_numbers[i][j]);
if(j == 4){
printf("\n");
}
}
}
return 0;
}
I should specify, that what i want it to do, is take in sets of data. Something along the lines of
int array[][] = {{}, {}, {}}
First, you should rename the macros THREEto COLUMNS and FIVE to ROWS, because it doesn´t make much sense to name macros after values. Consider, that you might want to change the values later and the understanding of what these macros are meant for is unclear at first sight.
Furthermore i don´t see any reason for declare the separate variables column and row inside of main() if you already have such macros. Please adjust that (You also need to change the declaration of totalArray() respectively).
Than you can incorporate this loop:
for (i = 0; i < COLUMNS; i++)
{
scanf("%d %d %d %d %d", &set_numbers[i][0], &set_numbers[i][1], &set_numbers[i][2], &set_numbers[i][3], &set_numbers[i][4]);
}
And you should really only use the macros, instead of hardcoding the actual values in the program. Consider you need to change the values later, then you need to go through the whole program again and change the according parts (which is relatively easy in your case, but just shouldn´t be). Consider also, you need to change them thereafter back again. That is the reason also, what the macros are meant for.

C - Entering values for 2d Array using for loop produces different values than entered

I have this simple program I am working on in class, it initialized a 3x5 2d Array of integers whose values are inputted for each cell by the user. The program then calls a function which runs through the array with a for loop to display each value, then calls a function which again uses a for loop to double every value, and calls the previous display function to show the array again.
All of this seems to be working, however I am consistently getting odd outputs for certain areas when initializing the values for the 2dArray.
For example: Entering 5 rows of "1, 2, 3" and then calling the display function produces this as output:
1,1,2,
1,2,3,
1,2,3,
1,2,5,
1,2,3
Further more, the doubling function produces further strange results but only in the areas where the output was different from what the user had inputted.
Output of the double function on the array I just posted displays as:
2,4,8
2,4,6
2,4,6
2,4,10,
4,8,6
The only real mathematical operation in the entire program is in the doubling functions, where it runs through a for loop setting the value of "array[j][i] = (array[j][i] = array[j][i] * 2)"
I cannot for the life of me figure out which part of the program I've written would cause the user inputs to change to what has been displayed. Inputting values other than "1,2,3" produces similarly odd results. Anyone have any idea what is wrong here? I feel like it must be a very simple mistake I am missing. Here is my source code:
#include <stdio.h>
#include <stdlib.h>
void displayArray(int array[][4]);
void doubleArray(int array[][4]);
int main() {
int dArray[2][4];
int i, j, k;
for(i = 0; i <= 4; i++){
for(j = 0; j <= 2; j++){
printf("Enter a value for the array at position %d,%d.\n", j, i);
scanf("%d", &dArray[j][i]);
}
}
printf("Displaying your original array...\n");
displayArray(dArray);
printf("Doubling your array...\n");
doubleArray(dArray);
printf("Displaying your doubled array....\n");
displayArray(dArray);
system("pause");
}
void displayArray(int array[][4]){
int i, j;
for(i = 0; i <= 4; i++){
printf("\n");
for(j = 0; j <= 2; j++){
if(j == 2 && i == 4){
printf("%d", array[j][i]);
}
else{
printf("%d,", array[j][i]);
}
//system("pause");
}
}
printf("\n");
}
void doubleArray(int array [][4]){
int i, j;
for(i = 0; i <= 4; i++){
for(j = 0; j <= 2; j++){
array[j][i] = (array[j][i] * 2);
//printf("%d\n", array[j][i]);
}
}
}
It's all in one .c file, and I am using devc++ if that makes any difference.
To calculate the DIMENSIONS of your 2D C arrays you have to count how many columns and how many rows there are. In your examples, it is 3 columns and 5 rows, and those are the values you must enter in your array definition:
int array[3][5]
Then, because C starts indexing with 0 offset, you can referr to the elements of the array using the columns 0 to 2 (that is, 3 columns) and rows 0 to 4 (that is, 5 rows). As other people said, this can be achieved using "lower than the limit" (correct: <3 for the columns, <5 for the rows) instead of "lower or equal than the limit" (incorrect, out of bounds: <=3 for the columns, <=5 for the rows).

Average of a row in a two-dimensional array in C?

I am having trouble making a program that uses a function call to find the average of the rows in a two dimensional array? I can't get it to work in a larger program. I made this program to try and figure out what I am doing wrong, but to no avail. Any outside help would be greatly appreciated! Here is the testing code:
#include <stdio.h>
double dAvg(double pt[][5],int rows);
int main(void){
int i;
//Initiallize array
double array[3][5]={{3.0,5.0,2.0,1.0,0.0},{4.0,8.0,6.0,3.0,3.0},{7.0,6.0,2.0,3.0,5.0}};
//Computes the average value per row of array
for(i=0;i < 3;i++){
printf("The average of row %d is %f",i,dAvg(array,3));
}
return 0;
}
double dAvg(double pt[][5],int rows){
int r,c;
double sum,avg;
//Calculate sum first
for (c=0,sum=0;c<5;c++){
sum += pt[r][c];
//Find average by dividing the sum by the number of numbers in a row
avg=sum/5;
return avg;
}
}
When I run the program, it just says that the program has stopped working, on top of that, I don't feel confident that I will actually work once that first issue is solved. I am quite new to multi-dimensional arrays and especially so for passing them to functions. Thanks again for any help!
Most errors were present in your dAvg function:
Namely:
You should not pass the entire 2D array if you only need one row there
You should pass the length of the array instead of hardcoding it everywhere (good practice, not a bug)
Your r was kept uninitialised therefore your indexing was not working
You were returning the average in every iteration therefore instead of summing the values you added the first and then you returned before adding the others.
double dAvg(double array[], size_t length){
size_t c;
double sum = 0;
// Calculate sum first
for (c = 0; c < length; c++){
sum += array[c];
}
// Find average by dividing the sum by the number of numbers in a row
return sum / (double) length;
}
int main(void){
int i;
//Initiallize array
double array[3][5] = {{3.0,5.0,2.0,1.0,0.0}, {4.0,8.0,6.0,3.0,3.0}, {7.0,6.0,2.0,3.0,5.0}};
//Computes the average value per row of array
for(i = 0; i < 3; i++){
printf("The average of row %d is %f\n", i, dAvg(array[i], 5));
}
return 0;
}

Using Malloc Arrays inside a for loop and an if statement in C - Leading to Segmentation

this is my first post, so sorry if it doesn't meet the standards in which I should post, if there are any issues with how I've placed the code just say and Ill take that into account for future posts. I tried to comment the code as much as possible, maybe a little too much.
So the idea of the code is to take a normal matrix in and then store it in reduced form, this works fine, but when I wish to also multiply this with with a vector it fails.
The code fails, since when I do the double for loop with an if statement it segments and I have no idea why.
It works fine if I specify the elements seperatly but then fails when I try to increment what elements it should select for Matrix_R when inside the if statement.
Any help would be greatly appreciated. Thanks !!
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i;
int j;
int n;
int m;
int k=0;
double * Vin;
double * Vout_M;
double * Vout_MR;
double ** Matrix;
double ** Matrix_R;
//Vout_M and Vout_MR are output vectors for the two possible inputted matricies
//Matrix_R is the reduced form of Matrix
n=4;
Vin = malloc(n*sizeof(double));
Vout_M = malloc(n*sizeof(double));
Vout_MR = malloc(n*sizeof(double));
Matrix = malloc(n*sizeof(double*));
for(i=0;i<n;i++)
Matrix[i] = malloc(n*sizeof(double));
//Allocates memory for the arrays
for(i=0;i<n;i++){
Vin[i]=1;
Vout_M[i]=0;
Vout_MR[i]=0;
}
//Initiates the vector arrays
for(i=0;i<n;i++)
for(j=0;j<n;j++)
Matrix[i][j]=0;
//Initiates the Matrix
Matrix[2][3]=5;
Matrix[0][2]=10;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(Matrix[i][j]!=0)
m++;
//Scans through to determine what size the reduced array should be
//In Future, this could be set up to read from a text file, and so RAM isn't used to store the array to find elements
Matrix_R = malloc(m*sizeof(double*));
for(i=0;i<m;i++)
Matrix_R[i] = malloc(3*sizeof(double));
for(i=0;i<m;i++)
for(j=0;j<3;j++)
Matrix_R[i][j]=0;
//Produces the reduced array, and initiates it
printf("\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(Matrix[i][j]!=0){
Matrix_R[k][0]=Matrix[i][j];
Matrix_R[k][1]=i;
Matrix_R[k][2]=j;
k++;
}
//Scans through the Matrix array and outputs to the Matrix_R array
for(i=0;i<k;i++)
printf("Matrix_R[%d][0] = %lf, Matrix_R[%d][1] = %lf, Matrix_R[%d][2] = %lf\n",i,Matrix_R[i][0],i,Matrix_R[i][1],i,Matrix_R[i][2]);
//Checks if it is storred correctly -- this outputs fine
//Now first do the multiplication between the normal matrix and vector --- Matrix * Vector
for(i=0;i<n;i++)
for(j=0;j<n;j++)
Vout_M[i] += Matrix[i][j]*Vin[j];
for(i=0;i<n;i++)
printf("\nVout_M[%d] = %lf",i,Vout_M[i]);
printf("\n");
//Prints the output from a standard Matrix * Vin in the form of Vout_M
k=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++){
if(i == Matrix_R[k][1] && j == Matrix_R[k][2]){
Vout_MR[i] += Matrix_R[k][0]*Vin[j];
k++;
}}
//Goes through standard matrix-vector multiplication, using reduced matrix
//SEGMENTS :: When trying to go through an if statement and incrementing k.
//i.e. If I set k=int, and then not increase it in the if statement it works.
for(i=0;i<n;i++)
printf("\nVout_MR[%d] = %lf",i,Vout_MR[i]);
printf("\n");
//Outputs the Vout_MR which is from Matrix_R * VIN
free(Vin);
free(Vout_M);
free(Vout_MR);
for(i=0;i<n;i++)
free(Matrix[i]);
for(i=0;i<m;i++)
free(Matrix_R[i]);
return 0;
}
In your code, you never initialized
int m;
and you're using the value uninitialized in
if(Matrix[i][j]!=0)
m++;
and
Matrix_R = malloc(m*sizeof(double*));
It produces a read-before-write scenario. The behaviour is not defined.
Also, always check for the return value of malloc() to ensure success.
You can [and should] use %f format specifier to print double values. Change
printf("\nVout_M[%d] = %lf",i,Vout_M[i]);
to
printf("\nVout_M[%d] = %f",i,Vout_M[i]);
Next, you've free()d all the Matrix[i] and Matrix_R[i] but you forgot to free() Matrix and Matrix_R themselves.
EDIT
In your code, there is no boundary check for the value k in
if(i == Matrix_R[k][1] && j == Matrix_R[k][2])
Once your k >= m, you'll be accessing out-of-bound memory invoking undefined behaviour. A side effect is segmentation fault.
Most likely, in your case, m is having a value 2, and when k becomes 2 via k++, the next access to i == Matrix_R[k][1] generates out-of-bound memory access.
for(i=0;i<n;i++)
for(j=0;j<n;j++){
if(i == Matrix_R[k][1] && j == Matrix_R[k][2]){
Vout_MR[i] += Matrix_R[k][0]*Vin[j];
k++;
}}
Here you keep incrementing k and there is no guarantee k<m so as you keep incrementing k there is a access Matrix_R[k][1] where k>m leading to UB

Problems displaying max & min values in 2D array

Hello I am trying to populate an array with random values between 0 and 10000, display each to the screen with their location then calculate max, min, and average value in addition to thier locations. I am having trouble displaying the results. Can someone please help?
Thank you!
#include <stdio.h>
#include<time.h>
#include<math.h>
int array [3][5];
int practice_array;
int i, row, col, max, min, sum, avg;
srand(time(NULL));
for ( row = 0; row < 2; row = row + 1){
for ( col = 0; col < 4; col = col +1){
array[row][col] = rand()%10000;
practice_array = array[row][col];
sum = array[row][col];
avg = sum / 15;
for(i =0; i< 8; i++){
printf("The value in row %d col %d is %d\n",row, col,practice_array);
}
}
}
for (i = 0; i < 8; i++){
max = array[0];
min = array[0];
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array [i];
}
}
printf("The max value is %d in row %d, col %d\n", max, row,col);
printf("The min value is %d in row %d, col %d \n", min, row,col);
return (0);
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define ROW 3
#define COL 5
int main(){
int array[ROW][COL];
int practice_array;
int i, row, col, max, min, sum, avg;
srand(time(NULL));
for ( row = 0; row < ROW; row = row + 1){
for ( col = 0; col < COL; col = col +1){
array[row][col] = rand()%(10000+1);
practice_array = array[row][col];
sum += practice_array;
printf("The value in row %d col %d is %d\n",row, col,practice_array);
}
}
avg = sum / (ROW*COL);//unused
int *pv = &array[0][0];
max = min = 0;
for (i = 1; i < ROW*COL; ++i){
if (pv[i] > pv[max])
max =i;
if (pv[i] < pv[min])
min = i;
}
printf("The max value is %d in row %d, col %d\n", pv[max], max/COL, max%COL);
printf("The min value is %d in row %d, col %d\n", pv[min], min/COL, min%COL);
return 0;
}
First you should really use defines for constants (array sizes, ...) like I've shown to you on the other thread otherwise your code is mess with magic numbers everywhere (for example in this code: 3, 5, 2, 4, 8, ...). And if you've to change a value, you need to change it everywhere; with a define you change it only once at one place.
Also, when it prints each values & location, they are duplicated 5 times before printing the next value this is because of this (completely useless) loop, just delete it and keep only the printf:
for(i =0; i< 8; i++){
printf("The value in row %d col %d is %d\n",row, col,practice_array);
}
For everything else, as far as I can see, you don't have fully understood how loops are working. I suggest you to learn the basics of the loops before trying to use them with arrays.
Also try to use step wise development by first building an array with simple numbers and printing it out. Then try adding random numbers to a specific location in each array position and so on with 2d stuff. It seems like you wrote down a bunch of code without stepping back and trying to run it a few times
After looking through you code I could see a few things that you still need to work on.
Don't forget all of that needs to be inside of the main method or the compiler will not know where to start. you will also need "#include <stdlib.h>" to get your srand to work.
If you try to find examples online on a simple srand being used, you will see what I mean. The variable sum is not finding the sum. You need to loop though all the locations and add them to the sum. It would then be easy to find the average using your method.
If you are looking to print out all of them, remember to also use that for loop and loop through every single location and print them out.

Resources