CMPT 225 Lab 0: Hello World


In this lab we will write a simple C++ program.

Creating your main function

All C++ programs start their execution at the main function. This is similar to Java, though different in that the C++ main function is not contained in a class. We will create a very simple main function that prints "Hello world!".

Some explanations

To get input and print output in C++, use the cin and cout functions.  cin is used for input and cout for standard output (to the display).  But first you need the appropriate library.

Include statements

Your program must start with include statements to import the necessary libraries.  The only library you will need for this program is the iostream library which contains the cin and cout functions.  In addition you will need to open the standard namespace to access these functions.  That is the function of these lines above the main function.

#include <iostream>
using namespace std;

Using cin and cout

To get input from the keyboard into a variable named x:

int x = 0;
cin >> x;

To send output to the display:

cout << x;

Note that this will not print the value of x on a new line, but you can use endl to specify a newline.  Below I'm printing the value of x on a new line (with some explanatory text) and then printing another line:

cout << endl << "The value of x is: " << x << endl;

Return values

By convention, main functions return the value 0 if everything went well. Other values can be used to denote various forms of failure or output results.

Compiling your main function


Say hello

Modify hello.cpp to have the following behaviour: This must be the only output from your program (e.g. no other prompts). There must be no newline (endl) at the end of these either.
uname@hostname: ~$ ./hello_world
5
Hello world!
uname@hostname: ~$ ./hello_world
42
Shh!

Testing

This program was quite simple, but we will illustrate how we might test this program. Download this zip file and save and unzip it in your lab0 directory:
uname@hostname: ~$ unzip lab0-test.zip
uname@hostname: ~$ ls
1.gt          2.in          a.out         hello_world   test.py
1.in          2.gt          hello.cpp     lab0-test.zip
Run the program test.py it contains:
uname@hostname: ~$ ./test.py
If you have correctly modified hello.cpp as specified above, you will see:
Running test 1... passed
Running test 2... passed
Passed 2 of 2 tests
test.py is a Python script, as you might have guessed. The "shebang" (#!) line tells linux to use python to run it. It uses input/output "redirection" (>,<) to pass input (*.in) to your hello_world program and compare (diff) this output (*.out) against specified output (*.gt).

If you have passed 2 of 2 tests, please ask a TA to take a look, and receive your 1 mark for this lab.


Back to the CMPT 225 homepage.