Вы находитесь на странице: 1из 2

An Exercise using a mix of value variables and pointer variables

This assignment is about using values and pointers to those values, and, conversely, using
pointers and the values that those pointers are pointing at. You will have to pay attention to
which variables are values and which variables are pointers, and convert back at forth between
pointers and values as needed.
 Write a main with three integer variables, called x, y, and z.
 Write a function called printXYZ() that takes three integer arguments (as values) and
prints their value.
 Write a function called enterXYZ() that takes three arguments, all pointers to integers,
called ptrX, ptrY, and ptrZ, and returns nothing. Inside the function prompt the user to
enter three values for x, y, and z, and then use scanf to read the values into ptrX, ptrY,
and ptrZ. Have the function check for valid input and recurse (call itself again) if needed.
Use the scanf shown below to clear old input before recursing.
 Call printXYZ from within enterXYZ, once three values have been successfully read.
 Write the swap function shown below that takes two pointers to ints.
 Write a function called xyzAscending() that takes three pointers to ints, called px, py,
and pz, and returns nothing. Inside the function arrange the values that px, py, and pz are
pointing at so they are in ascending order with x smallest and z the largest. (See
explanation at end.) Inside the function, call printXYZ after putting them in order.
Call your functions from main in this order: printXYZ, enterXYZ, printXYZ, xyzAscending,
and again printXYZ,each time passing the x, y, and z variables either by value or by reference,
depending on that the function expects.
/* to clear old input (up to the newline) */
scanf("%*[^\n]");

Here are some pieces that you can use as examples of code that mixes pointers and values.
void swap(int *val1, int *val2) {
int temp = *val1;
*val1 = *val2;
*val2 = temp;
}
/* example of code using swap */
int main() {
int x = 3;
int y = 7;
swap(&x, &y);

About sorting: if you are sorting three values, you can sort them in pairs. Start with x and y to
make y larger than y. Then do y and z to make z larger than y. Since you made y larger than x
and z larger than y, z is now the largest. Because you may have swapped y and z, it is no longer
clear that x is smaller than y, so sort x and y again (in case the smallest value started in z). In this
form, you need three if statements to sort three numbers.
Here's a worked out example for (x = 7, y = 5, z = 3).
1. First compare x and y. If x is bigger than y, swap. Now x = 5, y = 7, and z = 3.
2. Now compare y and z. If y is bigger than z, swap. Now x = 5, y = 3, and z = 7.
3. Now the largest value made it from x to z. But the smallest value only went from z to y,
So we have to compare x and y again, and do the final swap.

Вам также может понравиться