fork download
  1. //Zachary Abdollahi CS1A Chapter 9, P. 538, #5
  2. //
  3. /*******************************************************************************
  4.  *
  5.  * DEMONSTRATE POINTER PARAMETERS
  6.  * _____________________________________________________________________________
  7.  * This program demonstrates rewriting a function to accept pointer
  8.  * parameters instead of reference variables, multiplying each dereferenced
  9.  * value by 10, swapping them, and returning their sum.
  10.  *
  11.  * Computation is based on the formulas:
  12.  * New X = Original Y * 10
  13.  * New Y = Original X * 10
  14.  * Result = New X + New Y
  15.  * _____________________________________________________________________________
  16.  * INPUT
  17.  * num1 : First integer value entered by user
  18.  * num2 : Second integer value entered by user
  19.  *
  20.  * OUTPUT
  21.  * num1 : Modified first integer value
  22.  * num2 : Modified second integer value
  23.  * result : Sum of the two modified integer values
  24.  *
  25.  ******************************************************************************/
  26. #include <iostream>
  27. using namespace std;
  28.  
  29. // Function Prototype
  30. int doSomething(int *, int *);
  31.  
  32. int main()
  33. {
  34. int num1; //INPUT/OUTPUT - First integer value
  35. int num2; //INPUT/OUTPUT - Second integer value
  36. int result; //OUTPUT - Sum returned by doSomething
  37.  
  38. // Prompt User for Two Integers
  39. cout << "Enter the first integer: ";
  40. cin >> num1;
  41. cout << "Enter the second integer: ";
  42. cin >> num2;
  43.  
  44. // Display Values Before Function Call
  45. cout << "\nBefore calling doSomething:" << endl;
  46. cout << "num1 = " << num1 << ", num2 = " << num2 << endl;
  47.  
  48. // Call Function Passing Addresses of num1 and num2
  49. result = doSomething(&num1, &num2);
  50.  
  51. // Output Modified Values and Returned Sum
  52. cout << "\nAfter calling doSomething:" << endl;
  53. cout << "num1 = " << num1 << ", num2 = " << num2 << endl;
  54. cout << "Returned sum = " << result << endl;
  55.  
  56. return 0;
  57. }
  58.  
  59. /*******************************************************************************
  60.  * Function: doSomething
  61.  * Accepts two int pointers, swaps and multiplies their underlying values
  62.  * by 10 via dereferencing, and returns the sum of the new values.
  63.  ******************************************************************************/
  64. int doSomething(int *x, int *y)
  65. {
  66. int temp = *x;
  67. *x = *y * 10;
  68. *y = temp * 10;
  69. return *x + *y;
  70. }
Success #stdin #stdout 0s 592KB
stdin
4
7
stdout
Enter the first integer: Enter the second integer: 
Before calling doSomething:
num1 = 4, num2 = 7

After calling doSomething:
num1 = 70, num2 = 40
Returned sum = 110