COMPUTER AND
PROGRAMMING
Dr. Abdelhady Mostafa
Assiut University – Dept. of Mech. Eng.
MET 111 - First semester 2022/2023
Lecture 6
Course contents
■ Lecture 1: Introduction
■ Lecture 2: C++ Hello world!
■ Lecture 3: Flow of control (Loops)
■ Lecture 4: Flow of control (Decisions)
■ Lecture 5: Structures
■ Lecture 6: Functions (Exam 1)
■ Lecture 7: Functions (cont.)
■ Lecture 8: Objects and classes
■ Lecture 9: Objects and classes (cont.)
■ Lecture 10: Arrays and strings
■ Lecture 11: Arrays and strings (cont.) (Exam 2)
■ Lecture 12: Advanced topics 2
Work year exam 1
■Thursday
■17/11/2022
■1:30 – 3:30 pm
■320 مدرج
3
Today’s menu
■ Simple Functions
■ Passing Arguments to Functions
■ Returning Values from Functions
■ Reference Arguments
4
Reasons to use functions
■ A function groups a number of program statements into a unit and
gives it a name.
■ This unit can then be invoked from other parts of the program.
■ The most important reason to use functions is to aid in the
conceptual organization of a program.
■ Another reason to use functions is to reduce program size.
5
Simple Functions
#include <iostream>
using namespace std;
void starline(); //function
declaration
// (prototype)
int main() // function definition
{ void starline() //function
starline(); // call to declarator
function {
cout << “Data type Range” << // function body
endl; for(int j=0; j<45; j++)
starline(); // call to cout << ‘*’;
function
cout <<“char -128 to 127” <<
cout << endl;
endl;
} 6
starline(); // call to
Simple Functions
■ Any function consists of three main components:
– function declaration
– calls to the function
– function definition
7
Function
syntax
8
Function components
9
Comparison with Library Functions
Example of Library functions ch = getche();
Where are the declaration and definition of library functions?
When we use a library function we don’t need to write the
declaration or definition.
But when we write our own functions, the declaration and
definition are part of our source file.
10
Eliminating the Declaration
#include <iostream>
using namespace std;
void starline() //function
declarator
{
// function body
for(int j=0; j<45; j++)
cout << ‘*’;
cout << endl; starline(); // call to function
}
cout <<“char -128 to 127” <<
int main() endl;
{ starline(); // call to function
starline(); // call to
return 0;
function
cout << “Data type Range” << }
11
Eliminating the Declaration
We can eliminate the function declaration and place the function
definition directly before the first call to the function.
This approach is simpler for short programs but it is less flexible.
To use this technique, the functions has to be arranged so that
each one appears before it is called by any other. Sometimes this
is impossible.
12
Today’s menu
■ Simple Functions
■ Passing Arguments to Functions
■ Returning Values from Functions
■ Reference Arguments
13
Passing Arguments to Functions
An argument is a piece of data (an int value, for example)
passed from a program to the function.
Arguments allow a function to operate with different values, or
even to do different things, depending on the requirements of
the program calling it.
We can pass to functions:
Constants
Variables
Structures
14
Passing constants
#include <iostream>
using namespace std;
void repchar(char, int);
int main()
{
repchar(‘-’, 43);
cout << “Data type Range” << void repchar(char ch, int n)
{
endl;
for(int j=0; j<n; j++)
repchar(‘=’, 23); cout << ch;
cout << endl;
cout << “char -128 to 127” << endl;
}
repchar(‘-’, 43);
15
Passing variables
#include <iostream>
using namespace std;
void repchar(char, int);
int main()
{
char chin;
int nin;
cout << “Enter a character: ”;
cin >> chin;
void repchar(char ch, int n)
cout <<“Enter number of times to
repeat:”; {
cin >> nin; for(int j=0; j<n; j++)
repchar(chin, nin); cout << ch;
return 0; cout << endl;
} }
16
Passing structures
#include <iostream>
using namespace std;
struct Distance
{
int feet;
float inches;
};
void engldisp (Distance);
int main() void engldisp (Distance dd)
{ {
Distance d1={10, 12.5}; cout << dd.feet
engldisp(d1); << "\'-" << dd.inches
return 0; << "\"";
} }
17
Names in the Declaration
■ To increase the clarity of your function declarations, you can insert
meaningful names in the declaration, along with the data types.
\\ declaration
void display_point(int,
int);
Both are exactly the
same to the compiler
\\ declaration
void display_point(int horiz, int
vert);
The advantage of the second approach is clarity for the programmer.
Note that the names in the declaration have no effect on the names
you use when calling the function.
18
Today’s menu
■ Simple Functions
■ Passing Arguments to Functions
■ Returning Values from Functions
■ Reference Arguments
19
Returning Values from Functions
■ When a function completes its execution, it can return a single
value to the calling program.
■ Usually this return value consists of an answer to the problem the
function has solved.
■ When a function returns a value, the data type of this value must
be specified.
■ When functions are not required to return any value, we use the
return type void (as in previous examples).
■ If you don’t use a return type in the declaration, the compiler will
assume that the function returns an int value.
20
Returning Values from Functions
#include <iostream>
using namespace std;
float lbstokg (float);
int main ()
{
float lbs, kgs;
cout << “\nEnter your weight in
pounds: ”;
cin >> lbs;
kgs = lbstokg(lbs); float lbstokg (float pounds)
cout << “Your weight in kilograms {
is ” float kilograms =
<< kgs << endl; 0.45*pounds;
return 0; return kilograms;
} }
21
Eliminating Unnecessary Variables
#include <iostream>
using namespace std;
float lbstokg (float);
float lbstokg (float pounds)
int main () {
{ return 0.45*pounds;
float lbs, kgs; }
cout << “\nEnter your weight in
pounds: ”; or, you can write
cin >> lbs;
kgs = lbstokg(lbs);
cout << “Your weight in kilograms
is ” float lbstokg (float pounds)
<< kgs << endl; {
return 0; return (0.45*pounds);
} }
22
Returning Values from Functions
■ While many arguments may be sent to a function, only one
argument may be returned from it.
■ This is a limitation when you need to return more information.
■ However, there are other approaches to returning multiple
variables from functions:
– One is to return a structure
– Another is to pass arguments by reference
23
Returning structure variables
#include <iostream> Distance addlength (Distance dd1, Distance dd2)
using namespace std; {
struct Distance Distance dd3;
{ dd3.centimeters = dd1.centimeters +
int meter; dd2.centimeters;
float centimeters; dd3.meter = 0;
}; if (dd3.centimeters >= 100)
Distance addlength (Distance, Distance); {
void disp (Distance); dd3.centimeters = dd3.centimeters - 100;
dd3.meter++;
int main ()
}
{
dd3.meter = dd3.meter + dd1.meter + dd2.meter;
Distance d1={10, 82}, d2={5, 53}, d3;
return dd3;
d3 = addlength(d1, d2);
}
cout << endl;
//
disp (d3); ============================================
cout << endl; ==
return 0; void disp (Distance dd)
} { 24
Today’s menu
■ Simple Functions
■ Passing Arguments to Functions
■ Returning Values from Functions
■ Reference Arguments
25
Reference Arguments
■ A reference provides an alias—a different name—for a variable.
■ One of the most important uses for references is in passing arguments to
functions.
■ We can pass arguments to functions by value (as in previous examples) or by
reference.
■ When arguments are passed by value, the called function copies the
argument’s value into it. Then, the function cannot access the original
variable in the calling program, only the copy it created.
■ Passing by value offers insurance that the function cannot harm the original
variable.
26
Reference Arguments
■ Passing arguments by reference uses a different mechanism. Instead of a
value being passed to the function, a reference to the original variable
(memory address), in the calling program, is passed.
■ In this case, the function can access the actual variables in the calling
program.
■ We can use that to return more than one value from the function to the
calling program.
27
Passing Simple Data Types by Reference
Example 1
■ Suppose we want to write a program that asks the user to enter a
number of type float. The program will separate this number into
an integer and a fractional part.
■ That is, if the user’s number is 12.456, the program should report
that the integer part is 12.0 and the fractional part is 0.456.
28
Passing Simple Data Types by Reference
Example 1
#include <iostream>
using namespace std;
int main() Declaration void intfrac (float n, long& intp, float&
{ fracp)
void intfrac (float, long&, float&); {
float number, fracpart; intp = static_cast<long>(n);
long intpart; fracp = n - intp;
do { }
cout << “\nEnter a real number: ”;
cin >> number;
intfrac (number, intpart, fracpart);
cout << “Integer part is ” <<
intpart Hint:
<< “, fraction part is ” << fracpart var2 = static_cast<int>(var1)
<< endl; - Cast the type of var1 into int and place the
} while( number != 0.0 ); result in var2
return 0; - No header file is required for static_cast
29
Passing by
reference in the
example
30
Remarks
■ Reference arguments are indicated by the ampersand (&) following the data type
long& intp
This means intp is a reference to the integer variable passed to it.
■ The function declaration echoes the usage of the ampersand (&) in the definition
void intfrac (float, long&,
float&);
■ The ampersand (&) is not used in the function call
intfrac (number, intpart,
fracpart);
31
Exercise
■ Repeat the previous example by using structure variable as the
function return.
32
Passing Simple Data Types by Reference
Example 2
■ Suppose you have pairs of numbers in your program and you
want to be sure that the smaller one always precedes the larger
one.
■ To do this you call a function, order(), which checks two numbers
passed to it by reference and swaps the originals if the first is
larger than the second.
33
Passing Simple Data Types by Reference
Example 2
#include <iostream>
using namespace std;
int main()
{
void order(int& numb1, int& numb2)
void order (int&, int&);
int n1=99, n2=11; {
int n3=22, n4=88; if(numb1 > numb2)
order(n1, n2); {
order(n3, n4); int temp;
cout << “n1=” << n1 << endl; temp = numb1;
cout << “n2=” << n2 << endl; numb1 = numb2;
cout << “n3=” << n3 << endl; numb2 = temp;
cout << “n4=” << n4 << endl; }
return 0; }
} 34
Exercise
■ Repeat the previous example by using structure variable as the
function return.
35
Passing Structures by Reference
■ You can pass structures by reference just as you can simple data types.
■ We will see an example that performs scale conversions on values of
structure type Distance. A scale conversion involves multiplying a
group of distances by a factor.
■ For example, if a distance is 6'–8'', and a scale factor is 0.5, the new
distance is 3'–4''
■ If a distance is 5’–30'', and a scale factor is 0.5. What would be the new
distance?
■ The new distance is 2’–65'' (recall that 1 meter = 100 centimeters).
36
Passing Structures by Reference
#include <iostream>
using namespace std;
void scale ( Distance& dd, float factor )
struct Distance
{ {
int meter;
float centimeters = ( dd.meter*100 + dd.centimeters
float centimeters;
) * factor;
};
dd.meter = static_cast<int>(centimeters / 100);
void scale ( Distance&, float );
dd.centimeters = centimeters - dd.meter * 100;
void disp ( Distance );
}
int main()
{
Distance d1 = { 12, 65 }; //
cout << "d1 = "; disp(d1); ================================================
scale(d1, 0.5); =====
cout << "nd1 = ";
void disp ( Distance dd )
disp(d1);
cout << endl; {
return 0;
} cout << dd.meter << "\’-"
<< dd.centimeters << "\”";
37
Wrap up
■ Functions provide a way to help organize programs, and to reduce program size
■ Functions consist of three main parts: function declarations (prototypes),
function calls, function definition
■ Arguments can be sent to functions by value (the function works with a copy of
argument) or by reference (the function works with the original argument).
■ Functions can return only one value.
■ Functions ordinarily return by value, but they can also return by reference.
■ Arguments and return values can be either simple data types or structures.
38
Next Lecture …
Functions (cont.)
39
Questions?
40