Language: EN

cpp-primer-programa

Our First Program in C++

Now that we have our working environment set up, whether it’s Visual Studio, Visual Studio Code + GCC (or another you may have chosen), it’s time to see our first program.

This first program will be a console application that simply displays “Hello World” on the screen. It’s simple, but it serves to check that everything is correct and as a starting point.

The “Hello, World!” program is a classic in programming, used in many languages as the first application.

So, assuming you already have your favorite IDE installed and properly configured, let’s take a look at our first code 👇.

Creating a new C++ project

We start by creating a new folder for our project, for example HelloWorld, and inside it a text file named main.cpp.

You could choose any other name

Write the following code in the main.cpp file:

// Include the standard library for input and output
#include <iostream>

// Main function where the execution of the program begins
int main() { 
	// Print the message to the console
    std::cout << "Hello World from LuisLlamas.es!" << std::endl;

	 // Indicate that the program finished correctly
    return 0;
}

Now, run this code by pressing F5 (it’s the same key in both Visual Studio and Visual Studio Code) and we will see what it displays on the screen.

Hello World from LuisLlamas.es!

What’s happening here? When you run this program, the compiler translates the source code you have written into a language that the computer can understand.

  1. The flow of execution begins in the main() function
  2. When it reaches the line containing std::cout, the program displays the message “Hello, World!” to the console.
  3. The execution ends with return 0;, indicating that everything went well.

Let’s dive deeper.

Explanation of the code

Let’s take a closer look at each part.

Expanding the program

The program we have made is very simple. Let’s look at some modifications you can make to practice.

Modify the message

You can change the message that is printed to the console. Simply modify the text between the quotes.

std::cout << "Welcome to programming in C++" << std::endl;

More output lines

You can add more output lines with multiple std::cout statements.

std::cout << "Hello, World!" << std::endl;
std::cout << "This is my first program in C++." << std::endl;
std::cout << "I'm learning to program!" << std::endl;

Use variables

As you progress, you will learn to use variables in C++. Here’s a simple example with a string type variable.

#include <iostream>
#include <string>

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

In this case, we introduced a variable called greeting that contains the message, and then we printed it to the console.