Values in array getting altered yet they shouldn't - arrays

It's a program that requires the user to enter the values of two 3 by 3 matrix then finds the sum of both matrices and prints out the same together with the added matrices but for some reason after entering the values of both matrices the a value in matrix gets altered then it affects the sum but at times it doesn't
#include<stdio.h>
void main(){
int matrix1[2][2];
int matrix2[2][2];
int sumMatrix[2][2];
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
printf("Matrix[%d][%d]\n", i, j);
printf("Enter matrix one's values> ");
scanf("%d", &matrix1[i][j]);
}
printf("\n");
}
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
printf("Matrix[%d][%d]\n", i, j);
printf("Enter matrix two's values> ");
scanf("%d", &matrix2[i][j]);
}
printf("\n");
}
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
printf("%d ", matrix1[i][j]);
}
printf("\n");}
printf("\n");
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
printf("%d ", matrix2[i][j]);
}
printf("\n");}
printf("\n");
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
printf("%d ", sumMatrix[i][j]);
}
printf("\n");
}
}

You're declaring matrixes of size 2x2 and access them as if they were 3x3. What's happening more precisely is a buffer overflow, you write somewhere you shouldn't, and by doing so you overwrite other variables.

Lad, that is array overflow.
int matrix1[2][2];
But in the loop, you may get matrix1[2][1], matrix1[2][2].

Ok so clearly I'm the idiot. I thought array sizes are set based on the number of indices they'll have, so instead of int matrix1[2][2] it should be int matrix [3][3]

Related

Matrix with the diagonal set to 0, and the rest of the elements set from 1 to n (in C)

Firstly, a number N has to be input, and the matrix is of NxN dimensions then. The diagonal of the matrix has to be all 0, the elements of the matrix above the diagonal have to be from 1 to N diagonally, and the elements under the diagonal need to be filled from -1 to -N also diagonally. It should be something like this (if N=5):
But the problem that I have is that I print it out like this:
and I don't know how to fix it.
This is the code that I have:
`#include <stdio.h>
int main() {
int matrix[50][50], i, j, N;
printf("N: ");
scanf("%d",&N);
int k=0;
for(i=0; i<N; i++){
for(j=0; j<N; j++){
if(i==j){
matrix[i][j]=0;
}
else if(j>i && i!=j){
for(k=0; k<N; k++){
matrix[k-1][j]=k;
}
}
else if(j<i && i!=j){
for(k=0; k<N; k++){
matrix[i][k-1]=-k;
}
}
}
}
printf("Matrix:\n");
for (i=0; i<N; i++) {
for (j=0; j<N; j++)
printf("%4d", matrix[i][j]);
printf("\n");
}
return 0;
}`
I would really appreciate the help.
Here is you code modified, notice that 3 inner loops are removed with only one line.
second, you ask for the number N, however due to statically initialisation to maximum 50, you should as well verify that it is not. otherwise segmentation fault will happen.
or if you want to allow N >50 then better to do dynamic allocation on matrix.
#include <stdio.h>
int main() {
int matrix[50][50], i, j, N;
printf("N: ");
scanf("%d", &N);
if (N > 50){
printf("N should be smaller than 50, \n");
N = 50;
}
for(i=0; i<N; i++){
for(j=0; j<N; j++){
matrix[i][j]= j - i;
}
}
printf("Matrix:\n");
for (i=0; i<N; i++) {
for (j=0; j<N; j++)
printf("%4d", matrix[i][j]);
printf("\n");
}
return 0;
}

Error in calculating resultant matrix in C programming language

