Top Banner

of 24

CHAPTER 2 Intro to CPP Programming

Aug 08, 2018

Download

Documents

Rochelle Ann
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    1/24

    OBJECTIVES:

    At the end of the chapter the students should be able to:

    1. Familiarize themselves with the Microsoft(MS) Visual

    C++ Integrated Development Environment (IDE).2. Understand the basic components of a C++ program.

    3. Classify identifiers, keywords, constants, and variables.

    4. Enumerate and apply the basic data types of C++.

    5. Identify the different operators to be used.

    6. Know the precedence of operators.

    CHAPTER 2INTRODUCTION TO

    C++ PROGRAMMING

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    2/24

    20

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    3/24

    C++ was developed mainly for an object-oriented programming (OOP) approach.

    However, it can process both OOP and structured programming, with the latter being the

    focus of this books discussions.

    2.1The Integrated Development Environment (IDE)

    Before we get our hands dirty, it would be better for us to navigate the editor that we will

    be using in programming C++.

    Figure 2.1

    The Microsoft Visual C++ IDE

    Figure 2.1 illustrates the C++ editor, commonly called the Integrated Development

    Environment or IDE. An IDE is a program that hosts the compiler, debugger, and

    application-building tools. You can create programs, access the online help, and performdebugging without leaving the IDE. Below are some of the common features of the MS

    Visual C++ IDE:

    TitleBar MenuBar ToolBar

    Wiz

    ard

    Bar

    Project

    Workspace

    Editor Window

    Output Window

    21

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    4/24

    Automatic syntax highlighting colors keywords, comments, and other source

    code in different colors.

    Automatic smart indenting helps line up your code into easy-to-read columns.

    Auto-Completion automatically displays a menu of items to help you finish C++

    statements.

    Parameter Help displays the parameters for Windows functions as you type.

    Integrated keyword help enables you to get help on any keyword just by pressing

    F1.

    Drag-and-drop editing enables you to move text easily by dragging it with the

    mouse.

    Integration with the compilers error output helps you step through the list of

    errors reported by the compiler and positions the cursor at every error.

    Like any other Windows application, the MS Visual C++ Environment has its own titlebar, menu bar, and toolbars to help users perform programming tasks fast and easy. It

    also has three separate windows which perform different functions: documentoreditor,

    project workspace, and output.

    The Document Window / Editor Area

    The area on the right side of the IDE is the editor area. This is the area where youperform all your editing when using MS Visual C++.

    The Project Workspace Window

    The workspace, as it is normally called, appears on the left side of the IDE. It allows you

    to navigate the various parts of your development code, and can be viewed in two

    different ways:

    1. The Class View,which allows you to navigate and manipulate your source code

    on a C++ class level;and

    2. The File View,which allows you to view and navigate all the files that make up

    your application.

    The Output Window

    The output window appears at the bottom of the IDE and remains open until you chooseto close it. It provides information such as compiler progress statements, warnings, and

    error messages.

    22

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    5/24

    2.2 A Simple C++ Program

    Let us look at a very simple example of a C++ program:

    Source Code 2.1

    Welcome to C++!!!

    Source Code 2.1 is what is referred to as a program source code. It is made up of a

    combination of letters, numbers and other symbols. We will be writing and executing

    programs using the MS Visual C++ IDE.

    In this book, we will write C++ programs using the following format:

    void main(void){

    }

    HEADER FILES

    Like other programming languages, C++ has a large collection of pre-defined functions.

    You may think of a function as a group or sequence of statements. In some cases,

    programmers refer to functions as subprograms. The word pre-defined means thatusers or programmers can use the function without knowing or concerning themselves

    how they were written. For the meantime, we will only be using the header file

    iostream.h, which stores the standard input/output functions of C++.

    FUNCTIONS

    /* This is a simple C++ program */

    /* declaration of header file */

    #include

    /* start of main program */

    void main(void)

    {

    cout

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    6/24

    All statements should be written inside a user-defined function. The word user-defined

    means that it is the user who defined (or wrote) the description of a function. In Source

    Code 2.1, there is only one user-defined function the main() function. Take note that allC++ programs must have a main() function.

    STATEMENTS

    All C++ programs are made up of a sequence of instructions. In C++, instructions are

    also called statements, wherein a semicolon terminates each statement.

    In Source Code 2.1 above, there is only one statement -- the coutstatement. coutis thestandard output operator of C++ that is stored in the header file iostream.h.

    THE { } SYMBOLS

    The symbols { (open brace or open curly bracket) and } (close brace or close curly

    bracket) are used for grouping purposes. In the example program above, the open and

    close curly brackets signify the beginning and the end of the main() function respectively.

    Take note however that the curly brackets must always come in pair. A missing curly

    bracket is one of the most common causes ofsyntax errors. A syntax error is a

    programming error violating the rules that specify how a command or instruction should

    be written.

    As we shall see later on, the curly brackets are used to group several statements.

    THE /* */ SYMBOLS

    The symbols /* and */ are used for block comments inside the program. Comments

    simply provide additional information such as what the program is doing: what are the

    inputs, what are the outputs, etc. Think of /* as the beginning of a comment, and the */ as

    the end a comment. Just like the curly brackets, they symbols always come in pair.

    Comments are optional and maybe placed anywhere within the program source code.

    It is possible to write several lines of comments inside /* */. For example:

    24

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    7/24

    Source Code 2.2

    Block Comment

    Note that comments cannot be nested, i.e. you cannot put /* */ inside /* */. For example,

    the following will cause a syntax error:

    /*

    this is a comment

    /* this is one more comment which will cause an error */

    */

    Another option that can be used in inserting comments is by using // (double slash) for

    single line comments. This is so because the comment terminates at the end of the

    current line. For example:

    Source Code 2.3

    Single Line Comment

    #include

    /* The following is

    an example

    of a very simple C program */

    void main(void)

    {

    cout

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    8/24

    2.3 Identifiers, Keywords, Constants, and Variables

    2.3.1 NAMING CONVENTIONS

    Data and instructions to manipulate data are referred to by their names, also called

    identifiers. In C++, the following are rules and conventions to follow in giving a name:

    1. Names are made up of letters and digits.

    2. The first character must be a letter or an underscore (_). However, an underscore

    is not recommended to be used as the first character in a name since some of C+

    +s internal identifiers begin with underscores.3. C++ is case-sensitive, i.e., the lower-case letter a is not the same as the

    uppercase letter A.

    4. At least the first 31 characters of a name are significant.

    Valid

    Identifiers

    Invalid Identifiers

    Names Error Description

    a 1 must start with a character

    A 1_ab must start with a character

    main a& & symbol cannot be used in a name

    salary_per_day xyz_% % cannot be used in a name

    Student_1

    Student1

    Table 2.1

    Examples of Valid and Invalid Names in C++

    Table 2.1 above shows some examples of valid and invalid names in C++.

    2.3.2 KEYWORDS

    MS Visual C++ has its own set of keywords. These names are reserved and cannot beused for other purposes such as in naming user-defined variable names. In the example

    source codes above, the name void is a keyword. The MS Visual C++ language has a

    total of 59 keywords shown below.

    26

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    9/24

    break enum operator template

    bool explicit private this

    case extern protected throw

    catch false public truechar float register try

    class for reinterpret_cast typedef

    const friend return typeid

    const_cast goto short typename

    continue if signed union

    default inline sizeof unsigned

    delete int static using

    do long volatile virtual

    double mutable static_cast void

    dynamic_cast namespace struct while

    else new switch

    Table 2.2

    C++ Keywords

    It is important to note that main is a not a keyword in C++. However, although the name

    coutis actually not a C++ keyword and is not really part of the language, it is a name pre-

    defined in the standard input/output library, thus, it cannot be used as an identifier in C++

    like main.

    2.3.3 CONSTANTS

    Constants are entities whose value does not change. A constant can either be numeric

    constant or a literal constant. In C/C++, a numeric constant can be an integer or floating

    point number, while a literal constant can be a single character or a string, i.e. a constant

    with more than one character. A single character is written such that it is enclosed in a

    pair of single quotes. A string is written enclosed in a pair of double quotes.

    Numeric Constants Literal Constants

    1 'A'

    123 "A"

    -123 "Welcome to C++!!!"

    3.1416 "The quick brown fox jumps over the lazy dog."

    Table 2.3Examples of C++ Constants

    27

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    10/24

    The Table 2.3 shows some examples of numeric and literal constants. It is important to

    note that even if 'A' and "A" contains the same value, they are of different types. The

    former is a character while the latter is a string.

    2.3.4 VARIABLES

    A program is made of data and instructions to manipulate those data. Note that data have

    to be stored somewhere, and thus will need some memory space in the Random AccessMemory (RAM). In a C++ program, a variable is the entity that holds data. A variable, as

    the name suggests, is a varying entity depending on the actual data it holds. Without

    variables, it would be impossible to store data. A variable has the following

    characteristics:

    1. a symbolic name;

    2. an associated physical memory space (portion in a RAM);3. a data type;

    4. a value that depends on the data type;

    5. a scope; and

    6. a lifetime

    2.4 Basic Data Types in C++

    A data type specifies the kind of values can be assumed by a variable of that type, the

    range of values that can be assumed by a variable of that type, and the amount of memory

    (in bytes) needed by a variable to store a value of that type.There are five basic data types in C++, namely:

    char the character data type. The char data type is used to

    represent/store/manipulate character data values. The range of values that can be

    assumed by a char value is from 0 to 255. The number-to-character coding that isused in the American Standard Code for Information Interchange (ASCII).

    int the integer data type. The int data type is used to represent/store/manipulate

    signed whole numbers. The range of values that can be assumed by an int value

    is from -2147483648 to 2147483647.

    float the single precision floating point data type. The float data type is used to

    store single precision signed real numbers. The appropriate range of values that

    can be assumed by a float value is from 3.4 X 10 -38 to 3.4 X 1038. double the double precision floating point data type. The double data type is

    used to store double precision signed real numbers. The appropriate range of

    values that can be assumed by a double value is from 1.7 X 10-308 to 1.7 X 10308.

    bool the Boolean data type. The bool data type is used to represent Boolean

    values true orfalse.

    28

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    11/24

    The amount of memory space required to store an int, a floatand double is platform-

    dependent (depends on the machine and the software). For compilers such as the

    Microsoft Visual C++ compiler, a charand boolrequires 1 byte of memory each, an int

    andfloatrequires 4 bytes of memory each, while a double requires 8 bytes of memory.

    Note that a chardata type is actually numeric (from 0 to 255), and is treated as a subset

    ofintvalues. Any operation on integer values can also be performed on characters.

    The following program can be used to print the sizes of the basic data types:

    Source Code 2.4

    ThesizeofOperator

    Thesizeofis a keyword in C++. It is an operator that yields the size in number of bytes

    of the specified data type.

    2.5 Variable Declaration

    A variable declaration is an action by which a variable is introduced to a

    program/function. All variables in a C++ program must be declared. If you forgot to do

    so, the compiler will report a syntax error. The syntax for declaring a variable is as

    follows:

    ;

    A semicolon signifies the end of a declaration. A missing semicolon will cause thecompiler to generate a syntax error. Variables should be named following the C++

    naming conventions. For example:

    #include

    void main(void){

    cout

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    12/24

    char ch;

    bool b;

    int i;

    float f;double d;

    It is possible to declare several variables of the same type on the same line. In such a

    case, a comma should be inserted between two variables. A missing comma will generate

    a syntax error. For example:

    char ch1, ch2;

    bool b1, b2;

    int x, y, z;

    float degree_celsius, degree_fahrenheit, degree_kelvin;

    double numerator, denominator;

    In general, C++ allows the user to declare variables in any part of the program code

    before they can be used, but this is not advisable, especially for long programs.

    Although we can use any name for the variables, it is recommended, however, as a good

    programming practice for you to use a name that is descriptive or suggestive. For

    example, if you know that a variable will represent a temperature in degree Celsius, then

    dont use names such as x or c1. It is better to use a variable name such as celsius or

    degree_celsius. Note that the use of the underscore makes reading the variable name easy

    to read.

    By default, the value of a variable in C++ is GARBAGE, i.e., there is something stored inthat memory space but that something is invalid for the intended use. The use of a

    variable with a garbage value will cause a logical error. Unlike syntax errors, the

    compiler is not capable of detecting logical errors since these are errors committed by theprogrammer on the program or logic flow. To avoid such instance, we must assign a

    valid value to a variable before performing any operation on the variable.

    2.6 Operators

    Operators are symbols representing operations that can be performed on constants and

    variables. There are four basic operations available in C++ language.

    1. Assignment Operation

    2. Arithmetic Operation

    3. Relational Operation

    4. Logical Operation

    30

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    13/24

    The assignment operator is denoted by the equal symbol (=). It is used to store (i.e.,

    assign) a value to a variable. The syntax of an assignment operation is:

    = ;

    In the syntax above, variable name can be any valid identifier in C++, while expression

    can be a constant, variable or a valid expression.

    2.6.1 THE ASSIGNMENT OPERATOR

    The assignment operation is also a statement, thus a semicolon should terminate it.

    Source Code 2.5 below shows how to use the assignment statement. Expect, however,

    that if you run the program, there will be no output will be produced.

    Source Code 2.5

    The Use of the Assignment Statement

    It is also possible to assign a value of a variable to another variable of a compatible data

    type. For example:

    ch1 = Z;

    ch2 = ch1;

    x = 5;

    y = x;

    /* a sample program demonstrating the use of assignment statement */void main(void)

    {

    // declaration of variables

    char ch;bool b;

    int i;

    float f;

    double d;

    ch = A; // assign a char value to char variable

    b = false; // assign a false value (0) to bool variable

    i = 5; // assign an int value to int variablef = 1.25; // assign a float value to float variable

    d = 3.14159; // assign a double value to double variable

    }

    31

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    14/24

    If in some cases we assign a value whose data type is different from the data type of the

    receiving variable, the data type of the value will be converted to the data type of the

    variable (either demoted or promoted).

    2.6.2 THE ARITHMETIC OPERATORS

    MS Visual C++ supports a number of operators. The basic arithmetic operations, plus

    some other operations are available in C++ language. These are as follows:

    OPERATOR DESCRIPTION

    + (plus) addition (returns the sum of two operands)

    - (minus or dash) subtraction (returns the difference of two operands)

    * (asterisk) multiplication (returns the product of two operands)

    / (slash) division (returns the quotient of two operands)% (percent) modulus operator (returns the remainder)

    ++ (double plus) increment (returns the value of an operand plus 1)

    -- (double minus) decrement (returns the value of an operand minus 1)

    TABLE 2.4

    C++ Basic Arithmetic Operators

    The +, -, *, / , ++, and (we will elaborate more on the ++ and operators later) can be

    used for operands of type int, float and double data types. Actually, they can also be used

    on char since char is a subset of int. The % operator can be used only with integer

    operands. The first five operators in Table 2.4 are called binary operators because they

    require two operands, while the increment and decrement operators are referred to asunary operators because they require only one operand.

    The following program shows how to use the arithmetic operators with integer operands:

    32

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    15/24

    Source Code 2.6

    The Use of Arithmetic Operators

    In the example above, the statement e = 18 / 8; will result into a 2 instead of 2.25 (i.e.,

    the fractional part .25 is discarded). This is what we refer to as integer division, which

    occurs when the operands of the division operator are both whole numbers: char or

    integer values.

    When one of the operands is a float or double, the division is a real number division. For

    example:

    18.0 / 8 will result into 2.25

    C++ also provides a casting function which can be used to force a variable or an

    expression to be of a specific data type. The syntax for type casting is as follows:

    ()

    or

    ()

    Thus, the following operations can be used to retain the fractional part .25 from the

    previous example:

    #include

    void main(void){

    int a, b, c, d;float e;

    a = 10 + 15;

    b = 27 - 13;c = 4 * 6;

    d = 24 % 5;

    e = 18 / 8;

    cout

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    16/24

    (float)18 / 8

    float(18) / 8

    18 / float(8)

    18 / (float)8

    There are some important notes to remember in the use of C++ operators:

    Assigning a variable to a constant is syntax error. For example:

    12345 = x;

    Assigning the value of a variable to a variable of the same name is syntactically

    correct, but practically useless and does not make any sense. For example:

    a = 12345;

    a = a; // a get the value of a, which is 12345

    It is usual in programming to assign a value of an expression to a variable,

    wherein the old value of the variable is also used in the expression. For example:

    a = 50;

    a = a + 1;

    The statement a = 50; means the value 50 is assigned to a. The next statement adds 1 to

    this value resulting to 51, which is then assigned as the new value ofa.

    When an expression has sequence of arithmetic operations, it is evaluated following the

    MDAS rule, wherein multiplication or division should be performed first before additionor subtraction. To override this usual priority of operation, a pair of parentheses should

    be used. For example, given the expression:

    A + B * C

    Here the multiplication operation will be performed first before the addition. To perform

    the addition before multiplication, we have to write the arithmetic expression as:

    ( A + B ) * C

    Earlier, we were presented a C++ statement a = a + 1; which simply means increment

    the value of the variable a by 1. In the same way, if we intend to decrement a variable,say a, by 1 we can use the statement a = a - 1;. However, C++ provides a shortcutin

    performing such operations: the unary operators ++ (double plus) and -- (double minus).

    34

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    17/24

    The ++ is used to increment the value of an integer variable by 1. The -- is used to

    decrement the value of an integer variable by one. Source Code 2.7 illustrates the use of

    the ++ and operators.

    Source Code 2.7The ++ and -- Operators

    Used in a statement by themselves, the operators can be placed before or after a variable

    yielding same results. On the other hand, using the operators in a more complex

    expression will produce a different output. Source Code 2.8 shows an application of this

    behavior.

    #include

    void main (void)

    {

    char ch1, ch2;

    int a, b;

    a = 2;

    a++;

    cout

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    18/24

    Source Code 2.8

    The Use of the Prefix/Suffix ++ and -- Operators

    In the sample program above, the output after the statement b = a++; yields

    a = 11

    b = 10

    while the output after the statement b = ++a; yields

    a = 11

    b = 11

    2.6.3 THE RELATIONAL/COMPARISON OPERATORS

    The relational/comparison operators in C++ are as follows:

    #include

    void main (void){

    int a, b;

    a = 10;

    b = a++; // suffix ++

    cout

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    19/24

    OPERATOR DESCRIPTION

    == (double equal sign) equal to

    != (exclamation and equal sign) not equal to

    > (greater than sign) greater than< (less than sign) less than

    >= (greater than and equal sign) greater than or equal to

    y);

    d = (x < y);

    e = (x >= y);f = (x

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    20/24

    2.6.4 THE LOGICAL OPERATORS

    The logical operators in C++ are as follows:

    OPERATOR DESCRIPTION

    ! (exclamation mark) not

    && (double ampersand) and

    || (double bar) or

    TABLE 2.6

    C++ Basic Logical Operators

    The logical operators are normally used in conjunction with relational operators to test

    for multiple conditions. The logical NOT is a unary operator, it is used with only one

    operand to its right. The remaining operators are binary operators. The logical NOToperation is performed before logical AND, before logical OR.

    An actual C++ program that shows the result of the operators is presented below.

    Source Code 2.9

    The Use of Logical Operators

    #include

    void main(void)

    {

    /* logical NOT operator */cout

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    21/24

    2.6.5 THE PRECEDENCE OF OPERATORS

    The precedence of operators depends on their priority and associativity (i.e. is the

    expression evaluated from left to right or right to left). The table below presents the

    precedence and associativity of operators from highest to lowest. Operators that appear

    together have equal precedence and are evaluated according to their associativity.

    OPERATOR ASSOCIATIVITY

    ( ) postfix++ postfix-- Left to right

    ! prefix++ prefix-- & sizeof Right to left

    type casting Right to left

    * / % Left to right

    + - Left to right

    < >= Left to right== != Left to right

    && Left to right

    || Left to right

    = *= /= %= += -= Right to left

    Table 2.7

    Precedence of Operators

    39

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    22/24

    SUMMARY

    In this chapter we described the basic components of the Microsoft Visual C++ integrated

    development environment, which will be used in developing C++ programs. We also

    looked at the basic components in constructing a C++ program. Identifiers, keywords,

    constants, and variables were described. The basic data types of C++ were discussed

    accompanied by some example programs.

    Finally, the different operators accepted by the language were discussed including their

    precedence.

    40

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    23/24

    PRACTICE EXERCISE #2

    NAME: __________________________ DATE: _______________________

    COURSE/YR-SEC: ________________ INSTRUCTOR: _______________

    A. DIRECTION: Write C++ programs that will declare variables (using the appropriate

    data type) and assign values to these variables for the following problems. You can use

    any constant value for initialization purposes.

    1. Compute the sum of the integer values 1, 3, 5, 7, 8, and 9.

    2. The area of a rectangle is computed as length multiplied by width.

    3. The area of a triangle is computed as of the base multiplied by the height.

    4. The circumference of the circle is computed as 2 multiplied by PI (a constant

    value approximated as 3.1416) multiplied by the radius.5. The parameter of a square is computed as four multiplied by the length of its

    side.

    41

  • 8/22/2019 CHAPTER 2 Intro to CPP Programming

    24/24

    NAME: __________________________ DATE: _______________________

    COURSE/YR-SEC: ________________ INSTRUCTOR: _______________

    B. DIRECTION: Determine the results of the following operations.

    1. (A > B)

    2. (5.0 7)

    7. (2.0 < 2 || 5 > 5.0)

    8. !(5 4 || !(1))))

    42