C - Lecture01Introduction12
C - Lecture01Introduction12
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: ";
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”;
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>
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;
Computer Programming II 7
Review of Functions
3. Function with return value and parameters
#include <iostream>
using namespace std;
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:
Pass-by-reference
int addition (int& a, int& b)
...
Z = addition ( x, y)
Pass-by-pointer
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
Computer Programming II 12
Inline Functions
• To help reduce function-call overhead.
Computer Programming II 13
To define an inline function, insert the
keyword inline before the function
definition
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”;
}
}
…..
Computer Programming II 15
Function Overloading
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;
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.
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;
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.
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.
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:
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.
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,
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.
Computer Programming II 31
Next Lecture
Computer Programming II 32