Wednesday, July 14, 2010

C++: A sample program

Many beginning C++ (and other programming language) books start out with a
simple program named "Hello World," which became popular after the example
from "The C Programming Language" book by Brian karnigan and Dennis Ritchie.
The concept is used to introduce the syntax of a given language to new
programmers. I, too, wrote the "hello World" program as my first program at
school (well, almost the first program).

Here's how it is written in C++:
#include <iostream>
#include <string>
using namespace std;

int main()
{
cout << "Hello, World!" << endl;
return (0);}

In English, it is written: Print out the words, "Hello World!" onto the
computer monitor.

I'll explain what the words "cout" and int main() means later, but it is
important now to go over something crucial: Every C++ statement - that is,
C++ phrase - ends with a semicolon (;). If we forget to put that, the
compiler (the program used to translate source code, or things written in a
programming language to machine code) will complain and ask you to put it
in. So, for instance:
cout << "Hi, my name is Joseph." << endl;
Is legal, but:
cout << "Hi, my name is Joseph." << endl
is not.

Another thing: the "endl" just means put a new line when printing
information to the monitor (or any output device, as explained later). There
is another method, and that is using "\n" - from ASCII code, like:
cout << "Hi, my name is Joseph.\n";
will do the same thing as in the code with "endl" above.

2 comments:

  1. Nice explanation, but there is one typo when you are giving an example about code with and without semi-colons. It's the double angle bracket near "endl".

    ReplyDelete