Book Image

C++ Fundamentals

By : Antonio Mallia, Francesco Zoffoli
Book Image

C++ Fundamentals

By: Antonio Mallia, Francesco Zoffoli

Overview of this book

C++ Fundamentals begins by introducing you to the C++ compilation model and syntax. You will then study data types, variable declaration, scope, and control flow statements. With the help of this book, you'll be able to compile fully working C++ code and understand how variables, references, and pointers can be used to manipulate the state of the program. Next, you will explore functions and classes — the features that C++ offers to organize a program — and use them to solve more complex problems. You will also understand common pitfalls and modern best practices, especially the ones that diverge from the C++98 guidelines. As you advance through the chapters, you'll study the advantages of generic programming and write your own templates to make generic algorithms that work with any type. This C++ book will guide you in fully exploiting standard containers and algorithms, understanding how to pick the appropriate one for each problem. By the end of this book, you will not only be able to write efficient code but also be equipped to improve the readability, performance, and maintainability of your programs.
Table of Contents (9 chapters)
C++ Fundamentals

The try-catch block

During the execution of a program, an anomaly may occur. We refer to these runtime problems as exceptions, and they represent the response to an exceptional circumstance that arises outside of the normal functioning of a program. Designing code that's resilient to errors is one of the hardest things a programmer has to deal with.

Exceptions are generally thrown using the throw keyword when something that cannot be handled is encountered by the program. This is also referred to as raising an exception.

The try keyword is followed by a block containing statements that might throw one or more exceptions. These exceptions can be caught by one or more catch clauses, which are sequentially listed after the try block. The syntax for this is as follows:

try {
} catch (exception-declaration1) { 
} catch (exception-declaration2) { 

A catch block consists of the catch keyword, the exception declaration, and a block. Based on the exception thrown inside the try block, one catch clause is selected and the corresponding block is executed. Once the catch block has terminated, the program continues its execution with the statement following the last catch clause.

Let's examine the following example to understand how try-catch conditional statements handle exceptions:

#include <iostream> 
int main() 
  int x = 10; 
  try { 
    std::cout << "Inside try block" << std::endl;
    if (x > 0) // True
      throw x;// Following statement will be skipped
      std::cout << "After throw keyword" << std::endl;
  catch (int x ) { 
    std::cout << "Inside catch block: Exception found" << std::endl;
  std::cout << "Outside try-catch block" << std::endl; 
Inside try block
Inside catch block: Exception found
Outside try-catch block

Exercise 2: Counting the Number of Times a Specific Number Appears in a Given List

In this exercise, we will discuss using the if statement and a for loop to count our magic number. Here, we will be trying to find all numbers that are divisible by 3, ranging from 1 to 30.


To find out if a number is divisible by another, use the modulo (%) operator.

Now, let's perform the following steps:

  1. Import all the required header files:

    #include <iostream>
  2. We need to store the number of times a number is divisible by 3 in a counter. For this reason, we define and initialize the count variable to 0:

    unsigned count = 0;
  3. Now, we will use a for loop that produces values from 1 to 30 so that we can check whether they are divisible by 3 or not:

    for(unsigned x = 1; x <= 30; x++){
  4. Finally, we will check in the body of the for loop by using an if statement and the expression x%3 == 0, which evaluates to true if the division has a remainder equal to 0:

    if (x%3 == 0) {
  5. If the previous condition returns to true, then the X variable is divisible by 3 and we can increment the counter.

  6. Finally, we can print count:

    std::cout << count << std::endl;

Bonus exercises:

  • Find how many numbers are divisible by 11 within the range of 1 to 100

  • Print all the numbers that are not divisible by 3 within the range of 1 to 30

Activity 1: Finding the Factors of 7 between 1 and 100 Using a while Loop

In the following activity, we will use a while loop and implement the previous concept from the earlier exercise to print the numbers between 1 and 100 that are divisible by 7.

Now, let's rewrite the previous code using a while loop in the following way:

  1. Create a variable of the unsigned type.

  2. Now, write the logic to print the numbers that are divisible by 7 using the while loop.

  3. Then, we have to increase the value of i after each iteration. Use the following code:



The solution for this activity can be found on page 282.