2/100 Days of C++: Compile Your First C++ “Hello World” Program

In this journey of 100 Days of C++, the aim is not only to understand the basic and intermediate concepts of C++ programming but also to solve practical exercises to develop programming skills. Are you interested in joining the path? Then follow me on Instagram to stay updated on the topics and also get some tips and tricks on programming.

Welcome to Day 2 of our “100 Days of C++” series! In the previous post of this series, we understood compilers, linkers, and what it means to build a package. In this post, we implement those concepts in a C++ tutorial on “Hello World”. This means that we will compile a program, and create an object file that can be executed. Now, a “Hello World” program is the most basic level in any programming language and fails to provide much information except for the print function. Thus, we will consider a second example in which we will build a calculator.

By the end of this tutorial, you will have a solid grasp of compiling a C++ program and understand key components like headers, the main function, and more. We’ll start with the classic “Hello, World!” example and then move on to a slightly more complex program. So let’s get started!

Choosing an IDE

Before we proceed with writing and compiling your first C++ program, it’s important to choose a suitable Integrated Development Environment (IDE) for your development needs. An IDE can significantly enhance your programming experience by providing features like syntax highlighting, code completion, debugging tools, and more. Some of the popular names are Microsoft Visual Studio Code, Code::Blocks, PyCharm, etc. All of them are free to download and use.

I prefer VS Code as it is highly customizable, and plenty of plugins are available that make programming efficient and convenient. Moreover, it is easy to set up for a variety of languages like C, C++, and Python, with simple plugin configurations. To set up VS Code for C++, follow this official documentation from Microsoft that provides a step-by-step guide to configure the IDE. Now that we have the IDE ready, let us get our hands dirty.

Compiling the Hello World program

Let’s start with the traditional program in any programming language: “Hello, World!”.

#include <iostream>

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

Breaking down the code:

  • #include <iostream>: This line includes the input-output stream library, which is necessary for using std::cout.
  • int main() { ... }: This defines the main function where the execution of the program begins.
  • std::cout << "Hello World!" << std::endl;: This prints “Hello, World!” to the console. std::cout is used for output, and std::endl adds a new line.
  • return 0;: This ends the main function and returns 0, indicating that the program finished successfully.

Compiling the Code

To compile the above code, save it as “main.cpp” (or any other name you prefer). Next, open the terminal and navigate to your project folder. You can use the terminal available in VS Code or the default one available on your OS (hopefully Linux!). Recalling from the previous post on compilers and linkers, we compile our C++ program using the following code:

g++ main.cpp -o main

This will create an executable file in the project folder itself with the name “main”. Execute this file as follows:

./main

[In case you face a permission error, allow permissions to execute the file using the code sudo chmod +x main. ]

After executing, you should see the statement “Hello World!” printed in the terminal.

So what happened in the background? How did the processor, compiler, and linker work in this small program? Let us understand this process.

  • Preprocessing: The preprocessor handles the directives that start with #, such as #include. It includes the contents of the specified file into the program.
  • Compilation: The compiler converts the preprocessed code into assembly language.
  • Assembly: The assembler converts the assembly code into machine code, resulting in an object file.
  • Linking: The linker combines object files into an executable, resolving references between them.

This pipeline resulted in that executable that we were able to execute and gave us our desired output. Fun, isn’t it? Feel free to pause here and go through the above process again if needed. If you gained even a bit of confidence in C++ now, let us try something more fun and interesting.

hello world

Building a Simple Calculator using C++

#include <iostream>

int main() {
    double num1, num2;
    char operation;

    std::cout << "Enter first number: ";
    std::cin >> num1;

    std::cout << "Enter an operator (+, -, *, /): ";
    std::cin >> operation;

    std::cout << "Enter second number: ";
    std::cin >> num2;

    double result;

    switch (operation) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            if (num2 != 0) {
                result = num1 / num2;
            } else {
                std::cerr << "Error: Division by zero!" << std::endl;
                return 1;
            }
            break;
        default:
            std::cerr << "Error: Invalid operator!" << std::endl;
            return 1;
    }

    std::cout << "Result: " << result << std::endl;
    return 0;
}

