• Unit 10:INTRODUCTION TO C++ PROGRAMMING

    Key Unit Competency
    By the end of the unit, you should be able to write and execute a given algorithm
    using C++ Programming language.

    Unit Outline
    • Evolution and features of C++.
    • Compiling and executing C++ programs.
    • Input and output streams.
    • Variables.
    • Constants.
    • Output formatting.

    Introduction
    In 1980s when object-oriented programming started to gain grounds, Bjarne Stroustrup who was then a researcher at AT&T Bell Laboratories took the most popular language, C, and extended it with object-oriented features of SIMULA 67 and Smalltalk to facilitate object-oriented programming (OOP). To date, C++ is one of the best languages for multi-paradigm programming and a good language for learning procedural and object-oriented programming paradigms. In this unit, we begin by tracing the evolution of C++ then demonstrate how to write C++ programs.

    10.1 Evolution and features of C++
    10.1.1 Evolution of C++

    Evolution of C++ can be traced back to 1980 when Bjarne Stroustrup developed a language he referred to as “C with Classes” at Bell Laboratories. Motivated objectoriented programming pioneered in Smalltalk, Stroustrup included powerful features of SIMULA 67 into C with design goal of supporting object-oriented programming while retaining backward compatibility with C.

    By 1984, more enhancements had been added to “C with Classes” hence it was renamed C++. Therefore, the name C++ uses C increment operator (++) to indicate that C++ is an enhancement of C. This integration of object orientation into proceduraloriented C makes C++ a multiparadigm language suitable for developing system software like operating systems.

    10.1.2 Features of C++
    The design and evolution of C++ describes the principles of C++ that make it suitable language for cross-platform systems programming. This section gives an overview of C++ key design, programming and language-technical concepts that you may

    need to familiarise with before you start writing programs. The following are general
    features of C++ that makes it one of the most powerful and flexible programming
    supported by most computers.
    • Portability: Programs written in C++ are portable across multiple hardware and software platforms. For example, a program developed to run on Microsoft Windows can be run on Linux or Macintosh operating systems with minimal or no modification.
    • Object-oriented programming: The design goal of C++ is to support objectoriented programming. As mentioned earlier, instead of using function that access global variables, both data and variables are encapsulated into an object. This make data more secure because the communication between program objects is through message passing
    • Keywords: Keywords also referred to as reserved words are words that have special meaning in a language and can only be used for intended purpose. C++ has a large number of reserved words such as include, main, while, for, if, else and return.
    • Identifiers: In C++ programming, identifiers are symbolic names used to identify elements like variables and constants in a program. Because C++ s case sensitive, it is important to observe caution when creating user-defined identifiers.
    • Operators: Operators are used to evaluate an expression that returns a value. The three main types of operators supported both by C++ are arithmetic (+, -, /,* and %), relational (e.g. >, <, = =, != ), and logical (&&, | |, !). Other compound operators include increment (++), decrement operators (– –), bitwise operators, and ternary (? smile operator.
    • Storage in memory: In C++ a variable is a named storage location in computer memory for holding data of a particular type. Common data types supported by C++ include integers, floating-point (real), characters, arrays and records. C++ also supports complex data types such as struct(records), arrays and linked lots.
    Case sensitive: C++ is case-sensitive. This means that an identifier (symbolic name) in uppercase is different from the same identifier in lowercase. For example, an identifier “age” is completely different from “Age” or “AGE”. Most programmers C++ prefer to use lowercase for variable names, and uppercase in case of constants.
    Type checking: C++ provides a rules and mechanism for checking data types before execution starts. If a compiler detects inconsistence, it ensures that the data conversions defined in the language or by the user do not cause runtime errors or system failure.

    Assessment Exercise 10.1
    1. Using examples, discuss the main features of C++ programming language.
    2. Explain why C++ is regarded as a system programming language.
    3. Describe chronologically, the evolution of C++ programming language.
    4. Explain why C++ is regarded as multi-paradigm programming language.
    10.2 Syntax of C++ Program
    In C++, a program may consist of objects, functions, variables, and other components. However, regardless of size or complexity of a C++ program, the program has to include directives, and at least one function called main. For simplicity, the Fig. 10.1 shows general syntax of a C++ program:

    10.2.1 Sample C++ program
    To demonstrate the general syntax of a C++ program, we start with a HelloWorld program 10.2(a) whose output is shown in Fig. 10.2(b). Such a program is widely used to introduce beginners to any programming language.

    • The first line that starts with forward slash is a comment that describes what the program does. Comments are ignored by a compiler, but that may inform other programmers what the program is doing at any particular point. There are two types of comments: (/*...*/) or double-slash (//). The /* … */ multi-line comment instructs the compiler to ignore statements within the delimiters. On

    the other hand, the // is a comment delimiter that instructs the compiler to ignore a single-line comment.
    • The second statement #include <iostream> that starts with # is known as a preprocessor directive because it instructs a preprocessor to search for iostream file and insert it into your program. A preprocessor is a utility program that processes special instructions written in a C++ program. The preprocessor directive to include the iostream is critical because it contains input and output functions. In the past, the directive was accomplished using old style directive #include<iostream.h> that instructs a preprocessor to include iostream.h header file into the source code. In standard C++, this directive has been deprecated meaning that it is no longer supported by some compilers. However, to demonstrate
    use of <iostream.h>, hello world program can be rewritten as follows (Fig. 10.3):

    • Using namespace std; namespace is a feature in C++ used to ensure that
    identifiers do not overlap due to naming conflict. Identifiers may overlap by
    sharing different parts of a program. Each namespace such as std (standard)
    defines a scope in which identifiers are placed. This eliminates the need to use
    an operator called scope resolution operator represented by (:smile.
    • int main (); C++ programs consist of one or more functions. The parentheses
    after main indicates that this is a subprogram unit known as a function. In
    C++, the main egg function is executed first regardless of its location within the
    source code. The int (integer) before main egg indicates that the function gives
    out (returns) integer to another function. The curley bracket { immediately after
    egg parenthesis is the opening delimiter that shows the start of the main function
    body.
    • cout <<“Hello World”;This is the statement that actually displays Hello World
    statement on computer screen. The first word cout that stands for console out
    is used to fetch output from computer memory and print it on the screen. In this
    example, cout together with the symbol << known as stream insertion operator
    causes Hello World to be printed on the screen.
    Following Hello World string is the << endl that forces the cursor to be moved
    to a new line. The alternative is use of ‘In’ as shown below.
    cout “Hello World|n”;

    • return 0; When return statement is used at the end of a function, a value of 0 (zero) is returned to the operating system to indicate that the program has terminated successfully.
    • The last curly bracket, } is a closing delimiter that denotes the end of the main function.

    10.2.2 Compiling and Executing C++ Program
    Typically, compilation and execution of C++ programs goes through six phases: edit, preprocess, compile, link, load and execute illustrated in Fig. 10.4. In this section, we explain these steps used to create helloworld program discussed above using an open source development environment known as DevC++.

    10.2.2.1 Editing Source code
    In programming context, writing a program is commonly referred to as editing source code. You first create a C++ program source file such as the hello program discussed earlier using the editor, make necessary corrections and save the program on a secondary storage device, such as the hard drive with .cpp, .cxx, or .cc extensions e.g my.cpp. Each statements must end with a semicolon and a block of statements belonging to a function or control structure must be enclosed in curley brackets. The most common C++ statements include: input statements starting with cin >>, output statements that start with cout<<, and assignment such as an expression to add two numbers.

    There are several commercial and open source development tools available in which you can compile, build and run C++ applications. Common examples include GNU C++, Dev C++, Microsoft Visual C++, CodeLite, NetBeans and Eclipse.

    10.2.2.2 Preprocessing
    Once you issue the command to compile the source code, a preprocessor runs just before the compilation starts. The preprocessor obeys commands called preprocessor directives such as removing comments and blank spaces from the source code before compilation takes place.

    10.2.2.3 Compiling
    Compiling is the next step after preprocessing in which the source code is translated into object code. For example, the above illustration shows that my.cpp source code is compiled to my.obj.

    10.2.2.4 Linking
    C++ programs contain references to functions defined elsewhere such as the iostream. A linker combines the object code compiled from your source code with the imported library functions to produce an executable file. In Microsoft Windows, executable files have .exe extension such as My.exe shown earlier in Fig.10.4.

    10.2.2.5 Loading
    Before a program is executed, it must be loaded from the disk into main memory. This is done by the loader that takes executable file from the storage media and loads it into main memory.

    10.2.2.6 Execute
    Finally, the computer executes the program in memory. Once the program encounters the end marker, it is unloaded from main memory and control returned to the operating system. To execute a program, type the file name with exe extension e.g my.exe at the command prompt.

    Activity 10.1: Compiling and executing C++ program Write a C++ program named CPPTutorial that displays a statement “Programming in C++ is Fun”. Using illustrations, explain the process the program undergoes from to be translated from source code to an executable program.

    Assessment Exercise 10.2
    1. Explain the importance of the following compiler utilities:
    (a) Preprocessor. (b) Linker.
    2. Using an illustration, explain how a C++ program is compiled from source code to an executable file.
    3. Identify integrated development environments (IDE) or tools that can be used to create C++ applications.

    4. Study the sample C++ code below and identify possible syntax errors:

    5. Using appropriate C++ integrated development environment, create a program that displays in “Rwanda is a Beautiful Country”.

    10.3 Input and Output Streams
    In C++, input/output (I/O) operations occurs in streams which are sequences of bytes. During input operations, bytes flow from a device e.g., output keyboard to main memory while in output operations, bytes flow from main memory to devices, e.g., monitor. The C++ standard library contains iostream header that declares basic services required for stream I/O operations. The header defines cin and cout objects that correspond to the standard input stream, and output stream.

    10.3.1 Output Stream
    Output capabilities in C++ are provided by a library file known as ostream. The ostream has an object called cout that stands for console out that prints output on a standard output, usually a display screen. The object is used in conjunction with stream insertion operator, which is written as << (two “less than” signs). For example, the following cout statement statement causes the statement “Let’s be one Nation” to be printed on the screen:

                                cout<< “Let’s be one Nation”;

    In this case, the << operator inserts the data that follows it on the right. In this case, “Let’s be one Nation” is displayed on the standard output stream.

    10.3.2 Input Stream
    In C++ handling input is done using the cin combined with >> known as stream extraction operator. cin represents the standard input device (or Console INput), i.e., keyboard. The symbol >> after the cin. The >> operator causes data input such as an integer value to be input from cin into computer memory. The operator must be followed by the variable that stores the data to be extracted from the stream. For example, the following statements extracts value such as 78 from keyboard buffer (temporary memory) and assigns it to score:

                                    cin>>score;

    It is important to note that the >> operator skips black spaces encountered in the input stream. The following program demonstrates use of input and output stream to read (accept input) and write (display) the output.

    Fig. 10.5 shows the output after running the program.

    In the program, the cout << “Enter first integer: uses cout << outputstream to display a prompt message. This is followed by cin >> firstInt; statement used to read the user input from the keyboard and store the value into variable firstInt.

    Activity 10.2: Inputstreams and outputstreams
    Fig. 10.6 shows a pseudocode for a program that takes three numbers x, y and z, evaluates the expression and displays the result on the screen. Study the pseudocode and convert it to a C++ program.

    10.4 Variables and Data types
    The main memory is divided into byte locations also called memory cells as shown in Fig. 10.7. The number associated with memory location is called memory address. A group of consecutive bytes is used as the location for a data item, such as an integer or character. In this section, we describe how to store data of as valuables in memory cells.

    10.4.1 Variables
    In C++, a variable can be defined as a portion or location in memory set aside to store a certain value such x or y whose content is subject to change. It is called a variable because the value stored in it can be changed. In C++, a variable must have a “name” also known as identifier to uniquely identify the variable and type of data that to be stored in the variable.

    Activity 10.3:Variables
    In groups, let each member perform the following mental challenge for timed 30 seconds: Take the first number x whose value is 5 and store it in your memory. At the same time take another number y whose value is 2. Now, add 1 to the first number, then adds the two numbers, and finally deduct 4 from sum of x and y. What is the final answer?

    The mental process that you have just done in activity 10.3 with your memory is similar to what a computer can do with two variables. The same process can be expressed as pseudocode shown in Fig. 10.8:

    The activity demonstrates how a computer can store millions of numbers in memory, conduct sophisticated mathematical operations, and return the answer within fraction of a second.

    In C++, each variable requires an identifier (symbolic name) that distinguishes it from other variables. The following rules may be observed when naming variables and other identifiers in C++:
    1. A valid identifier is a sequence of one or more letters, digits or underscores characters ( _ ). For example, x, sum, and age are valid identifiers.
    2. C++ is a “case sensitive” language. This means that an identifier written in uppercase is not the same as that written in lowercase letters. For example, “House” is not the same as “house.”
    3. Avoid using spaces between words. For My House should be written as one word like MyHouse or use an underscore to combine the two words (My_House).
    4. Variable identifiers should always have to begin with a letter. For example, “3houses” is invalid.
    5. Identifiers may start with an underscore character ( _ ), but in some cases the syntax is reserved for keywords.
    6. The syntax rule of C++ defines keywords also known as reserved words, which have a unique meaning and must not be used for any other purposes. The reserved words already used are main, int, return, and using. The table below lists the reserved words of C++. C++ Reserved Words, all of which are in lower-case letters as shown in Table 10.1.

    7. Avoid meaningless identifiers such as J23qrsnf, and restrict single letter variable names such as x or i to variables that are used temporarily in the a section of the program.

    Activity 10.4: Rules of naming variables
    From relevant sources, identify all the keywords in C++ and explain what would happen if a programmer uses one of these keywords as a variable identifier.

    10.4.2 Data types
    The computer memory is organised in to cells that can store one or more bytes. A byte is the minimum amount of memory that we can manage in C++. To declare a variable, you must declare the type of variable so that the computer reserves enough bytes to store a value of that type.

    10.4.2.1 Data types
    Primary data type refers to basic data types used to identify the type of values used in a program. The most common primary data types in C++ include: int, char, float, double, bool,
    long int and short int. Table 10.2 shows summary of primary data types, memory size, and range of acceptable values.

    10.4.2.2 Complex data types
    A complex data type is a combination data of similar or different types. C++ supports complex data types such as string, array, struct (record), enumerated type, linked lists, and pointers. Apart from string data type, other examples of complex data types include arrays, linked lists, stacks, queues, trees and graphs. In this section we only demonstrate how to declare a string. To declare data of the type string, use the general syntax. String var name e.g string student_name;

    Activity 10.5: Data types
    In a C++ program, if user declares a short integer variable and enters a number such as 78,500 or a string like “pen”, the program may return a runtime error or display gabbage. Define the term memory overflow and explain the nature of results produced by such a program.

    10.4.3 Declaration of variables
    Variable declaration refers to reserving memory location by specifying the type of data to be stored. To declare a variable in C++, we use the following general syntax:
                           data_type variable_name;
    For example, the following two statements are valid declarations that instructs a computer to reserve 4 bytes for variable a, and 8 bytes for means core: mean_score.
                                      int a;// reserve 4 bytes
                               double mean_score; //reserve 8 bytes

    To declare more than one variables of the same type, use a single statement but seperate identifiers with commas as follows:
               data_type variable1, variable2...variablen;
    For example:
                           int first_Int, second_Int, sum, difference;
    This declares four variables; first Int, second int sum and difference of integer type. The statement can also be written as follows.

                                              int first_Int;
                                              int second_Int;
                                              int sum;
                                              int difference;

    Depending on the range of numbers to be represented, data types like short, long and int can either be signed or unsigned. Signed type represents both positive and negative values, while unsigned type can only represent zero and positive values. This can be specified using signed or unsigned as follows:

                                unsigned short int number_of_sisters;
                                  signed int MyAccountBalance;

    Due to difficulties experienced in manipulating strings, C++ introduced a data type known as string. The data type treated as an object in C++ is associated functions (methods) used to manipulate literal strings.

    Activity 10.6: Declaration of variables
    1. Study the program of Fig. 10.9 that prompts a user to enter two numbers: a and b. The program then multiplies the two numbers, and displays a valid product on the screen. To avoid possible memory overflow, replace the product data type with appropriate size that will hold a large value:


    2. Using suitable variable declaration, convert activity 10.3 consisting of variables x, y, sum and diff into a C++ program.

    10.4.4 Scope of variables
    The scope of a variable can either be global or local. A global variable is declared outside all functions while a local variable is declared within a function.. For example, the program shown in Fig. 10.10 declares global variables: area and perimeter outside the main function and local variables length and width within the main() function.


    10.4.5 Initialisation of variables
    By default, when you declare a variable, its value is unknown unless the user provides input. For a variable to store a concrete value, you can initialize it with a default value as follows:
                              data_type identifier = initial_value;
    For example, to initialise Age with a default value 0, we write the definition:
                              unsigned int Age = 0; or unsigned int Age (0);
    The program below shows how to initialise variables age and height to default values 24 and 5.7 as shown on the output screen. The program output shown in the following figure.


    NB: Declaring and initializing a variable with a default value is referred to as defining a variable. In other words, to define a variable is to state its data type, identifier and assigning it an initial value.

    Activity 10.7: Initialisation of variables
    Consider earlier problem in Activity 10.3. By initializing x with 5 and y with 2, write a program that returns sum and difference.

    Assessment Exercise 10.3
    1. Using C++ statement, demonstrate how to define a variable that stores Rwanda cities and towns. The variable should be initialised with the name of the capital city, i.e. Kigali.
    2. Write a C++ program that can be used to compute hypotenuse of a right-angled triangle whose sides are a, b and c shown in Fig. 10.12 below. Note that in to easily solve the problem, you may be required to use an in-built square function.


    10.5 Constants
    Unlike variables, a constant is a value in memory that does not change during program execution. For example, in mathematics, pi is a constant whose numeric value is 22/7
    or 3.142. In C++, constants may be classified into literal constants and symbolic constants.

    10.5.1 Literal Constants
    Literals constants are used to express particular values within a program. For example, in the following statement, 25 is a literal constant because you can neither assign another value to it nor can you change it. x + 25;
    Literal constants can be classified into integer numerals, floating-point numerals, characters, strings and boolean constants. For example, 75 is an integer literal constant, while 75.0 is a floating-point literal constant. On the other hand “K” a single
    character constant while string.
    Note that in C++, a character consists of one letter or numeral enclosed within single quotation marks such as ‘H’ while a string consists of one or more characters

    in double quotation marks. Boolean literal constants takes only two values, i.e., true (1) or false (0).

    10.5.2 Symbolic Constants
    A symbolic constant is a constant that is represented using a symbolic name. Once a symbolic constant is initialised, its value cannot be changed. There are two ways to declare a symbolic constant in C++ are:
    1. Using preprocessor directive #define. For example, the following statement declares a symbolic constant named sodas_crate that is replaced by 24 during execution:

                                  #define sodas_crate 24;

    2. Using keyword const followed by the data type of the symbolic constant as shown in the statement below:
    For example,

                        const short int sodas_crate = 24;

    The advantage is that the compiler is able to determine data type of the constant hence preventing possible runtime errors.

    10.5.3 Declaring Constants
    To declare a symbolic constant of a specific data type in C++ use the keyword const as follows:

                       const double PI = 3.142;

    The following program (Fig. 10.13) demonstrates how to declare a symbolic constant P1 used in a calculating area of a circle. See the output in Fig. 10.14.


    Fig. 10.14 shows a sample output after running the program.


    Activity 10.8: Declaration of constants
    Using C ++, write a C ++ program that prompts a user to enter the radius of a sphere,
    the program then calculates the surface area and volume of the sphere. In the source
    code, you must declare Pi as a symbolic constant whose value is 3.142.

    10.6 Output Formatting
    In programming, creating nicely formatted output is a good programming practice to improve readability of output and the user interface. In C++, the output stream has special characters and objects called manipulators used to format numbers, character sand strings. In this section, we discuss a few manipulators found in <iostream>.

    10.6.1 The endl manipulator
    When supplied with operator << at the end of a statements, endl object causes a newline
    character to be inserted at the end of a line. For example, the Hello word statement in our first program can be formatted to appear on its own line with the cursor blinking on a new line using the statement below:

                               cout << “Hello, world!” << endl;

    10.6.2 The setw() manipulator
    To produce number and string output formatted to fixed width in terms of number of character, C++ has a manipulator object called setw(). For example, setw(20) in the statement below adjusts the field width between the asterisk and Hello to 20 characters. If the characters are fewer, a blank space is inserted on the left of the output.

                                    cout<< “*”<< setw(20)<< “Hello!”<<endl;

    10.6.3 The setprecision() manipulator
    In C++, formatting floating point numbers may be rounded off to the nearest integer using setprecision() manipulator. The object is used together with fixed or scientific manipulators to specify the number of digits to be displayed. For example, the following statements rounds off the number to 2 decimal places:

                                      cout<<setprecision(2)<<fixed<<1234.56789

    To use the setw() and setprecision() manipulators, you must include <iomanip> preprocessor directive. For example, the following program demonstrates how to use the three objects to format output as shown in Fig. 10.15.


    Fig. 10.14 shows the output formatted using sector(), setprecision fixed and scientific manipulators.


    10.6.4 Format Base of Integer Output
    In computing, the commonly used numeric constants are decimal integers, floating point (real numbers), octal (base 8) and hexadecimal (base 16). In C++ we use format specifier to format or convert a number from one base to another. To change the base of printed values use dec, oct, and hex manipulators. The following program demonstrates how to format the three number systems:



    10.6.5 Format Output using Escape Sequence
    Output formatting can also be accomplished using a combination of a backslash and a character, known as escape sequence. They are called escape sequences because the backslash causes an “escape” from normal way a character is interpreted by C++ compiler. An example of an escape sequence used instead of endl is the newline “\n” that causes the cursor to go to a new line. The following program uses “\t” escape sequence characters to format output into rows and columns.



    Table 10.4 shows a summary of common escape sequence used to format output:


    Activity 10.9: Formatted output
    Create a BMI calculator program that reads the user’s weight in kilograms and height in meters, then calculates and displays the user’s body mass index in three decimal places using the expression below:


    Assessment Exercise 10.4
    1. Explain the importance of using fixed and scientific notation in formatting of floating-point numbers.
    2. Using manipulator functions setw() and setprecision (), modify the program used for calculating surface area and volume of a sphere in Activity 10.9 so that the results are displayed correct to two decimal places.
    3. Explain importance of the following escape sequence characters used to format output in C++ programs: \n, \b, \a, and \t.

    Unit Test 10
    1. Define the term reserved word.
    2. Explain why C++ is both procedural and object-oriented programming languages.
    3. Explain how C++ evolved from C.
    4. State five common features in C and C++ programming languages.
    5. Differentiate between procedural and object-oriented programming.
    6. State five rules that should be observed when choosing constant and variable
    identifiers.
    7. Why is it illegal to use a keyword such as if, else or for reserved for specific
    purpose in C++?
    8. Write a program showing the basic structure of a C++ program.
    9. Write a C++ program that allows the user to enter marks for three subject. The
    program should calculate, then display the total and mean score of the three
    subjects.
    10. Write a program that prompts a user to input five floating point numbers. The
    program computes sum and average, and then displays the results correct to 3
    decimal places.
    11. Write a program that reads temperature for a week in degree celsius, converts
    the celsius into Fahrenheit, and then calculate the average weekly temperature.
    The program should display the output formatted to 2 decimal places.
    12. Malaika took a loan of FRW 400 000 from a bank payable in three years at an
    annual interest rate of 8%. Write a program that calculates total amount paid at
    the end of the third year.



    Unit 9:INTRODUCTION TO COMPUTER PROGRAMMINGUnit 11:EXPRESSIONS AND OPERATORS IN C++ LANGUAGE