SrcForge

Lesson 2

Basic Syntax and Structure

A beginner-friendly guide to C++ program structure, syntax rules, and common building blocks.

Lesson content

C++ basic syntax defines how every C++ program is written and organized. Understanding the structure of a simple C++ program helps beginners learn how code executes, how output works, and how statements are written correctly.

What is C++ basic syntax?

C++ syntax is the set of rules used to write valid C++ programs. Every C++ program contains elements like header files, functions, statements, data types, and blocks of code.

Basic C++ program structure

#include <iostream>

int main() {
  // Print Hello, World! to the console
  std::cout << "Hello, World!" << std::endl;
  return 0;
}

Understanding the structure of a C++ program

  • include: Used to include a header file in the program.
  • iostream: Standard Input/Output header file used for input and output operations.
  • int: A data type used to store integer values.
  • main(): The main function is the execution starting point of a C++ program.
  • { }: Curly braces define a block of code.
  • return: Indicates the program has reached the end of execution.
  • ;: Used to terminate a statement in C++.

Example of C++ basic syntax

#include <iostream>

using namespace std;

int main() {
  cout << "Hello, World!" << endl;

  int a = 5, b = 3;
  int sum = a + b;

  cout << "Sum: " << sum << endl;
  return 0;
}

Explanation of the example

  • using namespace std;: Lets you use standard library names like cout and endl without writing std::.
  • cout: Displays output on the console.
  • endl: Moves the cursor to the next line after printing output.
  • int a = 5, b = 3;: Declares two integer variables and assigns values.
  • int sum = a + b;: Adds a and b and stores the result in sum.

Why learning C++ syntax is important

  • Write valid C++ programs
  • Understand how program execution works
  • Use variables and functions correctly
  • Perform input and output operations
  • Build a strong foundation for advanced C++ concepts

Frequently asked questions

What is the purpose of the main() function in C++?

The main() function is the starting point of every C++ program.

Why is #include <iostream> used in C++?

It includes the standard input/output library for cout, cin, and endl.

What does a semicolon (;) do in C++?

It marks the end of a statement.