Hello world

From Tux
Jump to: navigation, search

A typical first program in many programming languages is called hello world and refers to a basic program that is only designed to display text to the screen. This program is meant to be used to illustrate some of the basic features of a programming language, such as syntax and style. The terms program, source code, and code can be used interchangeably.

For C++, the hello world program is as follows:

 1 // This is a hello world program
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8         cout << "Hello world!" << endl;
 9 
10         return 0;
11 }

The following is a brief description of what each line is used for:

  • Line 1: Lines that start with // are comments and are not technically part of the program but are often written to describe the code or insert other useful information such as the author.
  • Line 2: This is a preprocessor directive that includes the header file iostream which we need to use coutand endl on line 6.
  • Line 3: This is a blank line which is used to improve code readability.
  • Line 4: This is a line that makes it easier to use commands in the standard namespace. This will be described in more detail later, but for now just know that it should be part of most programs that you write.
  • Line 5: Another blank line used to improve code readability.
  • Line 6: int main() is the definition of the main body (or main function) that describes where the program actually starts. Every C++ program contains this function. int refers to the fact that this function should return an integer to end it.
  • Line 7: { signifies the beginning of the main body block.
  • Line 8: This is a statement. Note that this code is indented. This is not technically required but improves code readability. Further details about this line are as follows:
    • cout is used to display output to the terminal
    • << is used to separate various things that will be displayed
    • "Hello world!" is a string
    • endl is used to end the line on the output, going to the next line on the display
    • ; is used to signify the end of the statement.
  • Line 9: Another blank line used to improve code readability.
  • Line 10: return 0; is the final line of the main body and returns an integer (in this case, 0) that matches line 6.
  • Line 11: } signifies the end of the main body. Note that this lines up in the same column as line 7.
  • Note that programs do not contain actual line numbers as shown above; the addition of line numbers is a function of the Wiki software and helps in referring to specific lines in our descriptions