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

  1. Preprocessor commands
    • Start with #, like #include <iostream>.
    • They tell the computer to include extra tools before running the program.
  2. Namespaces
    • We often write using namespace std;.
    • You don’t need to understand namespaces deeply now, just always add this line.
  3. The main() function
    • This is where your program starts running.
    • The computer executes commands from top to bottom inside { ... }.
  4. Curly braces { }
    • They group instructions together.
    • You will see them in functions, loops, and if-statements.
  5. Semicolons ;
    • Every instruction (line) ends with a semicolon.
    • Forgetting it will cause an error.
  6. Return statement
    • return 0; ends the program and tells the computer everything went fine.

What happens here?

  1. #include <iostream> tells the computer we want to use input/output commands.
  2. using namespace std; lets us write cout instead of std::cout (shorter and easier).
  3. int main() every program starts here.
  4. { ... } everything inside the curly braces is part of the program.
  5. cout << "Hello, world!"; prints text to the screen.
  6. return 0; ends the program.

When you run this, you will see:

Hello, world!

That’s your first program!

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.

// This is a single-line comment

/*
This is a
multi-line comment
*/

You will often write comments to remind yourself what something does.

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";
}