C++ Programming

This series of articles is developed from Storm Dragon's class.

Lesson 1: Hello World!

Reading

Before you begin, please read this article: Structure of a Program

Writing the Program

In the editor of your choice, please write the following code. Note: The bluefish editor version 2.02 allows for an automatic structuring of a c++ program.

// My first c++ program
#include <iostream>
using namespace std;
int main ()
{
   cout << "Hello World!";
   return 0;
}

Note: It is important to either read character by caracter or set your punctuation level to all in your Orca preferences for your editor.

Explanations

  1. The first line of the program is a comment. The program will stop reading the line when it encounters "//" (two slashes).
  2. We include input/output preprocessing.
  3. We declare standard global variables.
  4. We leave a blank line. This is not manditory but it is a convention for readability.
  5. We define the main function. This is where the program begins. Note: The word main is followed by a pair of brackets "()". These are rounded brackets. Americans call these parenthesies.
  6. We write a left-brace ({). All functions are enclosed by braces.
  7. We print our message to the screen. Notice the two left pointing arrows (less than characters <<). These tell the program to insert the words "Hello World" into the standard output stream. Note: The statement ends with a semicolon (;). All statements end with a semicolon.
  8. We set a return code of zero (0) and exit the main function.
  9. We end the main function with a right-brace (}).

Compiling the Program

Although not absolutely necessary, save your program with the "cpp" extension. We assume, for this exercise, you have named your program

hello1.cpp
and that it is stored in your home folder.

To compile "hello1.cpp", at a terminal or console prompt, type:

c++ hello1.cpp

If your prompt returns with no messages, your program has compiled successfully. Otherwise, you will need to correct your code and compile the program again.

Run Your Program

Your compiled program is in a file called

a.out

To run your program type:

./a.out

You may, of course, rename your program to something more meaningful than "a.out". It will also save your compiled program if you rename it; otherwise, the next compile you do will overwrite it.

Note: The "./" tells the operating system you understand you are executing a program.

Formatting Your Output

If we want to write more information to the screen, we may also want to format it. We can edit the line which begins "cout <<" to read as follows:

cout << "Hello World" << endl;
This will put an end-of-line character in our output stream. Now our prompt will appear on a separate line from our message to the world.

Assignment

  1. Write a new program which will display the following message on a line of its own:
    I am a c++ program.
    
  2. Read the article Variables, Data Types