Tuesday, September 11, 2012

First C++ Program

Start your preferred IDE for C++ and create a new Console Application or a new project. Name it as you desired. For Visual C++ and Visual Studio, Create a new Project->Other Languages->Visual C++->Win32->Win32 Console Application. Next Next...Check the check box for empty project.


For Visual C++/Visual Studio,
  1. In the Solution Explorer tab, right click the source files (folder icon), add->new item
  2. Select C++ File, name it main or a name that you desire.
Try to code this and run your program. For Visual C++ or Visual Studio Pressing F5 will run the program.
Please post your comments if you have problems doing it. Thanks!

#include <iostream>

using namespace std;

int main()
{
    cout<<"Hello World!";
    cin.get();
    return 0;
}


#include <iostream> - #include is a preprocessor directive, #include <iostream> tells the compiler to include the file iostream that contains functions/method declarations for standard input/output that will be used like cout (System.out.println in JAVA).

using namespace std; - the elements/functions/methods in the iostream are declared in a namespace with the namespace std. To access its functionality we will use this entities. This line is a frequently used line for Console apps in C++.

int main() - like in JAVA, it is the starting point of a program. Open curly brace { indicates the beginning of the function main() and Close curly brace indicated the end of the function main();

cout<<"Hello World!"; - cout is the standard output stream in C++, it is declared in the iostream. << is an insertion operator telling that the string "Hello World!" will be the output. cout is like System.out.print in JAVA.

semicolon ; - it is a very important character in C++ in order to end a command statement. This is a common error among programmers.

cin.get(); - is a function to accept a character input from the user. This is used here so that the console app will not close immediately after displaying Hello World!.

return 0; - the method main will return a value of 0. This is a common use to indicate a successful program exit or execution.

Done!
If you have problems, please comment. Thanks!

Next: C++ Variables

No comments:

Post a Comment