C++ Code for Printing "Hello World!"
This is a classic first program for anyone learning a new programming language. Here's a simple C++ code to print "Hello World!" to the console:
#include
int main() {
std::cout << "Hello World!" << std::endl;
return 0;
}
Explanation:
-
#include <iostream>
: This line includes the iostream library, which provides input and output functionalities, including thecout
object used for printing to the console. -
int main() { ... }
: This is the main function, the entry point for the C++ program. Any code inside this function will be executed. -
std::cout << "Hello World!" << std::endl;
: This line prints the string "Hello World!" to the console. Let's break it down:std::cout
: This is the standard output stream object, used for printing data to the console.<<
: This is the insertion operator, used to send data to the output stream."Hello World!"
: This is the string literal containing the text to be printed.std::endl;
: This manipulates the output stream to insert a newline character, moving the cursor to the beginning of the next line.
-
return 0;
: This line indicates that the program executed successfully. Returning a value other than 0 would indicate an error.
Compiling and Running the Code:
- Save the code: Save the code as a file named
hello.cpp
(or any other name with a.cpp
extension). - Compile the code: Use a C++ compiler like g++ to compile the code:
This will create an executable file namedg++ hello.cpp -o hello
hello
. - Run the executable: Execute the program using:
You should see "Hello World!" printed on your console../hello
Now you've successfully written your first C++ program!