Need Help

closed account (Doj23TCk)
Trying to learn C++ myself from the book and im on chapter 9 about functions.
The question is...
Write and test a function that takes the addresses of three double variable as arguments and that moves the value of the smallest carrying into the first variable, the middle value to the second variable, and the largest value into the third variable.

#include <iostream>
using namespace std;
void f(int *a, int *b, int *c)
{
int max,min,mid;
max = *a>*b ? *a:*b;
max = max>*c ? max:*c;

min = *a<*b ? *a:*b;
min = min<*c ? min:*c;

mid = *a + *b + *c - max - min;
*c = max;
*b = mid;
*a = min;
}
int main()
{
int a,b,c;
a=20;
b=23;
c=10;
cout<<a<<" "<<b<<" "<<c<<endl;
f(&a,&b,&c);
cout<<a<<" "<<b<<" "<<c<<endl;

return 0;
}
closed account (Doj23TCk)
oh okay thanks! I tried out what you did and changed it but it works out the same, but still helped a lot!

#include <stdio.h>
void swap(int *a, int *b, int *c)
{
int max,min,mid;
max = *a>*b ? *a:*b;
max = max>*c ? max:*c;

min = *a<*b ? *a:*b;
min = min<*c ? min:*c;

mid = *a + *b + *c - max - min;
*c = max;
*b = mid;
*a = min;
}

int main()
{
int a,b,c;
a=20;
b=23;
c=10;
printf("a = %d, b = %d, c = %d\n", a , b, c);
swap(&a,&b,&c);
printf("a = %d, b = %d, c = %d\n", a , b, c);
return 0;
}
closed account (Doj23TCk)
question but in the code the part
int max,min,mid;
max = *a>*b ? *a:*b;
max = max>*c ? max:*c;

min = *a<*b ? *a:*b;
min = min<*c ? min:*c;

what does the "?" mean
That's what's commonly known as the conditional operator, although you may also hear it as ternary operator from C.

http://www.cplusplus.com/forum/articles/14631/

Let's just break down the first "?:" since they're all the same.
1
2
3
4
5
6
max = (*a)>(*b) // max is being assigned a true/false value based on the RVal boolean
? *a // pick this if true
: *b; // pick this if false

// btw I do the parentheses because I'm not giving the compiler 
// a chance to decide order of operations when it comes to pointers 
Topic archived. No new replies allowed.