Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

Modern C++ Programming
Modern C++ Programming
Modern C++ Programming
Ebook884 pages4 hours

Modern C++ Programming

Rating: 0 out of 5 stars

()

Read preview

About this ebook

This book covers Modern C++ programming. The book is written in a neatly manner including the recent developments published in recent standards, C++11, C++17, C++20 and C++23. The book can be divided into two parts. The first part contains the classical programming units such as data types, loops, conditional statements, pointers etc. The second part of the book focuses on object oriented programming. Besides, concurrency in C++ programming is also explained in the book. The book includes the lately introduced subjects in C++ such as smart pointers, atomic data types, mutex race prevention and many other minor subjects. While writing the object oriented part of the book, attention is paid to the simplicity and we focused on the aim of the subject rather than providing programming units which include many code lines. While writing the book, the author used his many years of teaching experience, and tried to avoid long variable names and clumsy coding and paid attention to the learnability of the material with the smallest effort.

LanguageEnglish
PublisherOrhan Gazi
Release dateMar 2, 2024
ISBN9798224760732
Modern C++ Programming

Read more from Orhan Gazi

Related to Modern C++ Programming

Related ebooks

Software Development & Engineering For You

View More

Related articles

Reviews for Modern C++ Programming

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Modern C++ Programming - Orhan Gazi

    Preface

    C++ programming language was developed in 1980. In time, the language have been improved with the introduction of standards, C++11, C++14, C++17, C++20, and C++23, and the current C++ language is much more improved considering its versions before the year of 2010, and a new name Modern C++ is adopted in literature for the current C++. Although new features are added to the C++ language by the introduction of new standards, the skeleton of the language stays the same.

    In this book, we explain modern C++ programming language. In chapters 1-7, we explain basic programming concepts which are data types, conditional statements, loops, functions, arrays and type conversion. In chapter-6, we included lambda functions which are introduced in modern C++ programming. Besides, automatic data definition which is covered in chapter-2 is also a topic of modern C++ language. It should be never forgotten that in digital devices 2's complement representation is used for signed number. For this reason, we covered fundamentals concepts like binary, hexadecimal numbers and number representation in chapter-1. It is critical to have good knowledge of binary number representations when studying the pointers which are covered in chapter-9. For this reason, we strongly advise the reader to study the chapter-1 before processing with the other chapters.

    C programming language is usually considered for embedded software engineering; on the other hand, due to the object oriented ability of the C++ language its application scope is vaster considering the C language. Both C and C++ languages are the most adopted programming languages. According to the TIOBE index, C and C++ languages have always been in the top three places for the last 40 years, among 100 programming languages considering the reference year 2024.As every technology, programming languages improve in time. There is an increasing competition among programming languages over the last few decades. Although python language showed a tremendous incline in the recent years, C and C++ languages are still in the top three popularity places.  Due to the tough computation among programming languages, C++ had to update itself with a number of recent published standards. In these standards, either new features are introduced or some weak parts of the C++ language are improved. For instance, with the introduction of smarts pointers in C++11 standard, automatic de-allocation is enabled for dynamically allocated memory spaces, and memory leakage problem is alleviated.

    The object oriented programming using C++ is covered in chapters 13, 14, 15 and 17. Object oriented programming is not a simple subject for new beginners. For this reason, while explaining the subjects, classes, inheritance, operator overloading, and templates, we paid attention to be as simple as possible and we focused on the main concepts avoiding complex programming notation. We avoided using long variable and object names, and we tried to keep the programming lines in its minimum number. From our years of experience, we realized that providing complicated or long expressions even for variable names tires the human brain and brakes the learning speed, for this reason we just aimed to give the target information and avoided long lines and class or object names.

    Complex numbers are very widely used for electrical and computer engineers. In chapter-8, we explain how to use the complex numbers in C++ programming. Chapter-16 covers parallel programming, or concurrency in C++ programming.  The speed of a computer is determined by the clock frequency of its processor, and the frequency of a clock source cannot go beyond a certain limit, since, at very huge frequencies electrons are converted to photons and electronic devices burn. To decrease the computation time of high complex operations parallel processing can be employed and for this purpose electronic devices can contain multiple processors and each processor deal with a specific part of the computation. In C++ programming, we use threads for parallel processing operations, and to prevent race condition which arises when multiple threads try to access a shared resource, we use either mutex functions or atomic variables. These concepts are explained in details in Chapter-16.

    This is the first edition of the book, and the book will be updated and new examples will be added whenever it is needed. Lastly, for new programmers, we want to give a piece of advice, there is no difficult subject in science and engineering; something is difficult if it is not divided into sufficient number of pieces. If you follow the divide and conquer policy in your learning, your learning speed will be faster and your learning quality will be better.

    I dedicate this book to my lovely sister Seviye Gür, and to those people who like to teach something to the people.

    Prof. Dr. Orhan Gazi

    Electrical and Electronics Engineering Department

    Ankara Medipol University

    Saturday, February 17, 2024

    Chapter-1

    Representation of Numbers and Characters in Computer

    Abstract: This chapter covers the computer representation of numbers and characters. Computer uses binary number system. Everything is represented by binary numbers in computer. Information is expressed using symbols which include characters, numbers and symbols other than characters. Every symbol and number is represented by 7-bit ASCII codes. ASCII representation of positive numbers is the same as their binary representation. However, negative numbers are represented in 2's complement form in most of the electronic devices including computers.

    1.1 Number Bases

    Number base is a positive integer, and a number with base N can contain digits less than N.

    1.1.1 Decimal Numbers

    If base equals to 10, then all the digits forming a number should be less than or equal to 9. The numbers under base 10 are called decimal numbers.

    Example-1.1: We can write a few decimal numbers as

    In fact, in our daily life we use decimal numbers

    1.1.2 Binary Numbers

    If the base equals 2, then the numbers are called binary numbers and binary numbers can be formed using the digits 0 and 1.

    Example-1.2: We can write a few binary numbers as

    1.1.3 Octal Numbers

    If the base equals 8, then the numbers formed under this base are called octal numbers and an octal number can be formed using the digits

    Example-1.3: We can write a few octal numbers as

    1.1.4 Hexadecimal Numbers

    If the base equals16, then the numbers formed under this base are called hexadecimal numbers and a hexadecimal number can be formed using the digits

    where the letters and denote the numbers

    Example-1.4: We can write a few octal numbers as

    We can use or 0X prefix in front of the hexadecimal numbers. The hexadecimal number in the previous example can be written either as

    or as

    but usually small x, i.e., , is preferred.

    1.2 Conversion between Bases

    Assume that we have a number under a base. The equivalent of this number in another base can be calculated. This procedure is called conversion between bases.

    1.2.1 Binary to Decimal Conversion

    The n-bit binary number

    can be converted to decimal as

    Example-1.5: The decimal equivalent of

    can be calculated as

    which is equal to

    1.2.2 Binary to Octal Conversion

    To convert a binary number to octal, starting from the right most position we first divide the binary string into groups having 3 bits, and then convert each 3 bits to an octal number.

    Example-1.6: Convert the binary number

    to a number in octal base.

    Solution-1.6: Starting from the right most position we first divide the binary string into groups having 3 bits as

    where the left most bit can be left padded by zeros to make a group of three bits as

    and we convert each group to an octal number as in

    Thus, the equivalent octal number is

    1.2.3 Binary to Hexadecimal Conversion

    To convert a binary number to octal, starting from the right most position we first divide the binary string into groups having 4 bits, and then convert each 4 bits to a hexadecimal number.

    Example-1.7: Convert the binary number

    to a number in hexadecimal base.

    Solution-1.7: Starting from the right most position we first divide the binary string into groups having 3 bits as

    where the left most bit can be left padded by zeros to make a group of three bits as

    and we convert each group to an octal number as in

    Thus, the equivalent hexadecimal number is

    1.2.4 Decimal to Binary Conversion

    A decimal number can be converted to a binary number using successive division operation. In this method, the decimal number is divided by 2 and the remainder is recorded, the dividend is again divided by 2 and the remainder is recorded. This procedure is repeated with dividends until no more division operation can be achieved.

    Example-1.8: Convert the decimal number to binary.

    Solution-1.8: We divide 351 by 2 and remainder equals 1 and dividend equal 350.  We indicate this division operation as on the right hand side of Figure-1.1.

    Figure-1.1 Decimal to binary conversion for Example-1.8.

    If we continue division operation in a successive manner we obtain Figure-1.2.

    Figure-1.2 Successive division for Example-1.8.

    Finally, we collect the binary numbers from bottom to top as depicted in Figure-1.3, and obtain

    Figure-1.3 Bits are collected from bottom to top.

    Exercise: Find the decimal equivalent of the binary number

    1.2.5 Octal to Binary Conversion

    To convert an octal number to binary, we first convert each octal digit to a binary string having three bits, then concatenate all the bits and obtain the binary equivalent of the octal number.

    Example-1.9: Convert the octal number to binary.

    Solution-1.9: We first express each octal digit by three bits as shown in

    then we concatenate the bits and obtain the binary equivalent number as

    where removing spaces we get

    1.2.6 Hexadecimal to Binary Conversion

    To convert a hexadecimal number to binary, we first convert each hexadecimal digit to a binary string having four bits, then concatenate all the bits and obtain the binary equivalent of the hexadecimal number.

    Example-1.10: Convert the hexadecimal number 1AF39502 to binary.

    Solution-1.10: We first express each octal digit by three bits as shown in

    then we concatenate the bits and obtain the binary equivalent number as

    where removing spaces we get

    1.2.7 Hexadecimal to Decimal Conversion

    The n-digit hexadecimal number

    is converted to decimal as

    Example-1.11: The decimal equivalent of

    can be calculated as

    which is equal to

    Example-1.12: The decimal equivalent of

    can be calculated as

    which is equal to

    1.3 Positive Integers

    Positive integers are also called unsigned integers, and in computer positive integers are represented by their binary equivalents.

    Example-1.13: The hexadecimal number equals to the decimal number which is represented in computer by

    1.4 Two's Complement Form

    To find the 2's complement of a binary string, i.e., binary number, we start from the right most position and proceed to the left until we meet the first 1, and after meeting the first one, we go on proceeding to the left but we flip each bit to its complement form, i.e., 1 is converted to 0, and 0 is converted to 1.

    Example-1.14: Find the 2's complement of

    Solution-1.14: We start from the left-most bit and proceed to the left until we meet the first 1 as shown in Figure-1.4.

    Figure-1.4 Location of the first '1'.

    Next, we go on proceeding to the left, and take the complement of each bit as shown in Figure -1.5.

    Figure-1.5 Take the complement of each bit after first '1'.

    and the 2's complement form is obtained as

    where removing the spaces we obtain

    Example-1.15: Find the 2's complement of

    Solution-1.15: We start from the left-most bit and proceed to the left until we meet the first 1, however, for this string the first 1 is at the first position as shown in Figure-1.6.

    Figure-1.6 Location of first '1'.

    Next, we go on proceeding to the left, and take the complement of each bit as shown in Figure-1.7.

    Figure-1.7 Complemented ones.

    and the 2's complement form is obtained as

    0 0 0 0 0 0 0 1

    where removing the spaces we obtain

    Example-1.16: 2's complement of

    is

    What is the 2's complement of

    Solution-1.16: 2's complement of

    is

    Hence, we can write that

    If d is the 2's complement of a, i.e., d = 2's comp(a)

    then 2's complement of d is a, i.e., a = 2's comp(d)

    1.5 Negative Integers

    Assume that a is a positive integer, in computer the positive integer a is represented by a binary string which is obtained by converting a into binary. That is

    a is represented by d which is obtained by converting a into binary

    Negative integers in digital devices are represented in 2's complement form.

    That is

    if a is represented by d, then –a is represented by 2's complement of d

    Example-1.17: How are the numbers 17 and -17 are represented in computer? Use 8 bits for the representation.

    Solution-1.17: Using 8 bits, we can write the binary equivalent of 17 as

    Then, in computer the string

    represents the number 17.

    If the string   represents 17, then -17 is represented by

    2's complement of 

    which is

    Thus, in computer

    the string   represents 17

    and

    the string   represents -17

    In 2's complement form the most significant bit is always 1.

    Example-1.18: The string represents a negative integer in computer. What is the decimal equivalent of the number?

    Solution-1.18: Negative integers are represented by 2's complement of the binary representation of the it's opposite sign integer, i.e., positive integer. We know that

    If d=2's complement of a, then a = 2's complement of d

    To find the value of negative integer, we first take the 2's complement of the binary string which represents the negative integer, then convert the result to decimal and put a negative sign in front of it, accordingly, 2's complement of

    is

    and the decimal equivalent of this string is 1, then we can say that the string

    represents -1.

    Example-1.19: The string represents a negative integer in computer. What is the decimal equivalent of the number?

    Solution-1.19: Decimal equivalent of the negative integer can be calculated as

    Thus, the string is used to represent .

    1.6 Registers

    Registers are memory building blocks of memory units. A register is capable of holding a number of bits. A register is usually called number of cells it contains. Each cell can hold only 1-bit information.

    Example-1.20: 8-bit register contains 8 cells and can hold 8-bit of information.

    1.7 Memory Units

    A memory is composed of a number of registers, and each register has an address. Address values of the registers are kept in another set of registers. Register addresses are usually expressed using hexadecimal numbers. In Figure-1.8, a memory unit is depicted.

    Figure-1.8 A typical memory unit with 16-bit register addresses.

    1.8 How are the Integers Stored in Computer Memory, Big-Endian and Little-Endian?

    Numbers are stored in registers. Each register has an address. There are 2 types of data storage; these are little-endian and big-endian methods. In the little-endian method the least significant byte is written to the memory first, whereas, the big-endian method, the most significant byte is written to the memory first. In Figure-1.9, little-endian and big-endian methods are explained.

    Figure-1.9 Little-endian and big-endian memory storage.

    In this book, we will use little-endian method in our examples.

    Assume that 8-bit registers are used for storing number.  The most significant byte of the integer is stored the highest address and the others are stored consecutive lower addresses. Note that a 32-bit integer variable is stored into 4 consecutive registers.

    A typical resister is illustrated in Figure 1-10.

    Figure-1.10 A typical register.

    Problems

    1) Convert the following decimal numbers to binary

    2) Convert the following binary number to decimal, octal, hexadecimal

    3) Convert the hexadecimal number to decimal.

    4) Find the representation of the following positive numbers in computer, use 16-bit for representation:

    5) Find the representation of the following negative numbers in computer, use 16-bit for representation:

    6) The following strings represent some negative integers in computer; find the decimal equivalents of these integers

    7) How is the hexadecimal number stored in memory according to little-endian and big-endian conventions?

    Chapter-2

    Data Types and Operators

    Abstract: In this chapter we first will explain primary data types used in C++ programming and then explain the use of arithmetic, logical and shift operators for these data types. The primary data types of C++ language are char, int, float, double and their unsigned counterparts. To comprehend the subjects explained in this chapter very well, the reader should have a good knowledge of representation of numbers in computer-like systems. For this reason, we advise the reader to study the topics explained in chapter-1 before proceeding with this chapter.

    2.1 How to Start Writing a C++ Program?

    To write a C++ program, we should first form the main function of the program. For this purpose, we first write the word 'int' as in Code-2. 1.

    Code 2.1

    int

    Then, next to 'int' we write 'main(void)' as in Code-2.2.

    Code 2.2

    int main(void)

    We add curly brackets as in Code-2.3.

    Code 2.3

    int main(void) {

    }

    The statement 'return 0;' is written before the closing curly bracket. Note that there is a semicolon after 'return 0'.

    ––––––––

    Code 2.4   

    int main(void) {

    return 0;

    }

    Semicolon can also be written after '}', but is it not required.

    Code 2.5

    int main(void) {

    return 0;

    };

    The C++ program lines called statements are written in main function of the program and we get the template of the main function as in Code-2.6.

    Code 2.6

    int main(void) {

    // statements

    return 0;

    }

    A return value of 0 indicates the successful completion of program, while any other value indicates an error.

    The template can be simplified. The word 'void' in 'main' can be omitted as in Code-2.7.

    Code 2.7

    int main() {

    // statements

    return 0;

    }

    We can also omit return 0; statement as in Code-2.8.

    Code 2.8

    int main() {

    // statements 

    }

    Even, we can omit 'int' word before main, and we get Code-2.9.

    Code 2.9

    main() {

    // statements 

    }

    In this case, compiler issues warning, but it does not have any operational effect.

    We can start the curly parenthesis after main as in Code-2.10.

    Code 2.10

    main()

    {

    // statements 

    }

    In this case, compiler issues warning, but it does not have any operational effect.

    2.2 Comments in C++ Programming

    Single line comments can be written using after // as in Code-2.11.

    Code 2.11

    int main() {

    // Single line comment

    }

    Multi line comments can be written using between the characters /* and */ as in Code-2.12.

    Code 2.12

    int main() {

    /* This is a multiple line

    comment in C++  */

    // This is single line comment in C++

    }

    2.3 The first C++ Program

    C++ programs usually use built-in library functions, and these functions are included using header directives as in Code-2.13.

    Code 2.13

    #include

    using namespace std

    int main() {

    // statements

    }

    In this program is the name of the header file, the brackets < > indicate the library directory where header file exists, and the sign # is used to write the directives.

    Our first C++ program is shown in Code-2.14.

    Code 2.14

    #include

    using namespace std;

    int main() {

    cout << Hello World!;

    };

    where cout object is used to display the string on console. The output of the program is Hello World.

    Example-2.1: The cout is used twice in Code-2.15.

    Code 2.15

    #include

    using namespace std;

    int main() {

    cout << Hello World!;

    cout << How are You.;

    };

    Output(s): Hello World.How are You.

    Example-2.2: To print the next sentence to a new line, we can use new line character \n or endl manipulator as in Code-2.16.

    Code 2.16

    #include

    using namespace std;

    int main() {

    cout << Hello World! << endl;

    cout << How are You.;

    };

    Output(s):

    Hello World.

    How are You.

    The new line character \n can be used at any place inside a sentence as in Code-2.17.

    Code 2.17

    #include

    using namespace std;

    int main() {

    cout << Hello \n World.\n;

    cout << How \n are You.;

    };

    Output(s):

    Hello

    World.

    How

    are You

    2.4 Variable and Data Types

    A variable as its name implies can take a variety of values. But these values belong to a single data type. For instance if is an integer than can have many different integer values, but it cannot have a fractional value.

    A variable is declared as

    ––––––––

    dataType variable_name;

    Primary data types are:

    char  8 bit signed numbers usually used to represent characters,

    int  32 bit singed integers used to represent integers,

    float  32 bit signed numbers used to represent single precision fractional real numbers,

    double 32 bit signed numbers used to represent double precision fractional real numbers.

    auto  this specifier is used for automatic type detection

    The variables belonging to the same data type can be defined on the same line

    dataType variable_name1, variable_name2;

    Different data types should be separated by semicolon as in Code-2.18.

    Code 2.18

    #include

    using namespace std;

    int main() {

    char ch1 ='A', ch2;

    int num1, num2 = 14;  double num3, num4 = 6.8;

    auto num5 = 8.7;

    }

    To print the values of variable to the screen we use cout object which is used as

    cout << variable_name;

    To print more than one variable value to the screen, we use the format

    cout << variable_name1 << variable_name2;

    Example-2.3: We define four variables using both specific and auto type qualifiers, and we print the values using cout object in Code-2.19.

    ––––––––

    Code 2.19

    #include

    using namespace std;

    int main() {

    char ch1 = 'A';

    auto ch2 = 'B';

    int num1  = 25;

    auto num2 = 45;

    cout << ch1 = << ch1 << endl;

    cout << ch2 = << ch2 << endl;

    cout << num1 = << num1 << endl;

    cout << num2 = << num2 << endl;

    }

    The code can be written using a single cout as in Code-2.20.

    Code 2.20

    #include

    using namespace std;

    int main() {

    char ch1 = 'A';

    int num1  = 25;

    auto num2 = 45;

    auto ch2 = 'B';

    cout << ch1 = << ch1 << endl << ch2 = << ch2 << endl;

    cout << num1 = << num1 << endl << num2 = << num2 << endl;

    }

    Output(s):

    ch1 = A

    ch2 = B

    num1 = 25

    num2 = 45

    The 8-bit data type char can take integer values between -128 and +127.

    Example-2.4: The tilde symbol ~ has the ASCII value 126. Tilde symbol and its ASCII value can be printed as in Code-2.21.

    Code 2.21

    #include

    using namespace std;

    int main() {

    char ch = 'A';

    int num = 25;

    cout << Letter is << ch << endl;

    cout << Number is << num;

    };

    Output(s):

    Letter representation is ~

    Number value is 126

    2.5 Binary number representation in Modern C

    Binary numbers can be expressed using 0b or 0B prefix.

    Example-2.5: The previous code can also be written using binary number representation as in Code-2.26.

    Code 2.22

    #include

    using namespace std;

    int main() {

    char ch

    Enjoying the preview?
    Page 1 of 1