Game Programming




 
game programming
Game Programming :: Programming :: General Programming :: Code Examples :: [C++] Implementing Functions - View Topic
Topic Rating: *****
Printable View
Andy
Administrator
*****

Posts: 40
Status: Offline
Gender: Male
Joined:  
pm

Reputation: 0%

[C++] Implementing Functions (11th Jan 08 at 2:01am UTC)
Level: Beginner (some experience)

This code asks the user for two integer values. Using functions, it will then add, subtract, multiply, and divide the two numbers, and print them and the results of the arithmetic to the screen.

Note: Both the calculations and printing of the new values could have been coded using one function. However, as a rule, a function should be designed to perform only one task.
Note: The two functions do not return a value, so they are given the type void. This means the return statements are not needed, but it is considered good coding technique to include them anyway.

Code:
 
  1. // Using functions- Arithmetic with two values
  2.  
  3. #include<iostream>
  4.  
  5. using namespace std;
  6.  
  7. void useTwo(int &a, int &b, int &s, int &;d, int &p, double &q); // function prototype
  8. void printResults(int a, int b, int s, int d, int p, double q); // function prototype
  9.  
  10. int main()
  11. {
  12. int num1, num2, sum, difference, product;
  13. double quotient;
  14.  
  15. cout << "Please enter two integers to add, subtract, multiply and divide." << "\n\n";
  16.  
  17. useTwo(num1, num2, sum, difference, product, quotient);// function call
  18.  
  19. printResults(num1, num2, sum, difference, product, quotient);// function call
  20.  
  21. return 0;
  22. }// end of main program
  23.  
  24.  
  25. //************************************************************
  26. // functions begin here
  27. //************************************************************
  28. void useTwo(int &a, int &b, int &s, int &;d, int &p, double &q)
  29. {
  30. cout << "enter #1: ";
  31. cin >> a;
  32. cout << "enter #2: ";
  33. cin >> b;
  34.  
  35. s = a + b;
  36. d = a - b;
  37. p = a * b;
  38. q = a / b;
  39.  
  40. return;
  41. }// useTwo function
  42.  
  43. void printResults(int a, int b, int s, int d, int p, double q)
  44. {
  45. cout << "\n\n";
  46. cout << "number 1= " << a << endl;
  47. cout << "number 2= " << b << "\n\n";
  48. cout << "sum= " << s << "\n\n";
  49. cout << "difference= " << d << "\n\n";
  50. cout << "product= " << p << "\n\n";
  51. cout << "quotient= " << q << "\n\n";
  52.  
  53. return;
  54. }// printResult function
  55.  
 


 Printable View

All times are GMT+0 :: The current time is 9:16pm
Page generated in 0.1906 seconds
Purchase Ad-Free Credits
This Forum is Powered By vForums (v2.4)
Create a Forum for Free | Find Forums