Loading

Writing your First Program in the C++ Programming Language

5/3/2019
Take your first steps into C++

A C++ program starts in the main function. That is where execution begins:

int main() {

}

In the construct above, the name of the function is main. The return type of the function is int, an integer. There are no parameters for the function, so there's nothing in between the parentheses. The body of the function is enclosed with curly braces. That is where we are going to write our code next.

We can write characters to standard output (i.e. the console) using the coutobject. In order for us to use that object, we need to import a library called iostream. Let's see the code:

#include <iostream>

int main() {
    std::cout << "Hello World";    
}

Now, there are more things that we haven't covered.

To include the external code that is already written for you, we use the #includestatement. In this situation, the standard library file name is within < >.

A sequence of characters in C++ is called a string. Strings appear under double quotes. In our example, we have the string "Hello World". Note the quotes will not appear in the program output, only its contents.

The cout object is part of the std namespace, so we have to prefix it with std::.

The << is an overloaded operator that is actually a function call to direct the string text on its right-hand side to the output on the left-hand side. Think of it as the sequence of characters that is to be directed to be displayed in the standard output. Note the direction of the << operator arrow matters.

Before we can display the output of the program, we should add a line break after the hello message. Otherwise if you run the program in a terminal your command prompt will come up after the hello message instead of in a new line. We can use std::endlto add a new line break:

std::cout << "Hello World" << std::endl;    

The function mainhas a return type of int, an integer number. Even though our program is pretty simple and omitting the return value might still work, it is best we follow the principles and place the return statement at the end of the function:

#include <iostream>

int main() {
    std::cout << "Hello World" << std::endl;
    return 0;
}

The reason the return value is zero is because we expect the program to finish execution without any errors. Should the program have encountered any sort of error, the tradition is to use an error code that can be used to identify what kind of problem occurred. So if an integer other than 0 was returned in the program, it would have meant there was an error.

Now, bringing it all together, if you compile and run the program, you will get the following output:

Hello World

You can try running the program on Repl.it here.

To learn more about software development, visit NBK Tech World:

https://www.youtube.com/channel/UC3pR7vTMNPNmSk99YIBKUnw

See you there!

Did you like the lesson? 😆👍
Consider a donation to support our work: