Structure of a Program
Let’s look at what every C++ program is made of.
#include <iostream>
using namespace std;
// Your first program!
int main() {
cout << "Hello, World!";
return 0;
}Building Blocks
- Preprocessor commands
- Start with
#, like#include <iostream>. - They tell the computer to include extra tools before running the program.
- Start with
- Namespaces
- We often write
using namespace std;. - You don’t need to understand namespaces deeply now, just always add this line.
- We often write
- The
main()function- This is where your program starts running.
- The computer executes commands from top to bottom inside
{ ... }.
- Curly braces
{ }- They group instructions together.
- You will see them in functions, loops, and if-statements.
- Semicolons
;- Every instruction (line) ends with a semicolon.
- Forgetting it will cause an error.
- Return statement
return 0;ends the program and tells the computer everything went fine.
What happens here?
#include <iostream>tells the computer we want to use input/output commands.
using namespace std;lets us writecoutinstead ofstd::cout(shorter and easier).
int main()every program starts here.
{ ... }everything inside the curly braces is part of the program.
cout << "Hello, world!";prints text to the screen.
return 0;ends the program.
When you run this, you will see:
Hello, world!
That’s your first program!
Indentation and readability
Always indent the code inside {} with a tab or 4 spaces. It makes programs easier to read:
int main() {
cout << "Good style matters!";
}Bad style :
int main(){
cout<<"Hard to read";
}
Comments
Comments are notes for humans, not computers. The computer will ignore these lines, and they only serve to remind you, as a programmer, of certain functionalities.
You will often write comments to remind yourself what something does.