Lab Zero

Our First Program : Hello World

/* HelloWorld.cpp
 * Author: tauk
 * The classic hello world program in CPP
 */
#include <iostream>
using namespace std;
 
int main() {
   cout << "Hello World" << endl;
   cin.get();
   return 0;
}

Explanation of the above program

The first line is the comment and we have put the name of source file.
To put comments use either C style comments

/* this is is comment */

or the C++ Style Comments

//this is also a comment

You can use the C Style comments over multiple lines

/* HelloWorld.cpp
 * Author: tauk
 * The classic hello world program in CPP
 */

The program starts with the following line

#include <iostream>

which includes the iostream header file into our program. The iostream header file defines input/output functions such as cin and cout

The second line is

using namespace std;

which tells the compiler that we are using namespace std . namspace is similar to a Java package. std is the name of the namespace we are using. All standard C++ functions are defined in the std namespace.
In our example we are using cin and cout and these are defined in the std namespace.

The next important line in the program in the following

int main() {

The main() function is where in the program starts and ends. The main() function calls other functions and the controls return to the main().

In ANSI C++ main() must return an int. As we see in our example program above we return 0.

For now you can return 0 or not return anything which is the same as returning 0. However remember that in case of errors during program execution values other than zero are to be returned by main().

The first two lines in main() are of interest to us. The first line in main() is

cout << "Hello World" << endl;

which outputs to the console (also called standard output which is the screen by default). « is the redirection operator in this context of cout. The above line means redirect the "Hello World" string to the standard output.

The second line in the main() is

cin.get();

cin is used to read input from the console. Here we are using cin.get() to make the program stop executing until we give it some input from standard input (which is usually the keyboard). If we do not have this line the output window will go away very quickly and we will not be able to see the output on the console(screen).

The last line of the program return 0 has already been explained above.

Exercises

  1. Modify the above Hello World program to remove or comment the using namespace std; line and try to compile the program. Does it compile?
  2. Modify the above Hello World program and remove the cin.get() line and compile and run. What is the difference in the output?
  3. Modify the above Hello World program and remove the return 0; line. Compile and run. Note any differences.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License