-c++-lecture01introduction12

  • Uploaded by: booksofpavan
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View -c++-lecture01introduction12 as PDF for free.

More details

  • Words: 3,207
  • Pages: 32
Introduction Part I Lecture 1 Computer Programming II

1

Objectives The following topics will be discussed in this Lecture:          

One-Dimensional Array Two-Dimensional Array References Functions References in Functions Inline Functions Function Overloading Default Arguments Structures (Records) Classes Computer Programming II

2

Review of Arrays: One-Dimensional Arrays Q: Program to read five numbers, find their sum, and print the numbers in reverse order. #include using namespace std; int main() { int item[5]; item[5] int sum; int counter; cout<<"Enter five numbers."<<endl; sum = 0; for(counter = 0; counter < 5; counter++) { cin>>item[counter]; sum = sum + item[counter]; } cout<<"The sum of the numbers is: "<<sum<<endl; cout<<"The numbers in reverse order are: ";

Output: Enter five numbers. 2 3 5 7 9 The sum of the numbers is: 26 The numbers in reverse order are: 9 7 5 3 2 Press any key to continue . . .

for(counter = 4; counter >= 0; counter--) cout<
Computer Programming II

3

Review of Arrays: Two-Dimensional Arrays Q: Program in which each element is multiplied by 10 and displayed. #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 << "Display of multiplied elements"; for(i = 0; i < NUMROWS; i++) { cout << endl; for(j = 0; j < NUMCOLS; j++) { val[i][j] = val[i][j] * 10; cout << setw(5) << val[i][j]; } } cout << endl; system("PAUSE"); return 0; }

Computer Programming II

Output: Display of multiplied elements 80 160 90 520 30 150 270 60 140 250 20 100 Press any key to continue . . .

4

References Reference is simply another name for the original variable int x = 5; int& y = x; //ampersand int z = y; cout << “The value of x cout << “The value of y cout << “The value of z

sign (&) Read y is a reference to an int x is “ << x << “.\n”; is “ << y << “.\n”; is “ << z << “.\n”;

This can be seen in the following diagram:

output:

The value of x is 5 The value of y is 5 The value of z is 5 y contain the address of x

Computer Programming II

5

Review of Functions

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

1. Function with no return value and no parameters #include #include using namespace std;

Function Heading

void SquareArea(void) { double Side; cout << "\nEnter the side of the square: "; cin >> Side; cout << "\nSquare characteristics:"; cout << "\nSide = " << Side; cout << "\nArea = " << Side * Side << endl;

Function Body Output: Enter the side of the square: 5

} int main(void) { SquareArea(); system("PAUSE"); return 0; }

Function Call

Computer Programming II

Square characteristics: Side = 5 Area = 25 Press any key to continue . . .

6

Review of Functions 2. Function with return value and no parameters #include #include using namespace std; Return Value but int GetMajor(void) no Parameters { int Choice; cout << "\n1 - Business Administration"; cout << "\n2 - History"; Welcome to the student cout << "\n3 - Geography"; orientation program. cout << "\n4 - Education"; Select your desired major: cout << "\n5 - Computer Sciences"; 1 - Business Administration cout << "\nYour Choice: "; 2 - History cin >> Choice; 3 - Geography return Choice; 4 - Education } 5 - Computer Sciences int main(void) Your Choice: 1 { You select 1 int Major; Press any key to continue . . . cout << "Welcome to the student orientation program."; cout << endl; cout << "Select your desired major:"; Call GetMajor and when Major = GetMajor(); done return the results cout << "You select " << Major; to the variable Major cout << "\n"; system("PAUSE"); return 0; }

Output:

Computer Programming II

7

Review of Functions 3. Function with return value and parameters #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 << "Enter the price of the item: "; cin >> ItemPrice; cout << "Enter the tax rate: "; cin >> TaxRate; cout << "\nThe final price is: " << TotPrice(ItemPrice, TaxRate);

Output: Enter the price of the item: 20 Enter the tax rate: 5 The final price is: 21 Press any key to continue . . .

cout << "\n\n"; system(“PAUSE”); return 0; }

Computer Programming II

8

#include #include using namespace std; void swap(int &i, int &j); int main() { int x = 6, y = 9; cout << "Before the swap:\n"; cout << "X: " << x << endl; cout << "Y: " << y << endl; swap(x, y); cout << "\nAfter the swap:\n"; cout << "X: " << x << endl; cout << "Y: " << y << endl; system("PAUSE"); return 0; }

References in Functions Pass by reference Output: Before the swap: X: 6 Y: 9 After the swap: X: 9 Y: 6 Press any key to continue . . .

void swap(int &i, int &j) { int temp = i; i = j; j = temp; }

Computer Programming II

9

