Search code examples
cexponentiation

Write a function that for two numbers a and b returns their sum of squares a ^ 2 + b ^ 2 and (a + b) ^ 2 using pointers


My program return the wrong results. I honestly dont know where the problem is. a==5 and b==3, instead of returning the correct results, they return 2 for a ^ 2 + b ^ 2 and 10 for (a + b) ^ 2. Unless I am using pointers the wrong way, I do not know what is the problem.

#include <stdio.h>
#include <stdlib.h>

int main()
{
int a=5;
int b=3;
int c,d;
koko(&a,&b,&c,&d);
printf("Rezulat brojeva %d i %d je %d i %d",a,b,c,d);

}

int koko(int *x,int *y,int *z,int *u)
{
 *z=(*x)^2+(*y)^2;
 *u=(*x+*y)^2;
}

Solution

  • In the C syntax, the ^ character is not implied to be used to perform exponentiation on operands. It is implied as the XOR operator used by operations on bits.

    You can do the exponentiation by 2 by f.e. multiplying the respective value with itself:

    exp2_a = a * a;       // Example.
    

    Also the parameters of int* types for x and y in koko() do not need to be pointers (as soon as it isn´t a requirement for the task that all parameter types must be pointers), as we don´t need to alter the passed objects from inside of koko(). This makes the handle at the call to the function more convenient as we do not need to add the ampersand operator (&) for providing the relative addresses. Just change them to type int.

    Furthermore,koko() does not return anything, so the return value should be of type void, not int.

    So rather use:

    void koko(int x, int y, int* z, int* u)
    {
       *z = (x * x) + (y * y);
       *u = (x + y) * (x + y);
    }
    

    Next thing is you missed the declaration/prototype of koko() before main() since the function is defined after main() in the source code. This shall give you a compilation warning at least.


    Here is the complete and corrected code:

    #include <stdio.h>
    #include <stdlib.h>
    
    void koko(int,int,int*,int*);
    
    int main()
    {
       int a=5;
       int b=3;
       int c,d;
       koko(a,b,&c,&d);
       printf("Rezulat brojeva %d i %d je %d i %d",a,b,c,d);
    }
    
    void koko(int x, int y, int* z, int* u)
    {
       *z = (x * x) + (y * y);
       *u = (x + y) * (x + y);
    }
    

    Output:

    Rezulat brojeva 5 i 3 je 34 i 64