Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I wrote my code and tried compiling in Codeblocks but it is not working. While running the programming it was showing errors in "int det(, )". I also tried using "*a" but it did not work. All it does is ask me the size of the matrix and the values and then stops. I am writing the full program but I believe the error is in the part of int det(int n, int a[][]).
#include<math.h>
main()
{
int n,i,j;
printf("enter the size of the matrix");
scanf("%d", &n);
int a[n][n];
printf("enter the matrix \n");
for (i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
printf(" \n");
scanf("%d", &a[i][j]);
}
}
printf("%d determinant is", det(a,n));
}
int det( int a[][n],int n)
{
int i, j,k,d,l=0 ;
if(n=2)
{
d = a[0][0]*a[1][1] - a[0][1]*a[1][0];
return (d);
}
else
for ( k = 0; k < n ; k++ )
{
int b[n-1][n-1];
for (i=1; i<n; i++)
{
for(j=0 && j!=k ; j<n; j++)
{
b[i][j]=a[i][j];
}
}
l = a[0][j]*pow(-1,j)*det(b,n-1)+l;
}
return(l);
}
Update:
Updated code:
#include<math.h>
#include<stdio.h>
int det( int n, int a[][n]);
int main(void)
{
int n,i,j;
printf("enter the size of the matrix ");
scanf("%d", &n);
int a[n][n];
printf("enter the matrix \n");
for (i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
printf(" ");
scanf("%d", &a[i][j]);
}
// printf("\n");
}
printf(" determinant is %d\n", det(n,a));
}
int det( int n, int a[][n])
{
int i, aj,bj,k,d,p=0 ;
int sign =1;
if(n==2)
{
d = a[0][0]*a[1][1] - a[0][1]*a[1][0];
return d;
}
else
for ( k = 0; k < n ; k++ )
{
int b[n-1][n-1];
for (i=1; i<n; i++)
{
for(aj=0,bj=0 ; aj<n; aj++)
{
if(aj==k) continue;
b[i-1][bj]=a[i][aj];
++bj;
}
}
p = a[0][aj]*pow(-1,k)*det(n-1, b)+p;
}
return p;
}
[Edit by Spektre]
You got wrong index in the last computation. I would change your det code to (summary of my comments):
int det( int n, int a[][n])
{
if(n<=0) return 0; // stop recursion
if(n==1) return a[0][0]; // stop recursion
if(n==2) return a[0][0]*a[1][1] - a[0][1]*a[1][0]; // stop recursion
int i,aj,bj,k,p,sign,b[n-1][n-1];
for (p=0, sign=+1, k = 0; k < n ; k++, sign=-sign)
{
for (i=1; i<n; i++)
{
for (aj=0,bj=0 ; aj<n; aj++)
if (aj!=k)
{
b[i-1][bj]=a[i][aj];
++bj;
}
}
p= p + (sign*a[0][k]*det(n-1, b)); // here you had aj instead of k causing problems !!!
}
return p;
}
Sadly my compilers does not allow this kind of array passing and I would need to change it to either template or dynamic arrays which would be confusing for you ... So I tested on this and looks like it works:
const int N=3;
int A[N][N]=
{
{ 1,2,3 },
{ 2,3,1 },
{ 3,1,2 },
};
int det(const int n, int a[][n])
{
if(n<=0) return 0; // stop recursion
if(n==1) return a[0][0]; // stop recursion
if(n==2) return a[0][0]*a[1][1] - a[0][1]*a[1][0]; // stop recursion
int i,aj,bj,k,p,sign,b[N][N];
for (i=0;i<n;i++) for (k=0;k<n;k++) b[i][k]=0;
for (p=0, sign=+1, k = 0; k < n ; k++, sign=-sign)
{
for (i=1; i<n; i++)
{
for (aj=0,bj=0 ; aj<n; aj++)
if (aj!=k)
{
b[i-1][bj]=a[i][aj];
++bj;
}
}
p+= sign*a[0][k]*det(n-1,b); // here you had aj instead of k causing problems !!!
}
return p;
}
with result det(N,A)=-18 matching my own determinant functions.
You need a function prototype for det() before main(), and the size argument needs to precede the VLA in the function call. Also, you should be using size_t for array indices instead of int.
There is no reason to use pow() to alternate signs; instead use int sign = 1; and multiply by -1 when the sign needs to be alternated.
In the loop within det(), you have:
for(j=0 && j!=k ; j<n; j++) {}
with the intention of skipping over the kth column; instead you need to write this as:
for (j = 0; j < n; j++) {
if (j == k) continue;
...
}
But there is a further problem here with:
b[i][j]=a[i][j];
Since the indices for b[][] and a[][] are not the same, and in fact b is smaller than a, this will result in writing out of bounds to b. Instead you can declare separate column indices for the two matrices:
size_t aj, bj;
...
for (aj = 0, bj = 0; aj < n; aj++)
{
if (aj == k) continue;
b[i-1][bj] = a[i][aj];
++bj;
}
...
}
Finally, you multiply the determinant of b by the wrong element of a:
l = a[0][j]*pow(-1,j)*det(b,n-1)+l;
After making the other corrections, this should be:
l = sign * a[0][k] * det(n-1, b) + l;
Here is the complete modified code:
#include <stdio.h>
int det(size_t n, int a[n][n]);
int main(void)
{
size_t n,i,j;
printf("enter the size of the matrix: ");
scanf("%zu", &n);
int a[n][n];
printf("enter the matrix: \n");
for (i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("determinant is %d\n", det(n, a));
return 0;
}
int det(size_t n, int a[][n])
{
size_t i, aj, bj, k, d;
int l = 0;
int sign = 1;
if(n == 2)
{
d = a[0][0] * a[1][1] - a[0][1] * a[1][0];
return d;
}
else
for (k = 0; k < n ; k++)
{
int b[n-1][n-1];
for (i = 1; i < n; i++)
{
for (aj = 0, bj = 0; aj < n; aj++)
{
if (aj == k) continue;
b[i-1][bj] = a[i][aj];
++bj;
}
}
l += sign * a[0][k] * det(n-1, b);
sign *= -1;
}
return l;
}
Here are a couple of sample interactions:
λ> ./a.out
enter the size of the matrix: 3
enter the matrix:
1 2 3
4 5 6
7 8 9
determinant is 0
λ> ./a.out
enter the size of the matrix: 3
enter the matrix:
1 -2 3
4 -5 6
7 8 -9
determinant is 42
Update
OP has posted updated code, and this update is to address the new issues. First, main() must (for the most part) have one of two function signatures:
int main(void);
or
int main(int argc, char *argv[]); // equivalently int main(int argc, char **argv);
Now, you must either move the definition of det() before main(), or add a function prototype:
int det( int n, int a[][n]);
Since det() uses VLAs, the size argument must come before the array argument, so the function calls must change to:
printf("%d determinant is", det(n, a));
and
p = a[0][k]*pow(-1,k)*det(n-1, b)+p;
Finally, within the inner loop in det(), you must keep two indices, aj and bj, since a[][] and b[][] are different sizes, and the elements of a[][] and b[][] do not exactly correspond:
for(aj=0, bj=0 ; aj<n; aj++)
{
if(aj==k) continue;
b[i-1][bj]=a[i][aj];
++bj;
}
I would suggest not using pow() for the sign alternation for a number of reasons; it involves an unnecessary library call, and the return value of pow() is double.
Most of these points were made in the original answer. After making these changes, your code worked for me.
Related
I want to write a program where a user tells me an integer(n) and i calculate The sum of 1+(1-2)+(1-2+3)+(1-2+3-n)... where even integers are -k and odd integers are +k.
Ive made a function which does that But the sum is never correct. For example for n=2 it should be sum=0 but shows sum=-1 for n=3 should be sum=+2 but i shows sum=3. (Ignore the debugging printfs)
#include <stdio.h>
int athroismaAkolouthias(int n); // i sinartisi me tin opoia ypologizete to athroisma akolouthias 1+(1-2)+(1-2+3)+(1-2+3-4).....
int main(){
int n;
printf("give n: ");
scanf("%d", &n);
printf("the sum is %d", athroismaAkolouthias(n));
}
int athroismaAkolouthias(int n){
int sum1=0, sum2=0,sum=0;
int i, temp, j;
for (i=1; i<=n; i++){
for (j=1; j<=i; j++){
temp=j;
}
if (i%2==0){sum=sum-temp; printf("test1 %d%d",sum,temp);}
else{sum=temp; printf("test2 %d%d",sum,temp);}
}
return sum;
}
Your issue is with our loop which iterate with j, it should update the inner_sum based on j even/odd condition as follows:
#include <stdio.h>
int akl(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
int inner_sum = 0;
for (int j = 1; j <= i; j++) {
if (j % 2 == 0) {
inner_sum -= j;
} else {
inner_sum += j;
}
}
sum += inner_sum;
}
return sum;
}
int main() {
int n;
scanf("%d", &n);
printf("%d\n", akl(n));
}
You only need two variables for sum that I named them inner_sum and sum which shows the sum of each term and sum over all terms.
Suspicious Line: else {sum = temp; ...
Shouldn't you be adding or subtracting to sum every time??
Why are you assigning to it here, without an addition or subtraction?
You also have variables sum, sum1, and sum2.
You print sum1 and sum2, but never modify them.
Here's my solution:
// The sum of 1+(1-2)+(1-2+3)+(1-2+3-n)... where even integers are -k and odd integers are +k.
#include <stdio.h>
int ancho(int n)
{
int sum=0;
for(int i=1; i<=n; ++i)
{
for(int j=1; j<=i; ++j)
{
sum += (2*(j%2)-1)*j;
}
}
return sum;
}
int main(void)
{
int n = 5;
printf("Solution is %d\n", ancho(n));
}
// Solution is 3 for n = 5,
// because: 1 + (1-2) + (1-2+3) + (1-2+3-4) + (1-2+3-4+5) =
// 1-1+2-2+3 = 3
Output
Success #stdin #stdout 0s 5476KB
Solution is 3
IDEOne Link
I want to find prime numbers from the Fibonacci series after printing them. First, I implemented the code for Fibonacci then added each element into an array. Then passed the array to a method to check for prime. Wanted to try it with an array. Displaying the series but not the prime numbers from the following code.
#include <stdio.h>
int fib()
{
int a=0,b=1, arr[20];
arr[0] = a;
arr[1] = b;
printf("%d, %d,",a, b );
int c=0;
for(int i=2; i<=20; i++)
{
c=a+b;
arr[i] = c;
printf("%d,",c);
a=b;
b=c;
}
checkPrime(arr);
}
void checkPrime(int a[])
{
int i, count;
for(i=0; i<sizeof(a); i++)
{
count=0;
for(int j=2; j<=a[i]/2 ; j++)
{
if(a[i]%2==0)
count++;
}
if(count>1)
printf("%d is a Prime", a[i]);
}
}
int main()
{
fib();
}
Output of the code
0, 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,
8 is a Prime
You have certain bugs in your implementation.
In fib function you iterate until i <= 20 but your arr have length 20 therefore your loop will go out of bounds of array. You should iterate until i < 20 or increase length of your array.
In checkPrime function you iterate until i < sizeof(a). But sizeof function doesn't return size of your array. It returns size of type of variable that you pass to it therefore it will return sizeof(int*) which = 8 (in case you 64 bit machine but I guess you have). To fix this bug you should pass length of your array in checkPrime function and use it.
You don't reset the count variable after j loop.
checkPrime function doesn't check if the number is prime. You have wrong expression in your nested loop. To check if number N is prime you should check if there any divisor of N that at least less than sqrt(N). Your expression is wrong.
Considering the adjustments above I suggest the next solution:
void checkPrime(int a[], size_t a_len) {
int i, count;
for (i = 1; i < a_len; i++) {
count = 0;
for (int j = 2; j <= sqrt((double)a[i]); j++) {
if (a[i] % j == 0) {
count++;
break;
}
}
if (count == 0) {
printf("%d is a Prime\n", a[i]);
} else {
count = 0;
}
}
}
int fib() {
size_t arr_size = 21;
int a = 0, b = 1, arr[arr_size];
arr[0] = a;
arr[1] = b;
printf("%d, %d, ", a, b);
int c = 0;
for (int i = 2; i < arr_size; i++) {
c = a + b;
arr[i] = c;
if (i == arr_size - 1)
printf("%d ", c);
else
printf("%d, ", c);
a = b;
b = c;
}
printf("\n");
checkPrime(arr, arr_size);
}
The objective: Add only the pieces of the matrix that are part of a full X (upper and lower triangle).
1 1 1
0 1 0
1 1 1
Like this, middle one should add only once.
I can't add the lower triangle properly. Help much appreciated :)
void write(int niz[20][20], int n){
int i, j;
for(i=0; i<n; i++){
for(j=0; j<n; j++){
scanf("%d", &niz[i][j]);
}
}
}
void x(int niz[20][20], int n){
//Upper triangle
int i, j, pr=n, suma=0;
for(i=0; i<n/2 + n%2; i++,pr--){
for(j=i; j<pr; j++){
suma += niz[i][j];
}
}
printf("%d\n",suma);
//Lower triangle
pr = n;
for(i=n; i>n/2 + n%2; i--,pr--){
printf("%d",pr);
for(j=n-i; j<pr; j++){
printf("\n%d", niz[i][j]);
suma += niz[i][j];
}
}
printf("%d", suma);
}
int main()
{
int n;
printf("Matrix dimensions: ");
scanf("%d", &n);
printf("Numbers in the matrix: \n");
int niz[n][n];
write(niz, n);
x(niz, n);
}
Instead of writing separate functions for each lower, upper & diagonals you can do all together with little tricks, but it works only if row == column and thats's what you want I think.
int main() {
/* it can be anything like a[3][3] or a[7][7] and elements can
be all one or all 2 or any number */
int arr[5][5] = { {1,1,1,1,1},
{0,0,1,0,0},
{0,0,1,0,0},
{0,0,1,0,0},
{1,1,1,1,1} };
int row = sizeof(arr)/sizeof(arr[0]);
int col = sizeof(arr[0])/sizeof(arr[0][0]);
int sum = 0;
for(int index = 0; index < row; index++) {
for(int sub_index = 0; sub_index < col; sub_index++) {
if(index == 0 || (index == row-1) || sub_index == row/2)
sum = sum + arr[index][sub_index];
}
}
printf("sum = %d \n",sum);
return 0;
}
Its fine if it helps you otherwise write your own logic.
There are some mismatches between the declarations and types of the arguments passed to OP's function. While in main they declare a variable length array, named niz:
int n;
// ...
int niz[n][n];
The posted signature of both write and x requires an int niz(*)[20]. It should be changed to:
void write(int n, int niz[n][n]);
// this ^^^ may be a size_t, just remember to write it before the array
About the pattern you have to follow for the sum, I can't say to fully understand your requirement, but if I'm not completely wrong, it could be done this way:
#include <stdio.h>
#include <stdlib.h>
void read_matrix(int n, int niz[n][n])
{
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
scanf("%d", &niz[i][j]);
}
}
}
// Separate the calculation from the printing
int hourglass_sum(int n, int niz[n][n])
{
int sum = 0;
int i = 0;
//Upper triangle
for(int k = n; i < k; ++i, --k) {
for(int j = i; j < k; ++j) {
sum += niz[i][j];
}
}
//Lower triangle
for(int k = i + 1; i < n; ++i, ++k) {
for(int j = n - i - 1; j < k; ++j) {
sum += niz[i][j];
}
}
return sum;
}
int main()
{
int n;
printf("Matrix dimensions: ");
scanf("%d", &n);
int niz[n][n];
read_matrix(n, niz);
printf("\nSum: %d", hourglass_sum(n, niz));
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I've tried to create two matrices and do the product in another matrix, but the compiler gives an error of core dump. The creation of the first two matrices is right; something is wrong with the third matrix.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m;
int n;
int t;
int i;
int **A;
int **B;
int k;
int j;
scanf("%d",&n);
scanf("%d",&m);
scanf("%d",&t);
A=malloc(n*sizeof(int*));
for(i=0;i<n;i++){
A[i]=malloc(m*sizeof(int));
}
for(i=0;i<n;i++){ // A[n][m]
for(j=0;j<m;j++)
{
scanf("%d",&(A[i][j]));
}
}
B=malloc(t*sizeof(int*));
for(i=0;i<t;i++) //B[m][t]
{
B[i]=malloc(n*sizeof(int));
}
for(i=0;i<t;i++){
for(j=0;j<n;j++)
{
scanf("%d",&(B[i][j]));
}
}
int **C;
C=malloc(t*sizeof(int*));
for(i=0;i<t;i++){{A[i]=malloc(m*sizeof(int));}
for(i=0;i<t;i++){
for(j=0;j<m;j++){
C[i][j]=0;
for(k=0;k<n;k++)
{
(C[i][j])=(C[i][j])+((A[k][j])*(B[i][k]));
}
}
}
}
return 0;
}
You must separate memory for C, not for A. That is why when you try to access C[i][j] it generates this error. Change:
for(i=0;i<t;i++){{A[i]=malloc(m*sizeof(int));}
to
for(i=0;i<t;i++){ C[i]=malloc(m*sizeof(int));}
Complete code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m;
int n;
int t;
int i;
int **A;
int **B;
int k;
int j;
scanf("%d",&n);
scanf("%d",&m);
scanf("%d",&t);
A=malloc(n*sizeof(int*));
for(i=0;i<n;i++){
A[i]=malloc(m*sizeof(int));
}
for(i=0;i<n;i++){ // A[n][m]
for(j=0;j<m;j++){
scanf("%d", &(A[i][j]));
}
}
B=malloc(t*sizeof(int*));
for(i=0;i<t;i++) //B[m][t]
{
B[i]=malloc(n*sizeof(int));
}
printf("B\n");
for(i=0;i<t;i++){
for(j=0;j<n;j++)
{
scanf("%d",&(B[i][j]));
}
}
int **C;
C=malloc(t*sizeof(int*));
for(i=0;i<t;i++){
C[i]=malloc(m*sizeof(int));
}
for(i=0;i<t;i++){
for(j=0;j<m;j++){
C[i][j]=0;
for(k=0;k<n;k++)
{
(C[i][j])=(C[i][j])+((A[k][j])*(B[i][k]));
}
}
}
return 0;
}
Previous answers may have fixed the problem that caused the crash, but the code is still broken. It would be nice if the variables had more descriptive names. Since each variable is declared on a separate line, you could make use of the space to provide descriptive comments about the variables.
It is conventional to reference the rows of a matrix first, and then the columns. So, I will diverge from your usage, and say that matrix A has m rows and n columns. B must then have n rows, and it looks like you intend for t to hold the number of columns in B. Then the product C will be a m X t matrix.
Your code started to go wrong when you allocated space for B. You allocated for t rows of n elements, when you should have allocated for m rows of t elements (by your own notation). In my code below, because I have changed the order of m and n, I allocate for n rows of t elements.
Then, for the product matrix, I have allocated for m rows of t elements, where you had allocated for t rows of m elements. The calculation of the elements of the product matrix was also wrong in your code. The [i][j] element of C is the vector dot-product of the ith row of A and the jth column of B. The way you have calculated this element, C[i][j] is the dot-product of the jth column of A and the ith row of B.
Here is the code with corrections. I included some input prompts, and some code to display the entered matrices and the resulting product.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int m; // rows in A
int n; // cols in A
int t; // cols in B
int i;
int **A; // points to first row of A
int **B; // points to first row of B
int **C; // points to first row of C
int k;
int j;
printf("Enter number of rows in A: ");
scanf("%d", &m);
printf("Enter number of columns in A: ");
scanf("%d", &n);
printf("Enter number columns in B: ");
scanf("%d", &t);
A = malloc(sizeof(int*) * m); // A[m][n]
for(i = 0;i < m; i++){
A[i] = malloc(sizeof(int) * n);
}
for(i = 0; i < m; i++){
for(j = 0; j < n; j++)
{
scanf("%d", &(A[i][j]));
}
}
B = malloc(sizeof(int*) * n); // B[n][t]
for(i = 0; i < n; i++)
{
B[i] = malloc(sizeof(int) * t);
}
for(i = 0; i < n; i++){
for(j = 0; j < t; j++)
{
scanf("%d", &(B[i][j]));
}
}
C = malloc(sizeof(int*) * m); // C[m][t]
for(i = 0; i < m; i++){
C[i] = malloc(sizeof(int) * t);
}
for(i = 0; i < m; i++){
for(j = 0; j < t; j++){
C[i][j] = 0;
for(k = 0; k < n; k++)
{
C[i][j] = C[i][j] + A[i][k] * B[k][j];
}
}
}
printf("Matrix A:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%-5d", A[i][j]);
}
putchar('\n');
}
printf("Matrix B:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < t; j++) {
printf("%-5d", B[i][j]);
}
putchar('\n');
}
printf("Matrix product:\n");
for (i = 0; i < t; i++) {
for (j = 0; j < m; j++) {
printf("%-5d", C[i][j]);
}
putchar('\n');
}
return 0;
}
Here is the result of a test run:
λ> ./a.out
Enter number of rows in A: 2
Enter number of columns in A: 3
Enter number columns in B: 2
2 3 4
1 3 5
3 4
5 6
7 8
Matrix A:
2 3 4
1 3 5
Matrix B:
3 4
5 6
7 8
Matrix product:
49 58
53 62
I can't seem to find any info on how to access elements of an array via pointer in a function, I tried following multiple answers but none of them seem to work for me.
My task is next: Write a program in C with m x n dimension with elements being randomly generated from 0 to 9. Using two new functions calculate the sum of even elements and count the number of elements being equal to zero.
#include <stdio.h>
#include <stdlib.h>
void SumEven(int *a, int n, int m, int *sum){
}
void EqualToZero(int *a, int n, int m, int *number){
}
int main()
{
int** a;
int m, n, l, i, j, r, sum;
printf("Enter number of columns for matrix: ");
scanf("%d", &m);
printf("Enter number of rows for matrix: ");
scanf("%d", &n);
a = (int **) malloc(m*sizeof(int));
for (l = 0 ; l < m ; l++){
a[l] = (int **) malloc(n*sizeof(int));
}
time_t t;
srand((unsigned)time(&t));
printf("\n");
printf("Your matrix is:\n");
printf("\n");
for(i = 0 ; i < m ; i++){
for(j = 0 ; j < n ; j++){
r = rand() % 10;
a[i][j] = r;
printf("%d ", r);
}
printf("\n");
}
printf("\n");
SumEven(&a, n, m);
return(0);
}
As you can see in the provided code I left those functions empty as I don't know how to pass the matrix to them and access their elements so I can be able to print my results.
Also my pseudo code for the logic for the functions themselves are:
if(a[i][j] % 2 == 0)
printf("%d ", a[i][j])
and
if(a[i][j] == 0)
printf("%d ", a[i][j])
Also those parameters of the function are predefined in my task, so I have to follow them.
EDIT: I also don't know if I'm even passing the same matrix to the function with SumEven(&a, n, m);. I tried outputing the address of the matrix and using printf("%d", &a) to display an address both from main() and SumEven() functions.
This code may help. It does the following:
1. For an arbitrary array of integers, sum the elements of the array
- using a pointer to the SUM function
2. For an arbitrary array of integers, count the number of zero elements in
the array - using a pointer to the COUNTZERO function
#include <stdio.h>
#include <stdlib.h>
// sum the elements of the matrix
void sum(int* arr, int rows, int cols, int* result)
{
int sum = 0;
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
sum = sum + arr[i*cols + j];
}
}
*result = sum;
}
// count the number of zero elements in the matrix
void countZero(int* arr, int rows, int cols, int* result)
{
int count = 0;
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
if (arr[i*cols + j] ==0) count = count + 1;
}
}
*result = count;
}
// arbitrary initialisation of 2D array of ints (force last entry of the array to equal zero - for testing purposes)
void init2D(int *arr, int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
arr[i*cols + j] = 1;
}
}
// use this to test the countZero function
arr[(rows-1)*(cols-1)] = 0;
}
int main() {
int *array; // will hold a 2D array of integers
int N = 10; // arbitrary number of rows
int M = 5; // arbitrary num cols
// 2D array of integers expressed as one "contiguous row" of memory
// make sure your indexing is correct when referenceing the array for (i,j)th element
array = (int*)malloc(sizeof(int)*N*M);
if (array != NULL) {
init2D(array, N, M);
}
// the function pointer
void(*general)(int*,int,int,int*);
// will contain the sum result
int sumAll = 0;
int* ptsumAll = &sumAll;
// make the function pointer point to the sum function
general = ∑
// sum the contents of the array
general(array,N,M, ptsumAll);
printf("sum of array elements: %d\n", *ptsumAll);
// contains a count of the zero elements in the array
int count =0;
int* ptcount = &count;
// make the function pointer point to the count function
general = &countZero;
// count the number of zero element in the array
general(array, N, M,ptcount);
printf("number of zeros: %d\n", *ptcount);
free(array);
return 0;
}
some references:
https://www.cs.swarthmore.edu/~newhall/unixhelp/C_arrays.html
http://www.cprogramming.com/tutorial/function-pointers.html
I have added comments to help you with the code.
#include <stdio.h>
#include <stdlib.h>
void SumEven(int *a, int n, int m, int *sum){
//put this statement in 2 nested for loops of size n and m
if(a[i][j] % 2 == 0)
sum += a[i][j];
}
void EqualToZero(int *a, int n, int m, int *number){
//put this statement in 2 nested for loops of size n and m
if(a[i][j] == 0)
number++;
}
int main()
{
int** a;
int m, n, l, i, j, r, sum;
printf("Enter number of columns for matrix: ");
scanf("%d", &m);
printf("Enter number of rows for matrix: ");
scanf("%d", &n);
a = (int **) malloc(m*sizeof(int));
//should be m*sizeof(int*)
for (l = 0 ; l < m ; l++){
a[l] = (int **) malloc(n*sizeof(int));
//should be cast as (int*)
}
//I suggest you take look at declaring 2d arrays in C
time_t t;
srand((unsigned)time(&t));
printf("\n");
printf("Your matrix is:\n");
printf("\n");
for(i = 0 ; i < m ; i++){
for(j = 0 ; j < n ; j++){
r = rand() % 10;
a[i][j] = r;
printf("%d ", r);
}
printf("\n");
}
printf("\n");
SumEven(&a, n, m);
//need to pass &sum to this function. Also make sure it is initialized to 0
//call EqualToZero() function with proper parameters.
return(0);
//return 0; not return(0);
}
These will be your function prototypes:
void SumEven(int **a, int n, int m,int *sum);
void EqualToZero(int **a, int n, int m,int *number);
since you are passing a(double pointer) from calling then the there should be a double pointer(int **a) to receive it.
Calling:
SumEven(a, n, m,&sum);
EqualToZero(a, n, m,&number);
And this is how you can access the array inside your function:
void SumEven(int **a, int n, int m,int *sum){
int i,j,tsum=0;
for(i = 0 ; i < m ; i++){
for(j = 0 ; j < n ; j++){
if(a[i][j] % 2 == 0)
{
tsum+=a[i][j];
printf("%d ",a[i][j]);
}
}
}
*sum=tsum;
}
Also there is an error in this line a[l] = (int **) malloc(n*sizeof(int)); (‘int**’ to ‘int*’assignment),it should be a[l] = (int *) malloc(n*sizeof(int));.
Here's an example, given a 3D array
int buffer[5][7][6];
An element at location [2][1][2] can be accessed as buffer[2][1][2] or *( *( *(buffer + 2) + 1) + 2).
Reference
if(( *(*(a + i) + j) % 2 ) == 0 )
printf("%d", *(*(a + i) + j) )
if( *(*(a + i) + j) == 0 )
printf("%d", *(*(a + i) + j) )
This is how you do it.