1.3) Hello World program in C++
Let’s break down the “Hello World” program in C++ step by step, including code examples with explanations and the output of the code.
Table of Contents
Step 1: Include the Necessary Header File
In C++, you need to include the necessary header file to access standard input and output functions.
#include <iostream>
This line includes the <iostream> header, which provides functions like cout (for output) and cin (for input).
Step 2: Define the main() Function
The main() function is the entry point of a C++ program. It’s where the program execution begins.
int main() {
// Code goes here
return 0;
}
The int before main() indicates that the function returns an integer value. The return 0; statement signals the successful termination of the program.
Step 3: Output “Hello, World!”
To display “Hello, World!” on the console, use the std::cout (character output) stream.
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
In the above code:
std::coutis the standard output stream.<<is the stream insertion operator, used to insert data into the stream."Hello, World!"is the text you want to output.<< std::endlinserts a newline and flushes the output buffer.
Full Code
Here’s the complete “Hello World” program in C++:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Output:
Hello, World!
Explanation:
- The
#include <iostream>line includes the necessary header. - The
main()function is the entry point of the program. std::cout << "Hello, World!" << std::endl;outputs “Hello, World!” to the console.return 0;indicates successful program execution.
This simple program demonstrates the basic structure of a C++ program and how to use the std::cout stream to output text to the console.