1. Basic "Hello, World!" Program

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

2. Explanation

  • #include <iostream>: Includes the standard input-output stream library.
  • int main(): The main function where execution starts.
  • std::cout: Outputs text to the console.
  • << "Hello, World!": Sends the string to cout for display.
  • std::endl: Ends the line (can also use "\n").
  • return 0;: Indicates successful program execution.

3. Compiling & Running

  • Compile: g++ hello.cpp -o hello
  • Run: ./hello (Linux/macOS) or hello.exe (Windows)

4. Alternative Using printf

#include <cstdio>

int main() {
    printf("Hello, World!\n");
    return 0;
}
  • Uses printf from <cstdio> (C-style output function).

5. Using namespace std

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}
  • Eliminates std:: prefix but may cause namespace conflicts.

6. Hello World in a Function

#include <iostream>

void sayHello() {
    std::cout << "Hello, World!" << std::endl;
}

int main() {
    sayHello();
    return 0;
}
  • Defines sayHello() to encapsulate printing logic.