Writing Your First C++ Program
Once the environment is ready, you can write your first C++ program.
General Syntax:
#include <iostream>
using namespace std;
int main() {
// Statements
return 0;
}
Example:
#include <iostream>
using namespace std;
int main() {
cout << “Hello, C++ World!” << endl;
return 0;
}
Output:
Hello, C++ World!
Compiling and Running a C++ Program
The way you compile and run your code depends on the environment you’re using:
- a) Using GCC in Command Line (Linux or MinGW on Windows)
- Save the code in a file named program.cpp.
- Open the terminal or Command Prompt.
- Compile using: g++ program.cpp -o program
- Run the compiled file:
- On Linux/macOS: ./program
- On Windows: program.exe
- b) Using an IDE (e.g., Code::Blocks or Visual Studio)
- Open the IDE.
- Create a new C++ project.
- Paste your code into the editor.
- Click Build or Compile, then Run.