Our teacher asks to manipulate and search through a 25x15 matrix to find the biggest elements in their own Row & Column: if the (i,j) element is bigger than the mean value of i row, and bigger than the mean value of j column, then we can increment the counter that we'll return from the given function. After we found all of these so-called "Important Points" we search in them for the biggest of all, and pass the value and its coordinates to the Main by using the pointers passed to the function to modify the original variables.
The core of the exercise is the function to implement, with the given arguments:
int Importants(int a[ROW][COL], int *mi, int *mj, int *max);
I preferred to use more little functions to call when needed, than to implement everything in a big block, so I created the functions to find the mean value of a given column and row, the biggest element in a row.
We tried to use a supplementary array to store the positions, to bypass the pointers requisite, which contains a triplet of (i,j coordinate + value); anyway I'm not sure it's the right way.
Here's the full source-code
/*
In a matrix, the (i,j) couple is considered "IMPORTANT" is its value is
Bigger Than the Mean Value of the i row && Bigger Than the Mean Value of the j column
The exercise is to create, aside from Create (in the given interval) and Print functions, a function
named "Importants" which returns the number of Important points of the matrix; then search in these points
which one is the biggest and returns its value and coordinates by using the pointers defined in the function call.
FUNCTION DEFINITION CAN NOT BE ALTERED
*/
//import libraries
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//constant defines
#define ROW 25
#define COL 15
#define MIN 3
#define MAX 47
//vector with (i,j) positions and their value: every 3 elements you have 'i' row number, 'j' column number, and 'k' or 'max' value
int positions[COL*3];
//matrix generation with no first row element equal to the previous and next one
void create_matrix(int mat[][COL]) {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
//first generation try
mat[i][j] = rand() % (MAX - MIN + 1) + MIN;
//checks
if ((mat[i][j] == mat[i-1][j]) && (mat[i][j] == mat[i+1][j]) && (i >= 1)) {
if (j > 0){
j--;
continue;
}
else {
continue;
}
}
else if ((mat[i][j] == mat[i+1][j]) && i >= 1) {
if (j > 0){
j--;
}
else {
continue;
}
}
}
}
puts("Matrix Generated.\n\n");
}
//generate a vector with all zeros to avoid mistakes
void zero_vector(int vector[]) {
for (int i = 0; i < COL*3;i++) {
vector[i] = 0;
}
}
//print matrix
void print_matrix(int mat[][COL]) {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("[ %2i ] ", mat[i][j]);
}
printf("\n");
}
}
//find max element in a given row
int max_in_row(int mat[][COL], int i) {
int max_value = 0, second_max = 0;
for (int r = i, c = 0; c < COL; c++) {
if (mat[r][c] > max_value) {
second_max = max_value;
max_value = mat[r][c];
}
}
return max_value;
}
//find max element in Positions vector
void max_in_positions_vector(int vector[]) {
int max_value = 0, second_max_value = 0;
for (int i = 2; i < COL*3; i=i+3) {
if (vector[i] > max_value) {
second_max_value = max_value;
max_value = vector[i];
}
}
printf("\n\nThe biggest of \'Important Positions\' is:\t%i", max_value);
}
//calculate mean value of a given row
int row_mean_value(int mat[][COL], int i, int j) {
int r_mean = 0, sum = 0;
for (int r = i, c = j; c < COL; c++){
sum += mat[r][c];
}
r_mean = sum / COL;
printf("\nMean value of Row %i:\t%i", i, r_mean);
return r_mean;
}
//calculate mean value of a given column
int column_mean_value(int mat[][COL], int i, int j) {
int c_mean = 0, sum = 0;
for (int r = i, c = j; r < ROW; r++){
sum += mat[r][c];
}
c_mean = sum / ROW;
printf("\nmedia colonna %i:\t%i", i, c_mean);
return c_mean;
}
int Importants(int a[ROW][COL], int *mi, int *mj, int *max){
int i = 0, j = 0, n_Importants = 0, max_value, k;
for (i,k = 0; i < ROW; i++) {
max_value = max_in_row(a, i);
//row_mean_value(a,i,j);
for (j = 0; j < COL; j++) {
if (max_value > row_mean_value(a,i,j) && max_value > column_mean_value(a,i,j)){
n_Importants++;
positions[k] = i;
positions[k+1] = j;
positions[k+2] = max_value;
k += 3;
//debug prints
printf("\nMax Value n. %i:\t%i", j, max_value);
printf("\ni = %i\tj = %i\tk = %i\n\n", i, j, k);
}
}
}
return n_Importants;
}
//main function
int main() {
srand(time(NULL));
int mat[ROW][COL];
int mi = 0, mj = 0, max = 0, *mi_p = &mi, *mj_p = &mj, *max_p = &max;
create_matrix(mat);
print_matrix(mat);
zero_vector(positions);
int n_Importants = Importants(mat, mi_p, mj_p, max_p);
max_in_positions_vector(positions);
return 0;
}
I've updated the k cycle to iterate every k+3 as suggested only inside the if block; As noted, mi, mj are not used, and that's part of the problem and why I chose to use an array of positions: the "Importants" function definition can not be altered, and so I would have to use the variable pointers. Also I've edited the call to the max_in_vector function to the correct max_in_row function name.
Updates
I've worked on it, removed the positions array and used the pointers to pass back the coordinates, by implementing a search in the matrix from within the Importants function; I've adjusted the search because I think I have to check every element, else it would only check for the maximum of the row && column. I don't know how to explain it well, so I'll post the updated code:
//imports
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//global constants
#define ROW 25
#define COL 15
#define MIN 3
#define MAX 47
//int posizioni[COL*3];
int importants_vect[ROW*COL];
//create matrix with no duplicates for the first element of 2 adjacent rows (a[i][j] != a[i-1][j] AND a[i][j] != a[i+1][j])
void create_matrix(int mat[][COL]) {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
mat[i][j] = rand() % (MAX - MIN + 1) + MIN;
if ((mat[i][j] == mat[i-1][j]) && (mat[i][j] == mat[i+1][j]) && (i >= 1)) {
if (j > 0){
j--;
continue;
}
else {
continue;
}
}
else if ((mat[i][j] == mat[i+1][j]) && i >= 1) {
if (j > 0){
j--;
}
else {
continue;
}
}
}
}
puts("Matrix Generated.\n\n");
}
void zero_vector_init(int vect[]) {
for (int i = 0; i < COL*3;i++) {
vect[i] = 0;
}
}
//print matrix function
void print_matrix(int mat[][COL]) {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("[ %2i ] ", mat[i][j]);
}
printf("\n");
}
}
/* void maxi_vect(int vect[]) {
int max_value = 0, second_max_value = 0;
for (int i = 2; i < COL*3; i=i+3) {
if (vect[i] > max_value) {
second_max_value = max_value;
max_value = vect[i];
}
}
printf("\n\nIl max_value tra i punti importants e':\t%i", max_value);
} */
//find the mean of a given row
int row_mean_value(int mat[][COL], int i, int j) {
int r_mean = 0, sum = 0;
for (int r = i, c = j; c < COL; c++){
sum += mat[r][c];
}
r_mean = sum / COL;
printf("\nrow mean = %i / %i >>> %i", sum, COL, r_mean);
return r_mean;
}
//find the mean value in a given column
int column_mean_value(int mat[][COL], int i, int j) {
int c_mean = 0, sum = 0, r = 0, c = j;
for (r = i; r < ROW; r++){
sum += mat[r][c];
}
c_mean = sum / ROW;
printf("\ncolumn mean = %i / %i >>> %i", sum, ROW, c_mean);
return c_mean;
}
int max_in_vector(int vect[]) {
int max_value = 0, second_max_value = 0;
for (int i = 0; i < ROW*COL; i++) {
if (vect[i] > max_value) {
second_max_value = max_value;
max_value = vect[i];
}
}
return max_value;
}
//search inside the matrix for a given value and communicate its coordinates by modifying pointers to variables
void search_in_matrix(int mat[][COL], int to_search, int *mi, int *mj) {
//row and col variables are used for completeness, else we could just work with pointers
int found = 0, found_row = 0, found_col = 0;
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
if (mat[i][j] == to_search) {
found = mat[i][j];
found_col = j;
found_row = i;
}
}
}
*mi = found_row;
*mj = found_col;
return;
}
int Importants(int a[ROW][COL], int *mi, int *mj, int *max){
//init variables, including the ones to modify coordinate pointers
int n_importants = 0, i_coord = 0, j_coord = 0, max_p = 0;
//init mean value variables
int r_mean = 0, c_mean = 0;
//init counters
int i = 0, j = 0, k = 0;
//traversing the matrix
for (i ; i < ROW; i++) {
//calculate the mean of the row we're in
r_mean = row_mean_value(a, i, j);
for (j , k; j < COL; j++, k++) {
//calculating the mean of the column we're in
c_mean = column_mean_value(a, i, j);
//check for Important Point: a[i][j] MUST BE STRICTLY GREATER than r_mean and c_mean
if (a[i][j] > r_mean && a[i][j] > c_mean) {
//increment n_importants counter and fill the supplementary array with the value
n_importants++;
importants_vect[k] = a[i][j];
}
else continue;
}
//reinit j to 0. There are problems in print if not. Still don't know why
j = 0;
}
//search for the max in the supplementary array then search for its coordinates in the matrix
//and pass them back to the coordinate pointers
max_p = max_in_vector(importants_vect);
search_in_matrix(a, max_p, mi, mj);
return n_importants;
}
int main() {
srand(time(NULL));
int mat[ROW][COL];
int mi = 0, mj = 0, max = 0;
create_matrix(mat);
print_matrix(mat);
//zero_vector_init(posizioni);
zero_vector_init(importants_vect);
int n_importants = Importants(mat, &mi, &mj, &max);
//maxi_vect(posizioni);
int max_value = max_in_vector(importants_vect);
//int search = search_in_matrix(mat, max_value);
printf("\n\nThere are %i Important Points inside the matrix", n_importants);
printf("\n\nThe max among Important Points is\t%i\n", max_value);
printf("It's found on the row n°\t%i\n", mi);
printf("And on column n°\t%i\n\n", mj);
//printf("media: %.2f", med);
return 0;
}
Related
Im trying to sort a matrix by the sum of its row's digits, from highest to lowest. I dont know if i explained that correctly so here's some photos explaining it.
This is what my code outputs. Basically, it asks you for m and n, which are the dimensions of the matrix. In this example it's a 3x4, 3 rows and 4 columns. Then, the matrix should be sorted by rows, by the sum of row's digits. Which means, instead of what's being outputted in the picture above, the correct result should be this:
I have no idea how to sort this from highest to lowest, i have been trying for hours to no avail.
Here's my code:
#include <stdio.h>
#define N 30
void main(){
double a[N][N], s[N], p;
int i, j, m, n, max;
while(1){
printf("\nm, n? ");
scanf("%d%d", &m, &n);
if(m <= 0 || m > N || n <=0 || n > N)
break;
for(i = 0; i < m; i++){
printf("%2d. row? ", i+1);
for(j = 0; j < n; scanf("%lf", &a[i][j++]));
}
for(i = 0; i < m; i++)
for(s[i] = j = 0; j < n; s[i] += a[i][j++]);
for(j = 0; j < n - 1; j++){
for(max = i, j = i+1; j < n; j++)
if(s[j] > s[max])
max = i;
if(max != j){
p = s[j];
s[j] = s[max];
s[max] = p;
for(j = 0; j < m; j++){
p = a[j][i];
a[j][i] = a[j][max];
a[j][max] = p;
}
}
}
printf("New matrix: \n");
for(i = 0; i < m; i++){
for(j = 0; j < n; printf("%8.2lf", a[i][j++]));
printf("\n");
}
for(j = 0; j < m; j++)
printf("-------------");
printf("\n");
for(j = 0; j < m; printf("%8.2f \n", s[j++]));
printf("\n");
}
}
You can sort the rows of the matrix from highest to lowest, using a simple bubble sort algorithm.Your code modified below:
int main() {
double a[N][N], s[N], p;
int i, j, m, n, max;
while (1) {
printf("\nm, n? ");
scanf("%d%d", & m, & n);
if (m <= 0 || m > N || n <= 0 || n > N)
break;
for (i = 0; i < m; i++) {
printf("%2d. row? ", i + 1);
for (j = 0; j < n; scanf("%lf", & a[i][j++]));
}
for (i = 0; i < m; i++)
for (s[i] = j = 0; j < n; s[i] += a[i][j++]);
for (i = 0; i < m - 1; i++) { // modified here
for (j = i + 1; j < m; j++) { // modified here
if (s[j] > s[i]) { // modified here
p = s[i];
s[i] = s[j];
s[j] = p;
for (int k = 0; k < n; k++) {
p = a[i][k];
a[i][k] = a[j][k];
a[j][k] = p;
}
}
}
}
printf("New matrix: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; printf("%8.2lf", a[i][j++]));
printf("\n");
}
for (j = 0; j < m; j++)
printf("-------------");
printf("\n");
for (j = 0; j < m; printf("%8.2f \n", s[j++]));
printf("\n");
}
return 0;
}
Here's how i modified your code to achieve that:
Initialize a loop variable i to 0.
In the outer loop, run the inner loop j from i+1 to m-1.
In the inner loop, compare the sum of the row i with the sum of row
j. If the sum of row j is greater than the sum of row i, swap the
rows using a temporary variable.
After the inner loop finishes, increment the value of i by 1. Repeat
the outer loop until i becomes equal to m-1.
Output:
You can just use qsort to let it handle the sorting and item swapping. Then you only need to write the code for comparing two rows with each other.
Given something like this:
int matrix[3][4] =
{
{1,2,3,4},
{5,6,7,8},
{9,1,2,3},
};
You'd call qsort as:
qsort(matrix, 3, sizeof(int[4]), compare);
The only complexity is implementing the comparison callback function. There's two things to consider there:
We've told qsort that we have an array of 3 items, each of type int[4]. So the void pointers it passes along to us will actually be pointers to type int[4]. That is: int(*)[4].
qsort sorts in ascending order by default, where the item considered "less" ends up first. So we need to tweak that to get the largest item first.
Example:
int compare (const void* obj1, const void* obj2)
{
const int (*ptr1)[4] = obj1;
const int (*ptr2)[4] = obj2;
size_t sum1=0;
size_t sum2=0;
for(size_t i=0; i<4; i++)
{
sum1 += (*ptr1)[i];
sum2 += (*ptr2)[i];
}
if(sum1 > sum2) // largest sum considered "less" for qsort
return -1;
else
return 1;
return 0;
}
sum1 < sum2 would have placed the smallest row first.
Full example:
#include <stdio.h>
#include <stdlib.h>
int compare (const void* obj1, const void* obj2)
{
const int (*ptr1)[4] = obj1;
const int (*ptr2)[4] = obj2;
size_t sum1=0;
size_t sum2=0;
for(size_t i=0; i<4; i++)
{
sum1 += (*ptr1)[i];
sum2 += (*ptr2)[i];
}
if(sum1 > sum2) // largest sum considered "less" for qsort
return -1;
else
return 1;
return 0;
}
void print_matrix(size_t col, size_t row, int matrix[col][row])
{
for(size_t i=0; i<col; i++)
{
for(size_t j=0; j<row; j++)
{
printf("%d,", matrix[i][j]);
}
puts("");
}
}
int main (void)
{
int matrix[3][4] =
{
{1,2,3,4},
{5,6,7,8},
{9,1,2,3},
};
print_matrix(3,4,matrix);
puts("");
qsort(matrix, 3, sizeof(int[4]), compare);
print_matrix(3,4,matrix);
}
My code is this:
#include <stdio.h>
int array_second_positive(int A[], int size) {
int j, i;
for (i = 0; i < size / 2; ++i) {
A[i] = A[0];
for (j = 0; j < size; ++j) {
A[j] = A[j + 1];
}
}
for (i = 0; i < size; ++i) {
int z = 0;
int counter = 0;
while (z < size) {
if (A[z] > 0) {
counter++;
}
if (counter == 2) {
return A[z];
}
z++;
}
}
}
int main(void) {
int size = 6;
int array[] = { 3, -14, 15, 2, 6, 5 };
int result = array_second_positive(array, size);
}
I am trying to find the second positive number in the second half of an array. If we assume array size is even and we have definitely at least two positive number in the second half but I get no results.
#i want to find the max value of each row, i already created an array in the main of size[5][2], and i want to find the max value for each column#
void
maximum(int a[5][2])
{
int max = a[0][0];
int i, j;
for (i = 0; i < 2; i++) {
int max = a[0][i];
for (j = 0; j < 5; j++)
if (a[j][i] > max)
max = a[j][i];
}
printf("Maximum of 1st column= %d \n", max);
for (i = 0; i < 2; i++) {
int max = a[1][i];
for (j = 0; j < 5; j++)
if (a[j][i] > max)
max = a[j][i];
}
printf("Maximum of 2st column= %d \n", max);
max = a[0][0];
for (i = 0; i < 2; i++) {
for (j = 0; j < 5; j++) {
if (a[i][j] > max)
max = a[i][j];
}
}
printf("Maximum of all %d \n", max);
}
You're doing it the opposite way. [0][i] is the first row, not the first column. You must do it like [i][0] and [i][1], and same for the j. It's max=a[i][j].
Doing like like you say only checks the max of the first and second row, leaving the other three unchecked. Hope it helps.
You need to choose carefully the indeces and their order.
#include <stdio.h>
#include <stdlib.h>
void show_max(int rows, int cols, int mat[rows][cols])
{ // ^^^^ ^^^^ ^^^^^^^^^^^^^^^ VLA notation
// Traverse the array row-major order
for (int r = 0; r < rows; ++r)
{
int max = mat[r][0];
// ^^^^ First element of row r
for (int c = 1; c < cols; ++c)
{
if (mat[r][c] > max)
max = mat[r][c];
// ^^^^
}
printf("Max of ROW %d: %d\n", r, max);
}
int max_global = mat[0][0];
// Traverse the array in colmun-major order
for (int c = 0; c < cols; ++c) // <--
{
int max = mat[0][c];
// ^^^^ // First element of column c
for (int r = 1; r < rows; ++r) // <--
{
if (mat[r][c] > max)
max = mat[r][c];
// ^^^^
}
printf("Max of COLUMN %d: %d\n", c, max);
// This could be in the first nested loop.
if (max > max_global)
max_global = max;
}
printf("Max ELEMENT: %d\n", max_global);
}
int main(void)
{
int mat[5][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}};
show_max(5, 2, mat);
}
How do I get to write to 2D pointers where I have pnumber[2%4][2%4] and how can I get pnumber with more than 3 ciphers to be displayed?
I'm making a program to write pascals triangle in C.
When the pointer pnumbers[i][j] have both i and j = 2 mod 4, except for when i and j = 2, then my program won't write to the address and give the error message:
pascals triangle: malloc.c:2406: sysmalloc: Assertion '{old_top == initial_top (av) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int factorial(int p) {
if (p>=1) {
return p*factorial(p-1);
}
else {
return 1;
}
}
int NchooseM(int n, int m) {
return factorial(n)/(factorial(n-m)*factorial(m));
}
int main() {
int n =7;
int x = n-2;
int i, j, k;
/*
printf("How many rows of Pascals triangle do you want to write?\n");
scanf("%d", &n);
*/
int **pnumbers;
pnumbers = (int **) malloc(n *sizeof(int *));
/* Allocate memory for storing the individual elements in a row */
for (i = 0; i < n; i++) {
pnumbers[i] = (int *) malloc(i * sizeof(int));
}
pnumbers[0][1] = 1;
/* Calculating the value of pnumbers[k][l] */
for (i = 0; i < n; i++) {
for (j = 0; j <= i; j++) {
pnumbers[i][j] = NchooseM(i,j);
}
/*
if (!(i % 4 == 2 && i != 2))
for (j = 0; j <= i; j++) {
pnumbers[i][j] = NchooseM(i,j);
} else if (i > 2) {
for (j = 0; j <= i-1; j++) {
pnumbers[i][j] = NchooseM(i,j);
}
}
*/
}
/* Writing out the triangle */
for (i = 0; i < n; i++) {
for (k = 0; k <= x; k++){
printf(" ");
}
for (j = 0; j <= i; j++) {
printf("%d ", pnumbers[i][j]);
}
x = x-1;
printf("\n");
}
for (i = 0; i < n; i++) {
free(pnumbers[i]);
}
free(pnumbers);
return 0;
}
When I avoid writing to these addresses and just print them out I get some seemingly random integer at these memory addresses.
Also when avoid these addresses and just print out so many rows that I get some spots with a higher integer with more than 3 siphers, it seems to overflow - and I don't see the logic behind it.
The result of running the second code
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int factorial(int p) {
if (p>=1) {
return p*factorial(p-1);
}
else {
return 1;
}
}
int NchooseM(int n, int m) {
return factorial(n)/(factorial(n-m)*factorial(m));
}
int main() {
int n =20;
int x = n-2;
int i, j, k;
/*
printf("How many rows of Pascals triangle do you want to write?\n");
scanf("%d", &n);
*/
int **pnumbers;
pnumbers = (int **) malloc(n *sizeof(int *));
/* Allocate memory for storing the individual elements in a row */
for (i = 0; i < n; i++) {
pnumbers[i] = (int *) malloc(i * sizeof(int));
}
pnumbers[0][1] = 1;
/* Calculating the value of pnumbers[k][l] */
for (i = 0; i < n; i++) {
/*
for (j = 0; j <= i; j++) {
pnumbers[i][j] = NchooseM(i,j);
}
*/
if (!(i % 4 == 2 && i != 2))
for (j = 0; j <= i; j++) {
pnumbers[i][j] = NchooseM(i,j);
} else if (i > 2) {
for (j = 0; j <= i-1; j++) {
pnumbers[i][j] = NchooseM(i,j);
}
}
}
/* Writing out the triangle */
for (i = 0; i < n; i++) {
for (k = 0; k <= x; k++){
printf(" ");
}
for (j = 0; j <= i; j++) {
printf("%d ", pnumbers[i][j]);
}
x = x-1;
printf("\n");
}
for (i = 0; i < n; i++) {
free(pnumbers[i]);
}
free(pnumbers);
return 0;
}
But row number 13 is still quite messed up.
Code is experiencing int overflow and thus undefined behavior (UB).
With 32-bit int and int factorial(int p), p > 12 oveflows the int range.
Code could use a wider integer type (long long works up to p==20), but improvements can be made at NchooseM() to avoid overflow for higher values.
Something like the below. Works up to int n = 30;
int NchooseM(int n, int m) {
// return factorial(n)/(factorial(n-m)*factorial(m));
int nm = 1;
int den = 1;
for (int i = m+1; i <= n; i++) {
assert(INT_MAX/i >= nm);
nm *= i;
assert(nm % den == 0);
nm /= den++;
}
return nm;
}
Tried unsigned long long and works up to int n = 62;
Edit: Another bug:
I "fixed" by initializing all to 1, yet I suspect something remains amiss in /* Calculating the value of pnumbers[k][l] */ for (i = 0; i < n; i++) { code.
pnumbers[i] = malloc((i + 1) * sizeof pnumbers[i][0]);
for (int j = 0; j < i + 1; j++) {
pnumbers[i][j] = 1;
}
Aside: rather than pnumbers[i] = (int *) malloc((i+1) * sizeof(int));, consider below with no unneeded cast nor trying to match the right type.
pnumbers[i] = malloc(sizeof pnumbers[i][0] * (i+1));
I am trying to write a C program to find if the sum of the elements in the middle three rows equals to sum of elements in the middle three columns of matrix print. So far am able to find the sum of all the columns and rows in the matrix.
#include<stdio.h>
void main()
{
static int array[10][10];
int i, j, m, n,sum = 0;
printf("Enter the order of the matrix\n");
scanf("%d %d", &m, &n);
if (m>=5&& n>=5)
{
printf("Enter the elements of the matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
}
}
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
sum = sum + array[i][j] ;
}
printf("Sum of the %d row is = %d\n", i, sum);
sum = 0;
}
sum = 0;
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
sum = sum + array[i][j];
}
printf("Sum of the %d column is = %d\n", j, sum);
sum = 0;
}
}
else
{
printf("The matrix should be a 5 by 5 or bigger");
}
}
Try this
int mid1 = (m-3)/2;
int mid2 = (n-3)/2;
int sum1=0,sum2=0;
//suppose m is 9 index(0-8), so this for loop will add the index 3,4,5
for(i=mid1; i<mid1+3; i++)
{
for(j=0; j<n; j++)
{
sum1+=array[i][j];
}
}
for(i=0; i<m; i++)
{
for(j=mid2; j<mid2+3; j++)
{
sum2+=array[i][j];
}
}
if(sum1==sum2)
//equal
else
//not equal
Let's assume that the array has n rows and m columns. In this case you can calculate the sums of middle three rows and columns the following way
if ( n >= 3 && m >= 3 )
{
int k = ( n - 3 ) / 2;
int l = ( m - 3 ) / 2;
int cols_sum = 0;
int rows_sum = 0;
for ( i = k; i < k + 3; i++ )
{
for ( j = 0; j < m; j++ ) rows_sum += array[i][j];
}
for ( i = 0; i < n; i++ )
{
for ( j = l; j < l + 3; j++ ) cols_sum += array[i][j];
}
if ( rows_sum == cols_sum ) /* print appropriate message */;
}
Here is a demonstrative program
#include <stdio.h>
#define N 3
#define M 3
#define RANGE 3
int main( void )
{
int array[N][M] =
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
size_t n = N;
size_t m = N;
if ( n >= RANGE && m >= RANGE )
{
size_t k = ( n - RANGE ) / 2;
size_t l = ( m - RANGE ) / 2;
size_t i, j;
int cols_sum = 0;
int rows_sum = 0;
for ( i = k; i < k + RANGE; i++ )
{
for ( j = 0; j < m; j++ ) rows_sum += array[i][j];
}
for ( i = 0; i < n; i++ )
{
for ( j = l; j < l + RANGE; j++ ) cols_sum += array[i][j];
}
if ( rows_sum == cols_sum )
{
printf( "The sums of three middle rows and columns are equal "
"each other and have value %d\n", rows_sum );
}
else
{
printf( "The sums of three middle rows and columns are not equal "
"each other.\n"
"The sum of the rows has value %d "
"and the sum of the columns has value %d\n",
rows_sum, cols_sum );
}
}
return 0;
}
The output is
The sums of three middle rows and columns are equal each other and have value 45
Now all what you need is to provide the appropriate dimensions of the array and the user input of the data.
In you code you are asking user for row and column count, but you have already decided on that, moreover you cannot create a array dynamically with user input. However, there are ways you can work with to create arrays based on users request, we have Dynamic Memory Allocation concept to the rescue. For for time being, work with predefined size.
How to get row Data
In c, you have to fix on a row as i, in array[i][j] i is row and j is column reference, and loop through j to get all the row element values
How to get Column Data
same as above, loop through i and fix on j, exactly opposite.
#include<stdio.h>
int main()
{
/*This code works for only odd numbers and you have to make necessary changes to accommodate for even number of rows and columns*/
const int row = 5, colmn = 5;
static int array[row][colmn];
int i, j, m, n,sumRow = 0, sumColmn = 0;
int middleRow = row / 2, middleColmn = colmn / 2;
int howManyRows = 3;
printf("Enter the elements of the matrix\n");
/*
* first get elements from user
*/
for (i = 0; i < row; ++i)
{
for (j = 0; j < colmn; ++j)
{
printf("[%d][%d]",i,j);
scanf("%d", &array[i][j]);
}
}
/*
* printing elements to cross check the output
*/
for (i = 0; i < row; ++i)
{
for (j = 0; j < colmn; ++j)
{
printf("%d\t",array[i][j]);
}
printf("\n");
}
/*
* logic : get rows to adds (outer loop will loop through the rows to consider)
* inner loop is to get all the elements in each row
*/
for(int threeRows = 0 - howManyRows/2 ; threeRows <= howManyRows/2 ;threeRows++)
{
for (j = 0; j < row; ++j)
{
sumRow += array[j][middleColmn + threeRows];
}
}
/*
* its the same as above just the opposite
*/
for(int threeColmn = 0 - howManyRows/2; threeColmn <= howManyRows/2 ;threeColmn++)
{
for (j = 0; j < row ; ++j)
{
sumColmn += array[middleColmn + threeColmn][j];
}
}
printf("middleRow = %d middleColmn = %d sumRow = %d sumColmn = %d",middleRow, middleColmn,sumRow,sumColmn);
if(sumRow == sumColmn) printf("\nThey are equal");
else printf("\nnot equal");
return 0;
}