C++ Hello World Program
The Hello World program is the first and most basic program written when learning any programming language. In C++, it helps beginners understand the structure of a C++ program, how output works, and how code is compiled and executed.
1. Basic Structure of a C++ Program
A simple C++ program consists of a header file, the main function, and statements inside the main function. The program execution starts from the main() function.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
2. Explanation of the Code
- #include
: Includes the input-output stream library. - using namespace std; : Allows us to use standard library names without writing std:: repeatedly.
- int main() : The starting point of the program.
- cout : Used to print output to the console.
- return 0; : Indicates successful execution of the program.
3. Hello World Without Using Namespace
You can also write the program without using the namespace directive.
#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}
4. How to Compile and Run the Program
To run a C++ program, you need a compiler such as GCC or Clang.
g++ hello.cpp -o hello
./hello
If everything is correct, the output will be:
Hello, World!
5. Complete Example with User Interaction
Here is a slightly extended version where the user enters their name.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Hello, " << name << "! Welcome to C++.";
return 0;
}
Conclusion
The Hello World program is the foundation of learning C++. It introduces the structure of a C++ program, the main function, and output using cout. Once you understand this basic structure, you can move on to variables, data types, and control statements.
Codecrown