c++


SUBMITTED BY: imdmad

DATE: Aug. 16, 2015, 1:12 p.m.

FORMAT: Text only

SIZE: 2.6 kB

HITS: 5882

  1. Hello World:
  2. Code Listing:
  3. (Note: lines started with // are comments, which will be ignored by the compiler)
  4. // File name: HelloWorld.cpp
  5. // Purpose: A simple C++ program which prints "Hello World!" on the screen
  6. #include <iostream> // need this header file to support the C++ I/O system
  7. using namespace std; // telling the compiler to use namespace "std",
  8. // where the entire C++ library is declared.
  9. int main()
  10. {
  11. // Print out a sentence on the screen.
  12. // "<<" causes the expression on its right to
  13. // be directed to the device on its left.
  14. // "cout" is the standard output device -- the screen.
  15. cout << "Hello World!" << endl;
  16. return 0; // returns 0,which indicate the successful
  17. // termination of the "main" function
  18. }
  19. Running session:
  20. mercury[24]% CC HelloWorld.cpp -LANG:std -o HelloWorld
  21. mercury[25]% HelloWorld
  22. Hello World!
  23. mercury[26]%
  24. 2. Variables and Constants
  25. Code listing:
  26. // File name: ~ftp/pub/class/cplusplus/HelloWorld/Variable.cpp
  27. // Purpose: Demonstrate the use of variables and constants
  28. //
  29. #include <iostream>
  30. using namespace std;
  31. // declaring a constant. It's value cannot be changed.
  32. const int CONST_VAL = 5;
  33. int main()
  34. {
  35. int iValue; // An integer variable
  36. float fValue; // A floating point variable
  37. char cValue; // A character variable
  38. iValue = 1234; // Assigns 1234 to iValue
  39. fValue = 1234.56; // Assigns 1234.56 to fValue
  40. cValue = 'A'; // Assigns A to cValue
  41. // Now print them out on the screen:
  42. cout << "Integer value is: " << iValue << endl;
  43. cout << "Float value is: " << fValue << endl;
  44. cout << "Character value is: " << cValue << endl;
  45. cout << "The constant is: " << CONST_VAL << endl;
  46. return 0;
  47. }
  48. Running session:
  49. mercury[39]% CC Variable.cpp -LANG:std -o Variable
  50. mercury[40]% Variable
  51. Integer value is: 1234
  52. Float value is: 1234.56
  53. Character value is: A
  54. The constant is: 5
  55. mercury[41]%
  56. 3. Basic IO
  57. Code listing:
  58. // File name: ~ftp/pub/class/cplusplus/HelloWorld/BasicIO.cpp
  59. // Purpose: Converts gallons to liters
  60. #include <iostream>
  61. using namespace std;
  62. int main()
  63. {
  64. float gallons, liters;
  65. cout << "Enter number of gallons: ";
  66. cin >> gallons; // Read the inputs from the user
  67. liters = gallons * 3.7854; // convert to liters
  68. cout << "Liters: " << liters << endl;
  69. return 0;
  70. }
  71. Running session:
  72. mercury[46]% CC BasicIO.cpp -LANG:std -o BasicIO
  73. mercury[47]% BasicIO
  74. Enter number of gallons: 14
  75. Liters: 52.9956
  76. mercury[48]%

comments powered by Disqus