I am trying to write a program where I have two matrices and I multiply the two matrices and store it in a resultant matrix named "carr." For some weird reason, the matrix multiplication is not getting executed properly. Tried to find the issue for quite a while but couldn't find the error. Can anyone help? TIA for your time!
Here is the ss of the issue: https://snipboard.io/s9ifP4.jpg
#include <stdio.h>
int main()
{
int row1, column1, row2, column2,i,j,k, sum=0;
//START OF THE 1ST ARRAY//
printf("How many rows do you want for the first matrix? Ans: ");
scanf("%d", &row1);
printf("How many columns do you want for the first matrix? Ans: ");
scanf("%d", &column1);
int arr[row1][column1];
printf("Enter the elements of the first array:\n");
for(i = 0; i <row1; i++){
for(j=0; j < column1; j++){
scanf("%d", &arr[i][j]);
}
}
printf("\n----------------------------------------\n");
printf("The elements of the first array are:\n");
for(i = 0; i <row1; i++){
printf("[ ");
for(j=0; j < column1; j++){
printf("%d, ", arr[i][j]);
}
printf("]\n");
}
//END OF THE FIRST ARRAY//
printf("----------------------------------------\n");
//START OF THE 2ND ARRAY//
printf("\n**How many rows do you want for the second matrix?\n\nAlert: For matrix multiplication, the COLUMN of the 1st matrix MUST equal to the ROW of the 2nd matrix.\nAns: ");
scanf("%d", &row2);
printf("How many columns do you want for the second matrix? Ans: ");
scanf("%d", &column2);
int barr[row2][column2];
printf("Enter the elements of the second array:\n");
for(i = 0; i <row2; i++){
for(j=0; j < column2; j++){
scanf("%d", &arr[i][j]);
}
}
printf("\n----------------------------------------\n");
printf("The elements of the second array are:\n");
for(i = 0; i <row2; i++){
printf("[ ");
for(j=0; j < column2; j++){
printf("%d, ", arr[i][j]);
}
printf("]\n");
}
printf("----------------------------------------\n");
//END OF THE 2ND ARRAY//
//Everything above this part is okay. The problem starts from the Matrix multiplication part//
//MATRIX MULTIPLICATION//
//The resultant matrix where the values of the multiplied matrix is being held has row = ROW1 and column = COLUMN2.//
int carr[row1][column2];
if(column1 == row2)
{
for(i = 0; i < row1; i++){
for(j=0; j < column2; j++){
for(k=0; k < row2; k++){
sum = sum + arr[i][k] * barr[k][j];
}
carr[i][j] = sum;
sum=0;
}
}
}
else
{
printf("Matrix multiplication is not possible");
}
printf("\n----------------------------------------\n");
printf("The elements of the resultant array are:\n");
for(i = 0; i <row1; i++){
printf("[ ");
for(j=0; j < column2; j++){
printf("%d, ", carr[i][j]);
}
printf("]\n");
}
printf("----------------------------------------\n");
return 0;
}
Changing arr to barr fixes the issue. Thanks to #M Oehm for pointing out the error.

Why this function is not showing the correct result as output?

The output of this function everytime is:
The row with minimal sum is 1 whose sum is 0.
But I want it to calculate the sum of each row and then display the min row with its sum.
It displays the correct result if I use this code as a program, and not inside the function(as in this case).
void findRowWithMinimalSum(int row, int col, int A[row][col]){
int i,j,sum,minSum,position;
for(i=0; i<row; i++){
printf("\nGive the elements of row %d:\n", i+1);
for(j=0; j<col; j++)
scanf("%d", &A[i][j]);
}
for(i=0; i<row; i++){
for(j=0; j<col; j++)
printf("%d", A[i][j]);
printf("\n");
}
for(i=0; i<row; i++){
sum=0;
for(j=0; j<col; j++){
sum = sum + A[i][j];
}
if(sum<minSum){
minSum = sum;
position = i;
}
}
printf("\nThe row with minimal sum is %d whose sum is %d", position+1, minSum);
}
int main(){
int row, column, m[50][50];
//function call
findRowWithMinimalSum(3,3,m);
return 0;
}
Look carefully at minSum. You don't explicitly initialize it before using it in this test:
if (sum < minSum)
Therefore, if you're running a debug build and it gets initialized to zero, it'll never change unless sum is < 0.
Note that referencing an uninitialized value is undefined behavior, something that should be avoided at all costs.
Try this entering all numbers as negative.
Try setting it to INT_MAX and try again. Note that this is the correct solution to the problem.
As another editorial remark, it's probably not a good idea to modify the dimensions of the array. As declared in main() m is 50 by 50. But you're effectively viewing it as 3 by 3 in findRowWithMinimalSum(). That's not a good habit to get into, I can pretty much guarantee that doing so will cause problems for you at some point in the future.
Finally get yourself a debugger. This would have jumped right off the screen at you if you'd single stepped through findRowWithMinimalSum() watching how the variables change as the program progresses.
this will work
#include<stdio.h>
void findRowWithMinimalSum(int row, int col, int A[row][col]){
int i,j,sum,minSum,position;
for(i=0; i<row; i++){
printf("\nGive the elements of row %d:\n", i+1);
for(j=0; j<col; j++)
scanf("%d", &A[i][j]);
}
for(i=0; i<row; i++){
for(j=0; j<col; j++)
printf("%d", A[i][j]);
printf("\n");
}
for(i=0; i<row; i++){
sum=0;
for(j=0; j<col; j++){
sum = sum + A[i][j];
}
if(i==0){
minSum = sum;
position = i;
}
else if(sum<minSum){
minSum = sum;
position = i;
}
}
printf("\nThe row with minimal sum is %d whose sum is %d", position+1, minSum);
}
int main(){
int row, column, m[50][50];
//function call
findRowWithMinimalSum(3,3,m);
return 0;
}
void findRowWithMinimalSum(int row, int col, int A[50][50])
{
int i,j,sum=0,minSum=0,position,f=0;
for(i=0; i<row; i++){
printf("\nGive the elements of row %d:\n", i+1);
for(j=0; j<col; j++)
scanf("%d", &A[i][j]);
}
for(i=0; i<row; i++){
for(j=0; j<col; j++)
printf("%d ", A[i][j]);
printf("\n");
}
for(i=0; i<row; i++){
sum=0;
for(j=0; j<col; j++){
sum = sum + A[i][j];
}
if(f==0)
{
minSum=sum;
f++;
}
if(sum<minSum){
minSum = sum;
position = i;
}
}
printf("\nThe row with minimal sum is %d whose sum is %d", position+1, minSum);
}
int main(){
int row, column, m[50][50];
//function call
indRowWithMinimalSum(3,3,m);
return 0;
}

