Search This Blog

Saturday 25 January 2014

"Hello World" C++ Program

A “Hello World” program is usually the first program that beginner programmers learn. It is essentially a program that gives an output : “Hello World”. It is used to showcase the basic syntax and structure of the programming language. The Hello World program in C++ is as follow:

Hello World Program

Code Explained:
1.       #include<iostream.h>:  This is called a pre-processor directive. A pre-processor directive instructs the compiler which library files to include in the program. A library file is a file which contains reusable pre-written code which can be used in other programs. The “iostream.h” file contains code concerning input and output.
2.        void main() : It is a function header. C++ programs are written using functions, which are modules which do some specific work. Functions help to modularize the code which is useful while debugging. The main function is the entry point of a C++ program where the program execution begins. The body of the function is enclosed within curly braces({}). We will study functions in detail in later chapters.
3.        cout<<”Hello World”; : This is the statement to print “Hello World”. cout is an output statement defined in the “iostream.h” library which is used to give an output. “<<” is known as cascading signs which shows that data is to be outputted. “Hello World”, ie the message to be printed is enclosed in double quotes, as it is a string, (we will study them in detail later). At the end, every C++ statement end with a ‘;’, which is also called terminator.
A Minor Change
If you followed every step and tried to compile and run the program, you must have noticed that the output console window just flashes in and out within a fraction of second. This is because C++ is a very fast language, and it displays the text and closes the program very quickly. In order to see the output, we have to make a little change.
Add this line before the main function:
#include<conio.h>
And this line at the end:
getch();
At the end, your program must look like this:

If you have followed the steps correctly, you will get the following output:


What does the modification do?
1.       #include  : “conio.h” is another library files. It stands for “Console Input Output”. It defines statements related to input/output using the console.
2.       getch() : It is a predefined function in conio.h. It pauses the program until any character key is pressed by the user on the keyboard.
What did we learn

Today, we learned the how to write the most basic C++ program and learned a few new terminologies. Next day, we start learning C++ in earnest, see what goes on behind the scenes of popular programs we use.

No comments:

Post a Comment