Articles

How to write your first C++ program?

Writing your first C++ program is a great way to start learning the language. Here’s a simple example to get you started. This program prints “Hello, World!” to the console.

#include <iostream>

int main() {
// This is a simple C++ program that prints “Hello, World!” to the console.
std::cout << “Hello, World!” << std::endl;

// The main function must return an integer value (usually 0) to indicate successful execution.
return 0;

}

Now, let’s break down the code:

  1. #include <iostream>: This line includes the Input/Output Stream Library, which is necessary for performing input and output operations.
  2. int main(): This is the main function where the program execution begins. Every C++ program must have a main function. The int before main indicates that the function returns an integer value.
  3. {}: The curly braces {} denote the beginning and end of the main function’s block.
  4. std::cout << "Hello, World!" << std::endl;: This line prints the text “Hello, World!” to the console. std::cout is used for output, and << is the output stream operator.
  5. return 0;: The main function should return an integer value (usually 0) to the operating system, indicating that the program executed successfully.

To run this program, you need a C++ compiler installed on your system. Save the code in a file with a .cpp extension (e.g., hello.cpp). Then, open a terminal or command prompt and navigate to the directory containing your file. Use the following commands to compile and run the program:

g++ hello.cpp -o hello
./hello

This assumes you have the GNU Compiler Collection (g++) installed. Adjust the commands accordingly if you’re using a different compiler. After running the program, you should see “Hello, World!” printed to the console.

Leave a Comment