Writing your first C++ program is a great way to start learning the language. Here’s a simple example to get you started. This program prints “Hello, World!” to the console.
#include <iostream>
int main() {
// This is a simple C++ program that prints “Hello, World!” to the console.
std::cout << “Hello, World!” << std::endl;
// The main function must return an integer value (usually 0) to indicate successful execution.
return 0;
}
Now, let’s break down the code:
#include <iostream>
: This line includes the Input/Output Stream Library, which is necessary for performing input and output operations.int main()
: This is the main function where the program execution begins. Every C++ program must have amain
function. Theint
beforemain
indicates that the function returns an integer value.{}
: The curly braces{}
denote the beginning and end of themain
function’s block.std::cout << "Hello, World!" << std::endl;
: This line prints the text “Hello, World!” to the console.std::cout
is used for output, and<<
is the output stream operator.return 0;
: Themain
function should return an integer value (usually 0) to the operating system, indicating that the program executed successfully.
To run this program, you need a C++ compiler installed on your system. Save the code in a file with a .cpp
extension (e.g., hello.cpp
). Then, open a terminal or command prompt and navigate to the directory containing your file. Use the following commands to compile and run the program:
g++ hello.cpp -o hello
./hello
This assumes you have the GNU Compiler Collection (g++) installed. Adjust the commands accordingly if you’re using a different compiler. After running the program, you should see “Hello, World!” printed to the console.