The basic functions like the int main(), include, std::cout and return are already clear from the above tutorial. Yet this seems a bit more overwhelming than the previous “Hello World” tutorial, doesn’t it? Don’t worry, let us break this code down and understand it step by step:

  • Data Types: Similar to that in other programming languages, one can use several data types in C++, namely, the double, char, int, string and float (of course, there are more such as 8-bit integer, 16-bit integer, signed, unsigned, etc. but that is a topic for some other day. For now, we will keep things simple 😉 ). In this tutorial, we use the double to store the numbers input by the user and char for the corresponding operation that is to be carried out between those numbers.
  • Talking about input from the user, std::cin >> num1 and std::cin >> num2 take the first and second numbers as input and store the values in the corresponding variables. Similarly, std::cin >> operation takes in the desired operator as input.
  • Switch Statement: The switch statement in C++ is a crucial concept, and it is used widely in applications. switch (operation) { ... } determines the operation to perform based on the input operator. Within the statement, there are multiple cases, one of which is carried out depending on the input operation.
    case '+': result = num1 + num2; break;: Adds the numbers if the operator is ‘+’.
    case '-': result = num1 - num2; break;: Subtracts the numbers if the operator is ‘-‘.
    case '*': result = num1 * num2; break;: Multiplies the numbers if the operator is ‘*’.
    case '/': ...: Divides the numbers if the operator is ‘/’, with a check for division by zero.
  • Error Handling: In case of an error such as division by 0, which is impossible, the compiler will throw an error. This error statement can be handled more elegantly by printing a sophisticated statement. Below are two of such examples:
    std::cerr << "Error: Division by zero!" << std::endl;: Prints an error message if division by zero is attempted.
    std::cerr << "Error: Invalid operator!" << std::endl;: Prints an error message if an invalid operator is entered.

After understanding the code, we now proceed to compile it and link the necessary dependencies. Do not look at the code directly. Take a moment to remember how to compile the code to yield an executable.

Assuming that you named the program “calculator.cpp”, here is how to compile it and run:

g++ calculator.cpp -o calculator
./calculator

Summary

In this tutorial, we have covered how to compile your first C++ program and developed a simple calculator example. We discussed the basic structure of a C++ program, including headers, the main function, input, and output. We also understood the control structure, for instance, the switch statement.

Until now, you should feel comfortable writing, compiling, and running basic C++ programs. Feel free to modify the above examples and create your version to practice and improve skills in C++. Below are some of the suggestions:

  • Take the user name as input and print a statement to greet the user. For example, “Hello Chandler” or, “How you doin’, Joey!”
  • Create a program that determines if the input number is even or odd. (Hint: Make use of the % operator and if...else statement).
  • Create a program that returns the day based on the number input by the user. For instance, if the input is 1, the program returns Monday, if 2, then Tuesday, and so on. (Hint: Make use of switch statements).

Feel free to reach out on Instagram in case of any issues or errors. Also, do post your solutions on Instagram and tag me in the post @machinelearningsite. Happy coding 🙂

As we continue our 100-day journey, we will delve deeper into C++ features and best practices. Stay tuned for the next tutorial, where we will understand comments, variables, and objects in C++. You don’t want to miss out on the posts, do you? Then follow me on Instagram where I not only share updates on my latest blog updates, but also tips, tricks, and memes on programming and machine learning. Moreover, every follow provides me the motivation that helps me to continue to create such interesting and helpful content.

If you made it this far, why don’t you subscribe to my *FREE* newsletter? You’ll be updated with the latest blog posts, in case you miss them out. Don’t worry, this reminder is once a month, so no spam 🙂