I have the following task: Create a 2d array A[M][N], where M and N are inputted by the user as well the elements in each row and column. There must also be two functions: 1)The first one needs to calculate the average of all positive numbers in the 2d array. This function works just fine, at least I think so.
2)Here is where my problem is and I simply ran out of options. The second function needs to create a new array B whose elements are the sums of the elements in each row in array A. After that it needs to print out array B.
The problem is as follows: Upon inputting 2 and 2 for M and N, as well as "2" for each of the elements in the 2x2 array (I have tried with 3 everywhere too), the second function should print out array B with elements "4 4". It, however, prints out 4 and 0. When trying 3 for every prompt it printed out the first element just fine-"9" the other 2 elements should also be 9, however the program just spewed some random numbers.
The code in question:
#include <stdio.h>
#include <math.h>
#include <string.h>
//1.
float average(int Y, int X, int A[Y][X]){
float sum=0;
float br=0;
int k,r;
for(k=0;k<Y;k++){
for(r=0;r<X;r++){
if(A[k][r]>0){
sum+=A[k][r];
br++;
}
}
}
if(br>0){
return sum/br;
}
else
{
return 0;
}
//2.
void SumArray(int arrA[10][10], int m, int n, int B[10][1]);
int main()
{
int i,j,M,N;
printf("INPUT ROWS:\n");
scanf("%d", &M);
getchar();
printf("INPUR COLUMNS:\n");
scanf("%d", &N);
getchar();
int A[M][N];
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
printf("INPUT A[%d][%d]:", i,j);
scanf("%d", &A[i][j]);
}
}
printf("\n");
printf("ARRAY A LOOKS LIKE SO:\n");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
printf("%d ", A[i][j]);
}
printf("\n");
}
int B[M][1];
for(i=0;i<M;i++)
{
B[i][0]=0;
}
//1.
float avg= average(M,N,A);
printf("THE AVARAGE OF ALL POSITIVE ELEMENTS IS:\n%f\n", avg);
//2.
printf("ARRAY B LOOKS LIKE SO:\n");
SumArray(A, M, N, B);
return 0;
}
//2.
void SumArray(int arrA[10][10], int m, int n, int B[10][1])
{
int i,j;
float sum;
for( i = 0; i < m; i++)
{
sum=0;
for( j = 0;j < n; j++)
{
sum+= arrA[i][j];
}
B[i][0]=sum;
}
for(i=0;i<m;i++){
printf(" %d ", B[i][0]);
}
}
What I tried (I am a beginner when it comes to programming): Making array B a 2D array (it was 1D in the beginning), Swapping B[10]
with B[m]
and B[n]
, different compilers.