-1

I need to write a function that takes the elements in an array and changes the sign (ex. 3 --> -3 or -3 --> 3). l want use this array (int a[2][3] = { { 55,-44,},{1, -4},{6,11} };) instead of ( int a[] = { 5,6,-4};) What should I do?

#include <stdio.h>

void change_sign(int* beta)
{
   for (int i = 0; i < 3; i++) {
      beta[i] = -beta[i];
   }
}

int main(void)
{
   int a[] = { 5, 6, -4};

   for (int i = 0; i < 3; i++) {
      printf("%d ", a[i]);
   }
   printf("\n");
   change_sign(a);
   for (int i = 0; i < 3; i++) {
      printf("%d ", a[i]);
   }
   return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
C baby
  • 11
  • 1

1 Answers1

0

For starters it seems you mean this array

int a[3][2] = { { 55,-44,},{1, -4},{6,11} };

instead of this

int a[2][3] = { { 55,-44,},{1, -4},{6,11} };

In any case if your compiler supports variable length arrays then the function can look like

void change_sign( size_t m, size_t n, int a[][n] )
{
    for ( size_t i = 0; i < m; i++ )
    {
        for ( size_t j = 0; j < n; j++ )
        {
            a[i][j] = -a[i][j];
        }
    }
}

and call the function like

change_sign( 3, 2, a ); 

Otherwise the function can look like

#define N  2

void change_sign( int a[][N], size_t m )
{
    for ( size_t i = 0; i < m; i++ )
    {
        for ( size_t j = 0; j < N; j++ )
        {
            a[i][j] = -a[i][j];
        }
    }
}

and called like

change_sign( a, 3 );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335