Structure of a C++ Program
Every C++ program follows a basic structure. Once you understand what each part does, reading and writing C++ code becomes much easier. Let’s look at a simple C++ program and understand it line by line.
Example
#include <iostream>
using namespace std;
int main() {
cout << "Welcome to CoderMantra!";
return 0;
}
Program Structure
1. Header File
#include <iostream>
This line includes the iostream header file, which provides input and output features in C++. Without it, you cannot use cout or cin in your program.
2. Namespace
using namespace std;
The std namespace contains many built-in C++ features. Writing using namespace std; allows you to use cout, cin, and other standard library objects without adding std:: before them every time.
3. Main Function
int main()
The main() function is where every C++ program begins execution. When you run a program, the compiler starts executing the code inside this function.
4. Program Statements
cout << "Welcome to CoderMantra!";
This statement displays the text Welcome to CoderMantra! on the screen. Every statement in C++ ends with a semicolon (;).
5. Return Statement
return 0;
The return 0; statement tells the operating system that the program has finished running successfully.
Key Points
- Every C++ program starts from the
main()function. - The
iostreamheader file is required for input and output. using namespace std;makes standard library names easier to use.coutis used to display output on the screen.- Every statement should end with a semicolon (
;).
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.