Hello Everybody

I want to print the value of alternative element of a 2D array.
For Example-
23, 54, 76
37, 19, 28
62, 13, 19

Output should be-
23 76 19 62 19

I am trying to get this output since 5 hours. Here is my code -

#include <iostream.h>
#include <conio.h>
void process_Array(int Arr[][3],int x, int y);

void process_Array(int A[][3],int N, int M)
{
  clrscr();
  for (int R = 0; R < N; R++)
  {
    for (int C = 0; C < M; C=C+2)
    {
       cout<< A[R][C]<<" ";
    }
  }
cout<<endl;
cout<<endl;
  for (int I = 0; I < N; I++)
  {
    for (int J = 0; J < M; J++)
    {
       cout << A[I][J]<<" ";
    }
    cout<<endl;
  }
}
int main ()
{
  int arr[3][3] ={{23, 54, 76},
          {37, 19, 28},
          {62, 13, 19},
         };
  process_Array(arr,3,3);
  return 0;
}

By this code I am getting this output -
23 76 37 28 62 19, actually there must be 19 which is arr[1,1].

Please advice me.
Thank you.

You can use modular arithmetic to make a variable to take values between 0 - (n-1) when it's incremented by 2, or you can take advantage of odd-even steps of the row number, just start the col iterator(j) from 0 when the row number is even and from 1 when the row number is odd.

Using modular arithmetic as already suggested by ken, work out what expressions need to be evaluated in order to produce an output of
arr[0][0] arr[0][2] arr[1][1] arr[2][0] arr[2][2]

I am learning C++ I will be greatful if anyone can provide me some kind of example in codeform.
Thank you

Toggle a boolean flag, perhaps?

const int arr[3][3] = { 
                        { 23, 54, 76 },
                        { 37, 19, 28 },
                        { 62, 13, 19 },
                      } ;

bool alt = true ;
for( const auto& row : arr ) for( int i : row )
{
  if(alt) std::cout << i << '\n' ;
  alt = !alt ;
}
This article has been dead for over six months. Start a new discussion instead.