At this point you should have a blank file on the screen, with no code in it. Before you can actually write any code you need to set up the skeleton of the file. Every keyword in C++ is lowercase, so if you type something in uppercase and it isn’t working, now you know why. The first thing you will need is to include the header file for input and output.
#include <iostream> |
The next step would be to set it so that you can reference the code in the header file easily. Without this step you, everytime you would want to use a function you would need to specify which file it was in. To make it reference the header file without much hassle:
using namespace std; |
Notice the semicolon. In C++ mostly every line of code must have a semicolon at the end of it, otherwise it will be a syntax error.
For the main part of our code, we will need to put it in the main function. There are two ways to do this and while we won’t cover what they both mean, just yet, I will show you both of them and you can decide which way to use.
First Way: void main() { } |
Second Way: int main() { return 0; } |
In both ways all your code is going to go between the curly braces{}. I prefer to do it using void, it is the way I was taught, but I was taught using the .NET compiler. If your compiler doesn’t allow you to use void main then you must use int main instead. So the whole skeleton would look like:
#include <iostream> using namespace std; void main() { //Code here } |
#include <iostream> using namespace std; int main() { //Code here return 0; } |
That is valid code. To compile it, go to the green play button at the top, or just hit F5 and it will ask you if you want to compile it. Select yes and you should get a black screen that looks like a command prompt that opens for just a split second and then closes.
Now onto the coding.