Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟢 Foundation  ·  Lesson 05

Structure of a C++ Program

In this lesson: Basic structure of a C++ program — headers, namespace, main, statements — labelled example with output. In Hindi & English.

What does "structure" mean?

Every C++ program, from a two-line "Hello" to a school management system, is built from the same parts arranged in the same order. Knowing this structure helps you read any program quickly and write your own without forgetting a piece. It is also a favourite short-answer question in Class 11–12 and first-year exams.

The parts at a glance

#PartExampleRequired?
1Documentation (comments)// Program to find average marksNo, but recommended
2Preprocessor directives#include <iostream>Yes, if you use library features
3Namespace declarationusing namespace std;No
4Global declarationsconst int SUBJECTS = 5;, structs, classesNo
5Function declarations / definitionsdouble average(int total);No
6main() functionint main() { ... }Yes — exactly one

A complete example

C++
// 1. Documentation: program to calculate average marks of a student

// 2. Preprocessor directive
#include <iostream>

// 3. Namespace
using namespace std;

// 4. Global declaration
const int SUBJECTS = 5;

// 5. Function declaration (prototype)
double average(int total);

// 6. main() — execution starts here
int main() {
    int marks[SUBJECTS] = {78, 85, 69, 92, 74};
    int total = 0;

    for (int i = 0; i < SUBJECTS; i++) {
        total += marks[i];
    }

    cout << "Total   : " << total << endl;
    cout << "Average : " << average(total) << endl;
    return 0;
}

// 5. Function definition
double average(int total) {
    return static_cast<double>(total) / SUBJECTS;
}
Total : 398 Average : 79.6

Each part explained

1. Documentation section

Comments at the top describe the program's purpose, author and date. The compiler ignores them. See comments in C++.

2. Preprocessor directives

Lines starting with # are handled by the preprocessor before compilation. #include <iostream> copies in the declarations for cin and cout. Other common headers are <string>, <vector>, <cmath> and <iomanip>. See header files.

3. Namespace declaration

The standard library lives in the namespace std. using namespace std; lets you write cout instead of std::cout. It is convenient in small programs; in large projects write std:: explicitly. See namespaces.

4. Global declarations

Constants, structures, classes and (rarely) variables declared outside every function are global — visible to all functions below them. Keep global variables to a minimum; global constants are fine.

5. Functions

A function must be declared before it is called. You can either define it above main(), or put a prototype (double average(int total);) above main() and the full definition below — as in the example.

6. The main() function

int main() is where the program begins. Its body is enclosed in { }. return 0; tells the operating system the program ended successfully. There must be exactly one main() in a program.

How the program is processed

  1. Preprocessing: comments are removed and #include files are inserted.
  2. Compilation: the code is checked for errors and turned into object code.
  3. Linking: your object code is joined with library code (for example, the code behind cout) to make an executable.
  4. Execution: the operating system starts the program at main().
Terminal
g++ average.cpp -o average
./average

Statements, blocks and semicolons

  • Every statement ends with a semicolon ;.
  • A group of statements inside { } is a block; function bodies, loops and if bodies are blocks.
  • C++ is case-sensitive: Main, MAIN and main are different names.
  • Whitespace and line breaks are free-form, but good indentation matters to readers.

Structure with a class

In object-oriented programs, a class is usually declared in the global section and used from main():

C++
#include <iostream>
#include <string>

class Student {
public:
    std::string name;
    int marks;
    void show() const {
        std::cout << name << " scored " << marks << "\n";
    }
};

int main() {
    Student s{"Priya", 91};
    s.show();
    return 0;
}
Priya scored 91

Common mistakes

  • Missing #include <iostream> — "cout was not declared in this scope".
  • Calling a function before it is declared and without a prototype.
  • Writing void main() — standard C++ requires int main().
  • Forgetting the semicolon after a class or struct definition: class A { };
  • Two main() functions in files that are compiled together.
🏋️ Practice

Write a program with all six parts: a header comment, #include <iostream>, a global constant TAX_RATE, a function prototype double withTax(double price), main() that reads a price and prints the price with tax, and the function definition after main().

Summary

  • A C++ program has documentation, preprocessor directives, namespace, global declarations, functions and main().
  • Only main() is compulsory, and there must be exactly one.
  • #include lines are processed before compilation.
  • Declare (or prototype) functions before calling them.
  • return 0; signals successful completion.

Next: comments in C++ · Back: first C++ program.

Frequently Asked Questions

What is the basic structure of a C++ program?
A typical C++ program has: (1) preprocessor directives such as #include <iostream>, (2) an optional using declaration or namespace, (3) global declarations like constants, structures and classes, (4) user-defined functions, and (5) the main() function where execution starts, usually ending with return 0;.
Why is main() necessary in C++?
main() is the entry point: when the operating system runs your program, execution begins at the first statement of main(). A complete program must have exactly one main() function, otherwise the linker reports an "undefined reference to main" error.
What does return 0 mean in C++?
return 0; ends main() and sends the value 0 back to the operating system, which by convention means "the program finished successfully". A non-zero value signals an error. If you leave it out of main(), C++ automatically returns 0.
What is the difference between #include and #include "myfile.h"?
Angle brackets tell the compiler to look in the standard system include directories, which is used for library headers. Double quotes make it look in your project folder first, which is used for your own header files.
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicComments in C++ Your progress: 5 / 81 (6%) · Lesson 6 / 81 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free