|
Now lets break this down. The first line "//My first program" is a comment, the compiler will ignore this line completely. To add comments to your program, simply begin the line with "//" and anything after that will be ignored.
The first line of actuall code tells the compiler that we want to include "iostream" in our program. iostream is part of the standard library, all C++ compilers will understand any command included in any part of the standard library. iostream contains the basic I/O functions used to write to the screen and recieve input from the user.
The next line "using namespace std;" defines what namespace we will be using, in this case std. A namespace is basically a list of variable and function names, in order to not get standard library names mixed with others, the standard library creates the namespace std, so any time you want to use a command from the standard library you must include this line. The semicolon at the end of the line is needed for almost every line in C++, this tells the compiler that it has reached the end of that line.
"int main(){" this is a function decleration. A function is a block of code which begins and ends with a pair of curly brackets " { } ". This way we have a way of referencing this block of code in case if we want the program to run the same code multipule times. Functions also help keep the code looking clean. "int" is the data type the function returns, we will discuss data types later. "main" is the name of this function, every C++ program must have a main() function, this is where the program will begin to execute. If you want to pass a variable to a function, you would place the type of variable and specify a name for it between the parenthesis, for example "int myFunction( int number)". The curly braket shows where the function begins.
"cout << "Hello World!\n";" This line displays the text "Hello World!" on the screen. cout takes the text using "<<" which is known as an insertion operator. Think of it as a funnel, we want the data, in this case "Hello World!", to be "funneled" into cout. The "\n" means new line, its like pressing the enter key while typing in a text editor.
"system("Pause");" system() is used to send commands to the operating system, in this case we are sending "pause" which is a DOS command which pauses the screen until the user presses any key. I included this because once the program runs out of code to execute, it will close the window and you will not get a chance to see the results.
Ok now lets see it in action, type the code into Dev-C++, do not copy and paste it. You can copy and paste if you want, it will work just fine, but it will help you memorize the code quicker if you type it yourself. Once done, save it and press the compile button, once it finished press the run button. You should be presented with a DOS prompt which will give you this output:
Hello World!
Press any key to continue...
Too easy isn't it? Lets move on to data types.
|