Creating a C++ Hello World Program

Beginner

Introduction

In this lab, we will learn how to create a basic Hello World program in C++ programming language. This will include working with the input and output streams, understanding the basic structure of a C++ program, and learning how to write and execute code.

Create a file and name it main.cpp

We will be creating our hello world program in a file named main.cpp. Open the terminal and navigate to the project directory using the command:

cd ~/project

Now create a new file named main.cpp using the following command:

touch main.cpp

Add the basic program structure

Every C++ program consists of at least one function: main(). The main() function is the starting point for the program. In the main() function, we'll be using the cout statement to print the "Hello World!" message on the screen.

Add the following code to main.cpp:

#include<iostream>
using namespace std;

int main()
{
    cout << "Hello World!\n";
    return 0;
}

The #include <iostream> statement includes the iostream library to use the cout statement for printing the message to the terminal screen.

The using namespace std; statement allows us to use the standard namespace without having to type std:: every time.

Compile and run the code

To compile and execute the program, we can use g++ to compile our code.

Enter the following command in the terminal to compile the code:

g++ main.cpp -o main

This will create an executable file named main in the same directory.

Now, to run the program, we can enter the following command:

./main

This will execute the program and output the "Hello World!" message on the terminal screen.

Review the program's output

After we run the program, we should see the following message printed on the screen:

Hello World!

This message indicates that our program is working correctly and able to print a message to the terminal screen.

Modify the message

Now, let's modify the message that our program prints. We'll change the message to "Welcome to C++ Programming!".

#include<iostream>
using namespace std;

int main()
{
    cout << "Welcome to C++ Programming!\n";
    return 0;
}

Compile and run the code

Compile and run the code using the commands we previously used:

g++ main.cpp -o main
./main

Review the program's output to verify that the message has been updated:

Welcome to C++ Programming!

Summary

Congratulations! You have successfully created and executed a "Hello World!" program in C++. We have covered the basic structure of a C++ program, using the input and output streams, and modifying the message that our program prints.

Other Tutorials you may like