• Forum
  • Lounge
  • How to find the column index of a matrix

How to find the column index of a matrix element

Hello Everyone,

I am a beginner in C++.

I want to find the column index of a matrix element with given row number.

For example,

table = {{0, 2, 0, 4}, {3, 4, 0, 0.7}, {0.1, 0.9, 5, 6}}

current_row_index = 1
value = 4

Here current_row_index and value are variables. I want to find out the corresponding column index of 4.

I tried in following way, but it does not work. Can anyone please correct the code? Thank you!

for (int m = 0; m < row_size; ++m) {
for (int n = 0; n < column_size; ++n) {
if((m = current_row_index) && (table[current_row_index][n] == value))
value_index = n;


You don't need to loop on m if you know the row index.

That would solve your main problem. Use ==, not =, when comparing for equality (your if statement). You also appear to be breaking out of the column loop even if the value isn't found: you don't need the "else".

Please use code tags (and post complete programs).
Last edited on
you have assignment in your if statement, which is legal but usually wrong. (= vs ==)
does it work if you fix that?
your question is not matching your code. if row# is given why iterate it?
Last edited on
Thanks for your responses. I will try with ==.

In my question, i mentioned that current_row_index and value are variables.

I gave that example to explain what i want.

But, row # is not given. It will be selected randomly.

Thank you
selected randomly is given, in the sense we mean.
you say
for (int m = 0; m < row_size; ++m)
which checks every row.
if you randomly select it, the code should be
m = a_random_row;
for(all the columns of the mth row)

there is no point in checking to see if m is the selected row in a loop. Just use the selected row: the POINT of array like structures is the direct access, you don't need to LOOK for what you already know.
Ok, thank you.
Registered users can post here. Sign in or register to post.