1. //Hello World Program 2. #include <iostream.h> 3. 4. void main () 5. { 6. cout << "Hello World\n"; 7. }
Now lets look at each line in detail.
Line 1
This is a comment. A comment is some text in a program which is just used for
documentation purposes. A comment starts with the characters '//' then some text.
When your program is compiled, the compiler ignores all text from the two slashes
up to the end of the line.
You can also use the C programming style of comments where the comment starts with '/*' and ends with '*/'. All text between these are ignored and the text can be over multiple lines. For example:
/* Hello World Program This is using the C programming style comments */ #include <iostream.h> void main () { cout << "Hello World\n"; }
Line 4
This is the beginning of the main function. It is called the function header. The code
that you want to execute must be within a function and you can return values back
from a function. Functions will be dealt with in more detail in a later section. Every
program must have a main function and it is always the first function executed in a
program.
The first part of a function header tells the compiler what type of data should be returned from the function, then the name of a function and then any data you want to pass to a function. In this case the first part of the header is the word 'void', this means that the function does not return any value. After 'main' you will see two parentheses '()'. Inside the parentheses would be any information to pass to the function, but in this case we have no information to pass so we leave it blank.
Line 5
This lines contains the open curly brace character '{'. This tells the compiler that any
statements following this are part of the main function. All function must have a start
and end brace.
Line 6
This line prints the word Hello World on the screen. The cout command is a data stream which
is attached to screen output and is used to print to the screen, it is part of the iostream library.
At the end of Hello World there is a special character '\n'.
This representes the new line character and the '\n' should be treated
as a single character. It tells the computer to move down one line and continue
outputting from there. The << symbol is called the stream insertion operator
and it is used to insert the following data into the cout stream which then pirnts is to the screen.
Line 7
This line contains the closing curly brace character '}'. This tells the compiler that
the end of the function has been reached.
Type in the program, compile and run it. If you have no errors then your should see the words Hello World appear on the screen.