Home > OS >  how to get sum and absolute difference in the same function?
how to get sum and absolute difference in the same function?

Time:01-23

a function receives two integer pointers, int* a and int* b. Set the value of *a to their sum, and *b to their absolute difference. There is no return value, and no return statement is needed.

I got the values for *a but I'm unable to get the code for *b.

#include <stdio.h>
void update(int *a,int *b);


int main() {
    int a, b;
    int *pa = &a, *pb = &b;
    
    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
}
void update(int *a,int *b) 
{
    *a =*b;
    *b=*a-*b;
}

CodePudding user response:

You may use a temporally variable to store value of *a and then use it:

int tmp = *a;
*a  = *b;
*b = abs(tmp - *b);

CodePudding user response:

A little cleanup. Only the function needs pointers. Your main does not.

#include <stdio.h>
#include <stdlib.h>  // abs()

void sum_and_diff( int * a, int * b )
{
  int sum = *a   *b;
  int diff = abs( *a - *b );
  *a = sum;
  *b = diff;
}

int main(void)
{
  int a, b;

  printf( "a? " );  scanf( "%d", &a );
  printf( "b? " );  scanf( "%d", &b );

  sum_and_diff( &a, &b );

  printf( "sum = %d\n", a );
  printf( "absolute difference = %d\n", b );

  return 0;
}

CodePudding user response:

A simple answer (the simplest?), that doesn't require temporary variables or external functions like abs(), is:

void update(int *a, int *b) 
{
    *a  = *b;
    *b =  *a-*b-*b;
}

It fixes your code by also subtracting the "extra" *b you just added to *a

  • Related