#include #include using namespace std; void swap(int i, int j); int main() { int x = 6, y = 9; cout << "Before the swap:\n"; cout << "X: " << x << endl; cout << "Y: " << y << endl; swap(x, y); cout << "\nAfter the swap:\n"; cout << "X: " << x << endl; cout << "Y: " << y << endl; system("PAUSE"); return 0; }

References in Functions Pass by value Output: Before the swap: X: 6 Y: 9 After the swap: X: 6 Y: 9 Press any key to continue . . .

void swap(int i, int j) { int temp = i; i = j; j = temp; }

Computer Programming II

10

Pass-By … function int x = 5; y=3, z; 

Pass-by-value: int addition (int a, int b) ... Z = addition ( x, y)



Pass-by-reference int addition (int& a, int& b) ... Z = addition ( x, y)



Pass-by-pointer int addition (int* a, int* b) ... Z = addition ( x, y)

Computer Programming II

11

Function calls • When a function call is encountered, the program “jumps” to the address of the function and then “jumps” back when the function has completed • Each time the program “jumps” to execute a function, there is associated overhead: • “Loading” the function • Terminating the function call

Computer Programming II

12

Inline Functions • To help reduce function-call overhead. • “Advises” the compiler to generate a copy of the function’s code in place to avoid a function call. • Should be used only with small, frequently used functions. • Tradeoff: multiple copies of the function code are inserted in the program. With inline functions, the compiler replaces each instance of the function call with the corresponding code

Computer Programming II

13

To define an inline function, insert the keyword inline before the function definition inline double square (double x) { return x * x; }

Computer Programming II

14

Inline Functions Inline void myFunction(int n) { for (int i = 0; i < n; i++) { cout << i << “ “; } cout << “\n”; }

int main() { { int n = 2; for (int i = 0; i < n; i++) { cout << i << “ “; } cout << “\n”; } …..

int main() { … myFunction(2); … myFunction(5); … }

Computer Programming II

{

int n = 5; for (int i = 0; i < n; i++) { cout << i << “ “; } cout << “\n”;

} }

15

Function Overloading

Function overloading allows functions in C++ to share the same name.  Different types of arguments.  Different number of arguments. 

void void void void

myFunction(int a) {…} myFunction(char a) {…} myFunction(int x) {…} // Not permitted myFunction(int x, int y) {…}

Computer Programming II

16

#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 << "Integers before swap:" << endl; cout << i1 << ", " << i2 << endl; swap(i1, i2); cout << "Integers after swap:" << endl; cout << i1 << ", " << i2 << endl; cout << "Floating points before swap:" << endl; cout << f1 << ", " << f2 << endl; swap(f1, f2); cout << "Floating points after swap:" << endl; cout << f1 << ", " << f2 << endl; cout << "Characters before swap:" << endl; cout << c1 << ", " << c2 << endl; swap(c1, c2); cout << "characters after swap:" << endl; cout << c1 << ", " << c2 << endl; system("PAUSE"); return 0; }

Computer Programming II

void swap (int &a, int &b) { int temp = a; a = b; b = temp; } void swap (float &a, float &b) { float temp = a; a = b; b = temp; } void swap (char &a, char &b) { char temp = a; a = b; b = temp; } Integers before swap: 3, 5 Integers after swap: 5, 3 Floating points before swap: 3.14159, 1.23 Floating points after swap: 1.23, 3.14159 Characters before swap: A, B characters after swap: B, A Press any key to continue . . .

17

Default Arguments The default value of the argument is used when the default argument is omitted in a function call.

#include #include

Output:

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

9 7 Press any key to continue . . .

int main () { cout << test (14, 5) << endl; cout << test (14) << endl; system("PAUSE"); return 0; }

Computer Programming II

18

Records (structs) Struct is a set of diverse types of data that grouped together under a unique declaration. The components of a struct are called the members of the struct.

The definition of struct in C++:

Variable declaration:

struct student

student x;

{

student y; string firstName; string lastName; char courseGrade; int testScore;

The above two statements declare two struct variables, x and y, of the type student. The memory allocated is large enough to store firstName, lastName, courseGrade, testScore, programmingScore, and GPA.

int programmingScore; double GPA; };

Computer Programming II

A semicolon after the right brace is essential to end the struct statement.

19

Accessing struct Members x.firstName = “John”; x.lastName = “Brown”; x.courseGrade = ‘A’; x.testScore = 95; x.programmingScore = 98;

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

x.GPA = 3.9;

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 just about anything with struct members that you normally do with variables. You can, for example, use them in assignment statements or input/output (where permitted) statements. x.firstName

Computer Programming II

20

Assignment We can assign the value of one struct variable to another struct variable of the same type by using an assignment statement. The statement x

= y;

copies the contents of y into x.

In fact, the assignment statement x statements:

= y;

is equivalent to the following