Last element of one array overwritten by first element of the next array

I have been working on a problem that involves the multiplication of two matrices and I have to get the elements from the user. However, after getting the elements when I print them the last element of the fist matrix is equal to the first element of the second matrix. As a result I am not getting the correct results. I will be obliged if anyone could help. Thanks.
#include<stdio.h>
int main(){
int i, j, k, n;
// get the size of the square matrices from user
scanf("%d", &n);
// allogate memory for the matrices
int * mul_1 = calloc(n, sizeof(int));
int * mul_2 = calloc(n, sizeof(int));
int * mul_3 = calloc(n, sizeof(int));
//get data from user
for(i=0; i<n; i++){
for(j=0; j<n; j++){
scanf("%d", mul_1+n*i+j);
}
}
for(i=0; i<n; i++){
for(j=0; j<n; j++){
scanf("%d", mul_2+n*i+j);
}
}
// display matrices
printf("Entered matrices are:\n =First=\n");
for(i=0; i<n; i++){
for(j=0; j<n; j++){
printf("%d\t", *(mul_1+n*i+j));
}
printf("\n");
}
printf("=Second=\n");
for(i=0; i<n; i++){
for(j=0; j<n; j++){
printf("%d\t", *(mul_2+n*i+j));
}
printf("\n");
}
//begin matrix multiplicaition
for(i=0; i<n; i++){
for(j=0; j<n; j++){
int sum = 0;
for(k=0; k<n; k++){
int a = *(mul_1 + n*i + k);
int b = *(mul_2 + n*k + j);
sum += a*b;
}
*(mul_3 + i*n + j) = sum;
}
}
//display results
printf("Result:\n");
for(i=0; i<n; i++){
for(j=0; j<n; j++){
printf("%d\t", *(mul_3+n*i+j));
}
printf("\n");
}
return 0;
}
You don't allocate enough space (n) for mul_1, mul_2 and mul_3 which seems to be n*n matrices.
You can use valgrind to detect this kind of errors.

C finding maximum number in a row of 2D array and replacing it with elements in the upper triangle

Basically i want to create a 2 dimensional array size NxN, find the maximum value in each row and replace it in the upper triangle or rather replace the elements with the maximum it for that specific row, but above the diagonal.
#include <stdio.h>
#include <stdlib.h>
#define MAXIMUM 100
int main()
{
int n, i, j, temp,m;
float a[MAXIMUM][MAXIMUM], max;
printf("dimensions: ");
scanf("%d",&n);
printf("input elements\n");
for (i=0; i<n; i++){
for (j=0; j<n; j++){
scanf("%f",&a[i][j]);
}
}
max=a[0][0];
for (i=0; i<n; i++){
for (j=0; j<n; j++)
{
if(max<a[i][j]){
max=a[i][j];
}
for(m=0;m<n;m++) //the problem starts here
{
if(max>a[i][m]){
if(i+m>n-1){
a[i][m]=max;
}
}
}
}
}
for(i = 0; i < n; i++) {
printf("\n");
for(j = 0; j < n; j++) {
printf("%f ", a[i][j]);
}
}
return 0;
}
J loop finishes every times, then m loop starts so the value of j is n-1 when it is in m loop.That is a problem.
maybe like this
for (i=0; i<n; i++){
max=a[i][0];
for (j=1; j<n; j++){
if(max<a[i][j]){
max=a[i][j];
}
}
for(m=i;m<n;m++){
a[i][m]=max;
}
}

Resources