You are on page 1of 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 <iostream>
using namespace std; Output:
Enter five numbers.
int main() 2
{ int item[5];
item[5] int sum; int counter; 3
cout<<"Enter five numbers."<<endl; 5
sum = 0; 7
for(counter = 0; counter < 5; counter++) 9
The sum of the numbers is: 26
{
The numbers in reverse order are: 9
cin>>item[counter]; 7 5 3 2
sum = sum + item[counter]; Press any key to continue . . .
}
cout<<"The sum of the numbers is: "<<sum<<endl;
cout<<"The numbers in reverse order are: ";

for(counter = 4; counter >= 0; counter--)


cout<<item[counter]<<" ";
cout<<endl;
system("PAUSE");
return 0;
}

Computer Programming II 3
Review of Arrays: Two-Dimensional Arrays
Q: Program in which each element is multiplied by 10 and displayed.

#include <iostream>
#include <iomanip> Output:
using namespace std;
Display of multiplied elements
80 160 90 520
int main() 30 150 270 60
{ const int NUMROWS = 3; 140 250 20 100
const int NUMCOLS = 4; Press any key to continue . . .
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 4
References
Reference is simply another name for the original variable
int x = 5;
int& y = x; //ampersand sign (&) Read y is a reference to an int x
int z = y;
cout << “The value of x is “ << x << “.\n”;
cout << “The value of y is “ << y << “.\n”;
cout << “The value of z 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 <iostream>
#include <cstdlib>

using namespace std;


Function Heading
void SquareArea(void)
{
double Side;
cout << "\nEnter the side of the square: ";
cin >> Side;
cout << "\nSquare characteristics:";
Function Body
cout << "\nSide = " << Side;
cout << "\nArea = " << Side * Side << endl; Output:
} Enter the side of the square: 5

Square characteristics:
int main(void) Side = 5
{ Area = 25
SquareArea(); Function Call Press any key to continue . . .
system("PAUSE");
return 0;
}

Computer Programming II 6
Review of Functions
2. Function with return value and no parameters
#include <iostream>
#include <cstdlib>
using namespace std;

int GetMajor(void) Return Value but


{ no Parameters
int Choice;
cout << "\n1 - Business Administration";
Output:
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;
}

Computer Programming II 7
Review of Functions
3. Function with return value and parameters
#include <iostream>
using namespace std;

double TotPrice(double ItemPrice, double TaxRate)


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

int main() Output:


{
double ItemPrice, TaxRate; Enter the price of the item: 20
cout << "Enter the price of the item: "; Enter the tax rate: 5
cin >> ItemPrice;
cout << "Enter the tax rate: "; The final price is: 21
cin >> TaxRate;
cout << "\nThe final price is: " Press any key to continue . . .
<< TotPrice(ItemPrice, TaxRate);

cout << "\n\n";


system(“PAUSE”);
return 0;
}

Computer Programming II 8
#include <iostream>
#include <cstdlib>
using namespace std;
References in Functions
void swap(int &i, int &j); Pass by reference
int main()
{
int x = 6, y = 9;
cout << "Before the swap:\n";
cout << "X: " << x << endl;
Output:
cout << "Y: " << y << endl; Before the swap:
swap(x, y); X: 6
cout << "\nAfter the swap:\n"; Y: 9
cout << "X: " << x << endl;
cout << "Y: " << y << endl; After the swap:
system("PAUSE"); X: 9
return 0; 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 <iostream>
#include <cstdlib>
using namespace std;
References in Functions
void swap(int i, int j); Pass by value
int main()
{
int x = 6, y = 9;
cout << "Before the swap:\n";
cout << "X: " << x << endl;
Output:
cout << "Y: " << y << endl; Before the swap:
swap(x, y); X: 6
cout << "\nAfter the swap:\n"; Y: 9
cout << "X: " << x << endl;
cout << "Y: " << y << endl; After the swap:
system("PAUSE"); X: 6
return 0; 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
int main()
{
Inline void myFunction(int n)
{ int n = 2;
{
for (int i = 0; i < n; i++)
for (int i = 0; i < n; i++)
{
{
cout << i << “ “;
cout << i << “ “;
}
}
cout << “\n”;
cout << “\n”;
}
}
…..

int main() { int n = 5;


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

Computer Programming II 15
Function Overloading

 Function overloading allows


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

void myFunction(int a) {…}


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

Computer Programming II 16
#include <iostream> void swap (int &a, int &b)
#include <cstdlib> {
using namespace std; int temp = a;
a = b;
void swap (int &a, int &b); b = temp;
void swap (float &a, float &b); }
void swap (char &a, char &b); void swap (float &a, float &b)
{
int main() float temp = a;
{ a = b;
int i1 = 3, i2 = 5; b = temp;
float f1 = 3.14159f, f2 = 1.23f; }
char c1='A', c2='B'; void swap (char &a, char &b)
cout << "Integers before swap:" << endl; {
cout << i1 << ", " << i2 << endl; char temp = a;
swap(i1, i2); a = b;
cout << "Integers after swap:" << endl; b = temp;
cout << i1 << ", " << i2 << endl; }
cout << "Floating points before swap:" << endl;
cout << f1 << ", " << f2 << endl; Integers before swap:
swap(f1, f2); 3, 5
cout << "Floating points after swap:" << endl; Integers after swap:
cout << f1 << ", " << f2 << endl; 5, 3
cout << "Characters before swap:" << endl; Floating points before swap:
cout << c1 << ", " << c2 << endl; 3.14159, 1.23
swap(c1, c2); Floating points after swap:
cout << "characters after swap:" << endl; 1.23, 3.14159
cout << c1 << ", " << c2 << endl; Characters before swap:
system("PAUSE"); A, B
return 0; characters after swap:
} B, A
Press any key to continue . . .

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

#include <iostream>
#include <cstdlib>
Output:
using namespace std;

double test (double a, double b = 7)


{ 9
return a - b; 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;
The above two statements declare two struct
string lastName; variables, x and y, of the type student. The
char courseGrade; memory allocated is large enough to store
firstName, lastName, courseGrade,
int testScore;
testScore, programmingScore, and GPA.
int programmingScore;
double GPA; A semicolon after the right brace is
essential to end the struct statement.
};

Computer Programming II 19
Accessing struct Members
x.firstName = “John”;
To access a struct member
x.lastName = “Brown”;
(component), you use the struct
x.courseGrade = ‘A’;
variable name together with the
x.testScore = 95; member name; these names
x.programmingScore = 98; are separated by a dot (period).
x.GPA = 3.9;

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 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.

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 = y; is equivalent to the following
statements:

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.lastName << “ ”
<< x.courseGrade << “ ” << x.testScore << “ ”
<< x.programmingScore << “ ” << x.GPA << endl;
}

Computer Programming II 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 Each employee has the following members


(components): first name, last name, personal ID,
{
department ID, yearly salary, monthly salary, year-
string firstName; to-date paid, and monthly bonus.
string lastName;
int personID; Because we have 50 employees, and the data
string deptID; type of each employee is the same, we can use an
array of 50 components to process the employees’
double yearlySalary; data.
double monthlySalary; employeeType employees[50];
double yearToDatePaid; The above statement declares an array
double monthlyBonus; employees of 50 components of the type
employeeType. Every element of employees is
}; a struct.

Computer Programming II 24
struct employeeType
structs within a struct {
string firstname;
string middlename;
You have seen how the struct and array data
string lastname;
structures can be combined to organize information. string empID;
You also saw examples wherein a member of a struct string address1;
is an array, and the array type is a struct. Now, you will string address2;
learn about situations where it is beneficial to organize string city;
data in a struct by using another struct. string state;
string zip;
int hiremonth;
Let us consider the following employee record: int hireday;
int hireyear;
int quitmonth;
int quitday;
As you can see, a lot of information is packed into one int quityear;
struct. This struct has 22 members. Some members of string phone;
this struct will be accessed more frequently than string cellphone;
others, and some members are more closely related string fax;
than others. Moreover, some members will have the string pager;
string email;
same underlying structure. For example, the hire date
string deptID;
and the quit date are of the date type int. double salary;
};

Computer Programming II 25
structs within a struct
Let us reorganize this struct as follows:

struct nameType struct dateType


{ {
string first; int month;
string middle; int day;
string last; int year;
}; };

struct addressType struct contactType


{ {
string address1; string phone;
string address2; string cellphone;
string city; string fax;
string state; string pager;
string zip; 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
The information in this employee’s struct is easier to
{
manage than the previous one. Some of this struct
nameType name;
can be reused to build another struct. For example,
string empID;
suppose that you want to define a customer’s record.
addressType address;
Every customer has a first name, last name, and
dateType hireDate;
middle name, as well as an address and a way to be
dateType quitDate;
contactType contact;
contacted. You can, therefore, quickly put together a
string deptID;
customer’s record by using the structs nameType,
double salary;
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 The C++ keyword private can be used to


{ hide class data members and methods,
public: and the keyword public can be used to
void setAge(unsigned n); expose class data members and
int getAge();
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
class Person
{
{
public:
public:
void setAge(unsigned n);
void setAge(unsigned n)
int getAge();
{ age = n; }
private:
unsigned getAge() const
unsigned age;
{ return age; }
};
private:
void Person::setAge(unsigned n)
unsigned age;
{ age = n; }
};
int Person::getAge()
{ return age; } Scope resolution operator ::

Computer Programming II 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 <iostream> int main()


using namespace std; {
Person p; //create a single Person
class Person
Person stooges[3]; //create an array of Persons
{ p.setAge(12); // set p’s name
public: // set the stooges’ ages
stooges[0].setAge(45);
void setAge(unsigned n) stooges[1].setAge(46);
{ age = n; } stooges[2].setAge(44);
// print four ages
int getAge()
cout << p.getAge() << ‘\n’;
{ return age; } for(int i = 0; i < 3; i++)
private: cout << stooges[i].getAge() << ‘\n’;
return 0;
unsigned age;
}
};

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

You might also like