Home > Back-end >  How to shift 2d array column up in c program
How to shift 2d array column up in c program

Time:01-29

I need shift the column up in 2D Array and set the last row to zero.

if I call shift up once need to move the each column value to up and set the last column to zero. input array output array

1 2 3         4 5 6 
4 5 6  ==>    7 8 9
7 8 9         1 1 1
1 1 1         0 0 0

used swap logic bit the last row becomes first after calling shift UP.

void shiftup()
{
for(int col=0;col<=3;col  )

   {
       int start = 0;
       int end = 3 - 1;
       while (start < end) {
          swap(&arr[start][col], &arr[end][col]);
          start  ;
          end--;
   }
}
void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

can any one suggest the change in the above code.

CodePudding user response:

It is simpler to apply standard functions memmove and memset as for example

    memmove( a, a   1, sizeof( a ) - sizeof( a[0] ) );
    memset( a   3, 0, sizeof( *a ) );

Here is a demonstration program

#include <stdio.h>
#include <string.h >

int main( void )
{
    enum { M = 4, N = 3 };
    int a[M][N] =
    {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 },
        { 1, 1, 1 }
    };

    memmove( a, a   1, sizeof( a ) - sizeof( a[0] ) );
    memset( a   M - 1, 0, sizeof( *a ) );

    for (size_t i = 0; i < M; i  )
    {
        for (size_t j = 0; j < N; j  )
        {
            printf( "%d ", a[i][j] );
        }
        putchar( '\n' );
    }
}

The program output is

4 5 6
7 8 9
1 1 1
0 0 0

As for your code then at least this for loop

for(int col=0;col<=3;col  )
              ^^^^^^

is incorrect. You have to write instead

for(int col = 0;col < 3;col  )

And these calling of the function swap

swap(&arr[start][col], &arr[end][col]);

does not make a sense.

  •  Tags:  
  • Related