How to write your first C++ program?


0

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.


Like it? Share with your friends!

0

What's Your Reaction?

hate hate
0
hate
confused confused
0
confused
fail fail
0
fail
fun fun
0
fun
geeky geeky
0
geeky
love love
0
love
lol lol
0
lol
omg omg
0
omg
win win
0
win
Anand Narayanaswamy
Anand Narayanaswamy is the editor-in-chief of Learnxpress. He was a Microsoft Most Valuable Professional (MVP) for a period of 9 years. He is a ASPInsider based in Trivandrum, Kerala State, India. Anand is the author of Community Server Quickly published by Packt Publishing.

0 Comments

Your email address will not be published. Required fields are marked *