x.firstName = y.firstName; x.lastName = y.lastName; x.courseGrade = y.courseGrade; x.testScore = y.testScore; x.programmingScore = y.programmingScore; x.GPA = y.GPA;

Computer Programming II

21

The following function outputs the contents of a struct variable of the type student on the screen:

void printStudent(student x) { cout << x.firstName << x.courseGrade << x.programmingScore }

<< “ ” << x.lastName << “ ” << x.testScore << “ ” << x.GPA

Computer Programming II

<< “ ” << “ ” << endl;

22

Arrays in structs Array is a set of elements of the same type. Thus, array has two things associated with it: the values (that is, elements), and the length. Because the values and the length 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 the type int; and listLength, of the type int. Moreover, intList.listElem accesses the member listElem and intList.listLength accesses the member listLength.

Computer Programming II

23

structs in Arrays Suppose a company has 50 full-time employees. We need to print their monthly paychecks and keep track of how much money has been paid to each employee in the year-to-date. First, let’s define an employee’s record. struct employeeType { string firstName;

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

string lastName; int

personID;

double yearlySalary;

Because we have 50 employees, and the data type of each employee is the same, we can use an array of 50 components to process the employees’ data.

double monthlySalary;

employeeType employees[50];

double yearToDatePaid;

The above statement declares an array employees of 50 components of the type employeeType. Every element of employees is a struct.

string deptID;

double monthlyBonus; };

Computer Programming II

24

structs within a struct You have seen how the struct and array data structures can be combined to organize information. You also saw examples wherein a member of a struct is an array, and the array type is a struct. Now, you will learn about situations where it is beneficial to organize data in a struct by using another struct. Let us consider the following employee record: As you can see, a lot of information is packed into one struct. This struct has 22 members. Some members of this struct will be accessed more frequently than others, and some members are more closely related than others. Moreover, some members will have the same underlying structure. For example, the hire date and the quit date are of the date type int.

Computer Programming II

struct employeeType { string firstname; string middlename; string lastname; string empID; string address1; string address2; string city; string state; string zip; int hiremonth; int hireday; int hireyear; int quitmonth; int quitday; int quityear; string phone; string cellphone; string fax; string pager; string email; string deptID; double salary; };

25

structs within a struct Let us reorganize this struct as follows: struct nameType { string first; string middle; string last; };

struct dateType { int month; int day; int year; };

struct addressType { string address1; string address2; string city; string state; string zip; };

struct contactType { string phone; string cellphone; string fax; string pager; string email; };

We have separated the employee’s name, address, and contact type into subcategories. Furthermore, we have defined a struct dateType.

Computer Programming II

26

Let us rebuild the employee’s 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 employee’s struct is easier to manage than the previous one. Some of this struct can be reused to build another struct. For example, suppose that you want to define a customer’s record. Every customer has a first name, last name, and middle name, as well as an address and a way to be contacted. You can, therefore, quickly put together a customer’s record by using the structs nameType, addressType, contactType, and the members specific 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

Computer Programming II

27

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”, and “Simmons”, respectively. Note that newEmployee has a member called name. We access this member via newEmployee.name. Note also that newEmployee.name is a struct and has three members. We apply the member access criteria to access the member 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.

Computer Programming II

28

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

The class declaration class Person { public: void setAge(unsigned n); int getAge();

The C++ keyword private can be used to hide class data members and methods, and the keyword public can be used to expose class data members and methods.

private: unsigned age; };

Computer Programming II

29

Defining Class Methods Class methods/functions may be implemented in two ways:  A methods may be declared inside the class declaration but implemented outside the class declaration.  A method may be declared and implemented inside the class declaration. class Person { public: void setAge(unsigned n);

class Person { public: void setAge(unsigned n)

int getAge();

{

private:

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

Computer Programming II

}

unsigned getAge() const

unsigned age; };

age = n;

{

return age;

}

private: unsigned age; };

Scope resolution operator ::

30

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 the complete program that uses the Person class. #include using namespace std; class Person { void setAge(unsigned n) age = n;

}

return age;

private: unsigned age; };

//create an array of Persons // set p’s name

stooges[0].setAge(45); stooges[1].setAge(46); stooges[2].setAge(44); // print four ages

int getAge() {

//create a single Person

// set the stooges’ ages

public: {

int main() { Person p; Person stooges[3]; p.setAge(12);

}

cout << p.getAge() << ‘\n’; for(int i = 0; i < 3; i++) cout << stooges[i].getAge() << ‘\n’; return 0; }

Computer Programming II

31

Next Lecture In the next lecture, we will cover :  Basic concepts of pointers in C/C++, their declaration and use  Applications of pointer variables and pointer operators  Relationship between pointers and arrays  Pointer arithmetic  Dynamic Memory Allocation  Difference between static array and dynamic array

Computer Programming II

32

More Documents from "booksofpavan"