Hello World!, Variables and Basic IO 


Contents of this section:

  1. Hello World!
  2. Variables and Constants
  3. Basic IO

1. Hello World:

    Code Listing: 

(Note: lines started with // are comments, which will be ignored by the compiler)


// File name: HelloWorld.cpp
// Purpose:   A simple C++ program which prints "Hello World!" on the screen

#include <iostream>  // need this header file to support the C++ I/O system
using namespace std; // telling the compiler to use namespace "std",
		     // where the entire C++ library is declared.
	
int main()
{
        // Print out a sentence on the screen.
        // "<<" causes the expression on its right to 
        // be directed to the device on its left.
        // "cout" is the standard output device -- the screen.
	cout << "Hello World!" <<  endl;
	return 0; // returns 0,which indicate the successful	
		  // termination of the "main" function 
		     
}

    Running session:

mercury[24]% CC HelloWorld.cpp -LANG:std -o HelloWorld
mercury[25]% HelloWorld
Hello World!
mercury[26]%

2. Variables and Constants

Code listing:

// File name: ~ftp/pub/class/cplusplus/HelloWorld/Variable.cpp
// Purpose:   Demonstrate the use of variables and constants
//
#include <iostream>
using namespace std;
// declaring a constant.  It's value cannot be changed.
const int CONST_VAL = 5;        
int main()
{
	int    iValue;  // An integer variable
	float  fValue;  // A floating point variable
	char   cValue;  // A character variable
	
	iValue = 1234;    // Assigns 1234 to iValue
	fValue = 1234.56; // Assigns 1234.56 to fValue
	cValue = 'A';     // Assigns A to cValue
	
	// Now print them out on the screen:
	cout << "Integer value is: " << iValue << endl;
	cout << "Float value is: " << fValue <<  endl;
	cout << "Character value is: " << cValue << endl;
	cout << "The constant is: " << CONST_VAL << endl;
	
	return 0;
}

Running session:

mercury[39]% CC Variable.cpp -LANG:std -o Variable
mercury[40]% Variable
Integer value is: 1234
Float value is: 1234.56
Character value is: A
The constant is: 5
mercury[41]% 

3. Basic IO

Code listing:

// File name: ~ftp/pub/class/cplusplus/HelloWorld/BasicIO.cpp
// Purpose:   Converts gallons to liters

#include <iostream>
using namespace std;

int main()
{
  float gallons, liters;

  cout << "Enter number of gallons: ";
  cin >> gallons; // Read the inputs from the user

  liters = gallons * 3.7854; // convert to liters

  cout << "Liters: " << liters << endl; 

  return 0;
}

Running session:

mercury[46]% CC BasicIO.cpp -LANG:std -o BasicIO
mercury[47]% BasicIO
Enter number of gallons: 14
Liters: 52.9956
mercury[48]% 




Last modified: Friday, 21-Aug-2020 15:28:12 CST
Copyright 2000 Department of Computer Science, University of Regina.

 CS Dept Home Page

Teaching Material

C++ Index Page