C++ Code For Printing Hello World

3 min read Jul 01, 2024
C++ Code For Printing Hello World

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:

  1. #include <iostream>: This line includes the iostream library, which provides input and output functionalities, including the cout object used for printing to the console.

  2. int main() { ... }: This is the main function, the entry point for the C++ program. Any code inside this function will be executed.

  3. 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.
  4. 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:

  1. Save the code: Save the code as a file named hello.cpp (or any other name with a .cpp extension).
  2. Compile the code: Use a C++ compiler like g++ to compile the code:
    g++ hello.cpp -o hello
    
    This will create an executable file named hello.
  3. Run the executable: Execute the program using:
    ./hello
    
    You should see "Hello World!" printed on your console.

Now you've successfully written your first C++ program!