+ All Categories
Home > Documents > -C++-Lecture01Introduction12

-C++-Lecture01Introduction12

Date post: 30-May-2018
Category:
Upload: booksofpavan
View: 215 times
Download: 0 times
Share this document with a friend

of 32

Transcript
  • 8/14/2019 -C++-Lecture01Introduction12

    1/32

    Computer Programming II 1

    IntroductionIntroduction

    Part IPart I

    Lecture 1Lecture 1

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    2/32

    Computer Programming II 2

    ObjectivesOb

    jectives

    One-Dimensional ArrayTwo-Dimensional ArrayReferences

    FunctionsReferences in FunctionsInline FunctionsFunction OverloadingDefault ArgumentsStructures (Records)Classes

    The following topics will be discussed in this Lecture:

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    3/32

    Computer Programming II 3

    Review of Arrays: One-Dimensional ArraysReview of Arra

    ys: One-Dimensional Arrays

    #include using namespace std;

    int main(){ int item[5]item[5] ; int sum; int counter;

    cout

  • 8/14/2019 -C++-Lecture01Introduction12

    4/32

    Computer Programming II 4

    Review of Arrays: Two-Dimensional ArraysReview of Arra

    ys: Two-Dimensional Arrays

    #include #include using namespace std;

    int main(){ const int NUMROWS = 3; const int NUMCOLS = 4; int i, j; int val[NUMROWS][NUMCOLS] = {8,16,9,52,

    3,15,27,6,14,25,2,10};

    cout

  • 8/14/2019 -C++-Lecture01Introduction12

    5/32

    Computer Programming II 5

    int x = 5;

    int & y = x; //ampersand sign (&) Read y is a reference to an int xint z = y;cout

  • 8/14/2019 -C++-Lecture01Introduction12

    6/32

    Computer Programming II 6

    Review of FunctionsReview of Functions - Function is a block of instructions that is executed when it is called from other point of the program.

    1. Function with1. Function with no return valueno return value andand no parametersn

    o parameters

    #include #include

    using namespace std;

    void SquareArea(void){ double Side;

    cout > Side;cout

  • 8/14/2019 -C++-Lecture01Introduction12

    7/32Computer Programming II 7

    #include #include using namespace std;

    int GetMajor( void )

    {int Choice;cout

  • 8/14/2019 -C++-Lecture01Introduction12

    8/32Computer Programming II 8

    #include using namespace std;

    double TotPrice( double ItemPrice, double TaxRate){ double Price;

    Price = ItemPrice + (ItemPrice * TaxRate / 100); return Price;}

    int main(){ double ItemPrice, TaxRate;

    cout > ItemPrice;cout > TaxRate;cout

  • 8/14/2019 -C++-Lecture01Introduction12

    9/32

    Computer Programming II 9

    #include #include using namespace std;

    void swap( int &i, int &j);int main(){ int x = 6, y = 9;

    cout

  • 8/14/2019 -C++-Lecture01Introduction12

    10/32

    Computer Programming II 1010

    #include #include using namespace std;

    void swap( int i, int j);int main(){ int x = 6, y = 9;

    cout

  • 8/14/2019 -C++-Lecture01Introduction12

    11/32

  • 8/14/2019 -C++-Lecture01Introduction12

    12/32

    Computer Programming II 1212

    Function callsFunction calls

    When a function call is encountered, the program

    jumps to the address of the function and thenjumps back when the function has completed

    Each time the program jumps toexecute a function, there is associatedoverhead:

    Loading the function

    Terminating the function call

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    13/32

    Computer Programming II 1313

    To help reduce function-call overhead .

    Advises the compiler to generate a copy of thefunctions code in place to avoid a function call.

    Should be used only with small, frequently usedfunctions.

    Tradeoff: multiple copies of the function code areinserted in the program.

    Inline FunctionsInline Functions

    With inline functions, the compiler replaces each instanceof the function call with the corresponding code

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    14/32

    Computer Programming II 14

    To define an inline function, insert thekeyword inline before the functiondefinition

    inline double square ( double x) { return x * x; }

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    15/32

    Computer Programming II 15

    int main(){

    myFunction(2);

    myFunction(5);}

    Inline void myFunction( int n){

    for ( int i = 0; i < n; i++){

    cout

  • 8/14/2019 -C++-Lecture01Introduction12

    16/32

  • 8/14/2019 -C++-Lecture01Introduction12

    17/32

    Computer Programming II 17

    #include #include using namespace std;

    void swap ( int &a, int &b); void swap ( float &a, float &b); void swap ( char &a, char &b);

    int main(){ int i1 = 3, i2 = 5; float f1 = 3.14159f, f2 = 1.23f; char c1='A', c2='B';

    cout

  • 8/14/2019 -C++-Lecture01Introduction12

    18/32

    Computer Programming II 18

    #include #include

    using namespace std;

    double test ( double a, double b = 7){ return a - b;}

    int main ()

    { cout

  • 8/14/2019 -C++-Lecture01Introduction12

    19/32

    Computer Programming II 19

    Records (Record s ( structstruct s)s)Struct is a set of diverse types of data that grouped together under aunique declaration.

    The components of a struct are called the members of the struct .

    The definition of struct in C++:struct student

    {string firstName;

    string lastName;

    char courseGrade;

    int testScore;

    int programmingScore;

    double GPA;

    };

    A semicolon after the right brace isessential to end the struct statement.

    Variable declaration:student x;

    student y;

    The above two statements declare two struct variables, x and y , of the type student . Thememory allocated is large enough to storefirstName , lastName , courseGrade ,

    testScore , programmingScore , and GPA .

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    20/32

    Computer Programming II 20

    AccessingAcces sing structstruct MembersMembers

    x.firstName = John;

    x.lastName = Brown;

    x.courseGrade = A;

    x.testScore = 95;

    x.programmingScore = 98;

    x.GPA = 3.9;

    To access a struct member (component), you use the struct variable name together with themember name; these namesare separated by a dot (period).

    x.firstName is just like any other variable. x.firstName is a variable of the type string, x. courseGrade is a variable of the type char ,x.testScore is a int variable, and so on. As a result, you can do justabout anything with struct members that you normally do withvariables. You can, for example, use them in assignmentstatements or input/output (where permitted) statements.

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    21/32

  • 8/14/2019 -C++-Lecture01Introduction12

    22/32

  • 8/14/2019 -C++-Lecture01Introduction12

    23/32

    Computer Programming II 23

    Arrays inArrays in structstruct ssArray is a set of elements of the same type. Thus, array has two things associatedwith it: the values (that is, elements), and the length. Because the values and thelength are both related to the array, we can define a struct containing both items.

    const arraySize = 1000;

    struct listType

    {

    int listElem[arraySize]; //array containing the list

    int listLength; //length of the list

    };

    The following statement declares intList to be a struct variable of the type listType .

    listType intList;

    The variable intList has two members: listElem , an array of 1000 components of thetype int ; and listLength , of the type int . Moreover, intList.listElem accessesthe member listElem and intList.listLength accesses the member listLength .

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    24/32

    Computer Programming II 24

    structstruct s in Arrayss in A rrays

    Suppose a company has 50 full-time employees. We need to print their monthly paychecksand keep track of how much money has been paid to each employee in the year-to-date.First, lets define an employees record.

    struct employeeType

    {

    string firstName;

    string lastName; int personID;

    string deptID;

    double yearlySalary;

    double monthlySalary;

    double yearToDatePaid;

    double monthlyBonus;

    };

    Each employee has the following members(components): first name, last name, personal ID,department ID, yearly salary, monthly salary, year-to-date paid, and monthly bonus.

    Because we have 50 employees, and the datatype of each employee is the same, we can use anarray of 50 components to process the employeesdata.

    employeeType employees[50];The above statement declares an arrayemployees of 50 components of the typeemployeeType . Every element of employees isa struct .

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    25/32

  • 8/14/2019 -C++-Lecture01Introduction12

    26/32

    Computer Programming II 26

    Let us reorganize this struct as follows:

    struct nameType

    {string first;string middle;string last;

    };

    struct addressType{

    string address1;string address2;string city;string state;string zip;

    };

    struct dateType

    { int month; int day; int year;};

    struct contactType{

    string phone;string cellphone;string fax;string pager;string email;

    };

    We have separated the employees name, address, and contact type intosubcategories. Furthermore, we have defined a struct dateType.

    structstruct s within as within a structstruct

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    27/32

    Computer Programming II 27

    Let us rebuild the employees record as follows:

    struct employeeType{

    nameType name;string empID;addressType address;dateType hireDate;dateType quitDate;contactType contact;string deptID;

    double salary;};

    The information in this employees struct is easier tomanage than the previous one. Some of this struct

    can be reused to build another struct . For example,suppose that you want to define a customers record.Every customer has a first name, last name, andmiddle name, as well as an address and a way to becontacted. You can, therefore, quickly put together acustomers record by using the struct s nameType ,addressType , contactType , and the membersspecific to the customer.

    Consider the following statement:

    employeeType newEmployee;

    This statement declares newEmployee to be a struct variable of the type employeeType .

    The statement:

    newEmployee.salary = 45678.00;

    sets the salary of newEmployee to 45678.00

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    28/32

    Computer Programming II 28

    The statements:

    newEmployee.name.first = Mary;

    newEmployee.name.middle = Beth;

    newEmployee.name.last = Simmons;

    set the first , middle , and last name of newEmployee to Mary , Beth , andSimmons , respectively. Note that newEmployee has a member called name . Weaccess this member via newEmployee.name . Note also that newEmployee.name is astruct and has three members. We apply the member access criteria to access themember first of the struct newEmployee.name . So newEmployee.name.first

    is the member where we store the first name.The statement:

    cin >> newEmployee.name.first;

    reads and stores a string into newEmployee.name.first .

    The statement:

    newEmployee.salary = newEmployee.salary * 1.05;

    updates the salary of newEmployee .

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    29/32

    Computer Programming II 29

    ClassesClasses

    A class is a logical method to organize data and functions in the same structure. Theyare declared using keyword class. Whose functionality is similar to keyword struct,

    class Person{

    public:

    void setAge(unsigned n);

    int getAge();

    private:unsigned age;

    };

    The class declaration

    The C++ keyword private can be used tohide class data members and methods,and the keyword public can be used toexpose class data members andmethods.

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    30/32

    Computer Programming II 30

    Defining Class MethodsClass methods/functions may be implemented in two ways:

    A methods may be declared inside the class declaration but implemented outside theclass declaration.

    A method may be declared and implemented inside the class declaration.

    class Person

    {

    public:

    void setAge(unsigned n);int getAge();

    private:

    unsigned age;

    };

    void Person::setAge(unsigned n){ age = n; }

    int Person::getAge()

    { return age; }

    class Person

    {

    public:

    void setAge(unsigned n)

    { age = n; }

    unsigned getAge() const

    { return age; }

    private:

    unsigned age;

    };

    Scope resolution operator ::

    http://fit.mmu.edu.my/
  • 8/14/2019 -C++-Lecture01Introduction12

    31/32

    Computer Programming II 31

    Using Classes in a Program

    Classes are created to be used ultimately in Programs. Before a class can be used in a program,its declaration must be visible to any functions that are meant to use the class. Below is thecomplete program that uses the Person class.

    #include

    using namespace std;

    class Person

    {

    public:void setAge(unsigned n)

    { age = n; }

    int getAge()

    { return age; }

    private:unsigned age;

    };

    int main(){Person p; //create a single PersonPerson stooges[3]; //create an array of Persons

    p.setAge(12); // set ps name// set the stooges agesstooges[0].setAge(45);stooges[1].setAge(46);stooges[2].setAge(44);// print four ages

    cout

  • 8/14/2019 -C++-Lecture01Introduction12

    32/32


Recommended