Sunday, October 17, 2010

Lesson 1: Introduction to C++: Hello World

The Introduction:
The classic "Hello World" program for C++ is simple. It simply opens command prompt and writes "Hello World" for you to see (and in our example, it waits for any input of the user before it allows the command prompt window to close.)

The Code:
#include <iostream>
int main()
{
std::cout<<"Hello World!";
std::cin.get();
return 0;
}

The Breakdown:
#include <iostream>
IOStream enables you to use functions that exist in the "iostream library." This includes Input and Output functions. Input functions include cin.get(); .  Output functions include cout<<. (Another input function is cin>>...; with the signs pointing a different direction, but we will get to that later.)

int main(){....return 0;}
This is the main function, meaning that when your program first launches, anything within the brackets is executed in the order in which it is listed.
-The reason for it being "int" or having "return 0;" is irrelevant as of now; that is just the way it is (note that some compilers do not require main to be "int," but it usually necessary.
-Since main is declared as an "integer," it must return an integer as well, whether is is 0, 1, or 93. 
Therefore int examplefunction() must also return an integer and string examplefunction() must return a string, but void examplefunction() need not return anything... but we will get to other functions like "string" and "void" later.
-The brackets, { and }, are used almost as a container for everything inside of the main function. It makes it visually easier to manage as well.

std::cout<<"Hello World!";
This function, cout lets you write words or numbers to command prompt. (We'll explain "std" later.)

std::cin.get();
This function, cin makes your program wait for an input (anything followed by the Enter key) before it continues to execute.

The Screenshot

No comments:

Post a Comment