Before going deep into the C++ language details, let us get started
with full-fledged C++ program! Idea of this program is to introduce the
overall structure of C++ program and give you flavor of the C++.
A D V E R T I S E M E N T
//include this file for cout
#include <iostream.h>
int main()
{
//print out the text string, "Hello, World!"
cout << "Hello, World!" << endl;
return 0;
}
To prepare next section, create a new text file and save this code into
the file. If you are using unix machine, save a file with a filename hello.C
(.C is a file extension). If you using Windows machine, save file with a filename
hello.cpp.
Brief Explanation of the program "Hello, Dave"
Let us look at each line of the code which makes the hello.C.
//include this file for cout
This is a comment line. "//" indicates that everything that follows this symbol should
be ignored by compiler. This allows to add some explanatory note, which might
otherwise be confusing code. You have a freedom to comment the code as you
like -- some programmers will not use any comments; others do write multi
line comments for C++ code. It is up to you. But one should add comments.
It is good way of writing the code, because programmers often do not understand the code
they have written a week ago!
#include <iostream.h>
The line is read as "pound include i-o-stream dot h". Effect of this line is
it will just "copy and paste" entire file iostream.h into the file at
this line. It is like the syntax as replacing a line #include <iostream.h>
by the contents of a file iostream.h. "#include" is known as the preprocessor directive,
int main() {
Every program in C++ should have what is known as the main function. When you run a
program, program will go through every line of the code in main function and will execute
it. If the main function is empty, then the program will do nothing.
//print out text string, "Hello, World!"
This is a comment line which the compiler ignores anything following the
"//" (till the end of a line), By commenting we can say whatever we want on these lines.
cout << "Hello, World!" << endl;
This is a line which will print the text string, "Hello, World!". For now, do not
worry about the working of the cout just try to know how to use it. You can print out any
series of the text strings by separating them by <<. So, instead of saying it cout << "Hello, World!"
<< endl;, you could say cout << "Hello, " << "World" << "!" << endl;.
The statement endl simply adds the carriage return (the stands for the "end-line").
return 0;
Since the return type of main is int This line of code is necessary. Let us
see about the functions and the return types later, for now understand that
the function's return type is an integer type, the function should return an
int. return 0; will simply returns 0.