Here is an example of a simple C++ program that prints “Hello, World!” to the console:
#includeusing namespace std; int main() { cout << "Hello, World!" << endl; return 0; }
Let's go through each line of the code:
- `#include
- `using namespace std;`: This line tells the compiler to use the standard namespace, which contains many C++ library functions.
- `int main() {`: This line defines the main function, which is the entry point of the program. The function returns an integer value, which is typically 0 if the program runs successfully.
- `cout << "Hello, World!" << endl;`: This line uses the cout object to output the string "Hello, World!" to the console. The `<<` operator is used to insert the string into the output stream, and the `endl` manipulator is used to insert a newline character. - `return 0;`: This line returns the integer value 0 to indicate that the program ran successfully. To run this program, you need to follow these steps: 1. Open a text editor (such as Notepad, Sublime Text, or Visual Studio Code) and copy the above code into a new file. 2. Save the file with a .cpp file extension (for example, helloworld.cpp). 3. Open a command prompt or terminal window and navigate to the directory where you saved the file. 4. Type the following command to compile the program:
` g++ helloworld.cpp -o helloworld
This command uses the g++ compiler to compile the program and create an executable file called helloworld.
5. Type the following command to run the program:
` ./helloworld
This command runs the helloworld executable and should output "Hello, World!" to the console.
That's it! You have written and run a simple C++ program.