1

Consider I have an array A={-4, 2, 2}, {3, -3, 3}, {6, 6, 0 } I want to access column wise.Col={-4,2,2} col_0={3,-3,3} col_1={6,6,0} I have tried something like this yet I am not getting output Can anyone help me. I am beginner in c

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define rows 3 
#define col 3

int main()
{
   int matrix_A[rows][col]=
 {
    {-4, 2, 2},
    {3, -3, 3},
    {6, 6, 0}
};
int col[rows];
int col_0[rows];
int col_1[rows];
int n;
for(n=0;n<rows;++n)
{
    col[n]=matrix_A[n][0];
    col_0[n]=matrix_A[n][1];
    col_1[n]=matrix_A[n][2];
}
print("%lf",col[n]);
print("%lf",col_0[n]);
print("%lf",col_1[n]);      

}

2
  • 1
    col[i] is actually same as matrix_A[i], Check this tutorial: programiz.com/c-programming/c-multi-dimensional-arrays PS: col is actually row in your case. That's not how 2d array works. Commented Apr 13, 2021 at 6:48
  • 1
    n will be 3 after the loop so it will be out of bounds, as index is 0...2 Commented Apr 13, 2021 at 7:07

1 Answer 1

1

Would you please try the following:

#include <stdio.h>
#include <stdlib.h>
#define rows 3
#define cols 3

int main()
{
    int matrix_A[rows][cols] = {
        {-4, 2, 2},
        {3, -3, 3},
        {6, 6, 0}
    };
    int col_0[rows];
    int col_1[rows];
    int col_2[rows];
    int n;

    for (n = 0; n < rows; n++) {
        col_0[n] = matrix_A[n][0];
        col_1[n] = matrix_A[n][1];
        col_2[n] = matrix_A[n][2];
    }
    printf("col_0 = %d %d %d\n", col_0[0], col_0[1], col_0[2]);
    printf("col_1 = %d %d %d\n", col_1[0], col_1[1], col_1[2]);
    printf("col_2 = %d %d %d\n", col_2[0], col_2[1], col_2[2]);

    return EXIT_SUCCESS;
}

Output:

col_0 = -4 3 6
col_1 = 2 -3 6
col_2 = 2 3 0

Please note the values of the first column or col_0 is {-4, 3, 6}, not {-4, 2, 2}.
The same with the second and the third.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.