CSE141
Introduction
to Computer
Programming
Functions
Presented by: Dr. 1
Course Outline
1. An Overview of Computers and Programming Languages
2. Basic Elements of C++
3. Input/Output
4. Control Structures I (Selection)
5. Control Structures II (Repetition)
6. User-Defined Functions
7. User-Defined Simple Data Types, Namespaces, and String
Type
8. Arrays and Strings
9. Structures
10.Recursion*
*Lecture slides are inspired by Prof. Mahmoud Khalil’s Lectures* 2
GENERAL NOTE
Hidden Slides are Extra
Knowledge
Not Included in Exams
Lecture Outline
◦ User-defined functions
◦ Random Numbers Generation
◦ Enum
◦ Identifier Scope
◦ Inline Functions
◦ Template Functions
4
Recap: Guess the output
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double number, squareRoot;
number = 25.0;
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
5
Recap: Guess the output
#include <iostream>
#include <cmath>
using namespace std;
Functions
int main()
{
double number, squareRoot;
number = 25.0;
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
6
C++ Functions
A function is a block of code which only runs
when it is called.
Functions are used to perform certain actions,
and they are important for reusing code:
◦ Define the code once, and use it many times.
7
C++ Functions
◦Modularize a program
◦Software reusability
◦Call function multiple times
8
Program Components in C++
Modules: functions and classes
Programs use new and “prepackaged” modules
◦ New: programmer-defined functions, classes
◦ Prepackaged: from the standard library
Functions invoked by function call
◦ Function name and information (arguments) it needs
Function definitions
◦ Only written once
9
Divide and Conquer
Construct a program from smaller pieces or
components.
Each piece more manageable than the original
program.
10
Function Types
Standard Library Functions: Predefined in C++
User-defined Function: Created by developer
11
C++ Function Declaration
returnType functionName (parameter1,
Data Comma
parameter2,...) separat
type of
ed
{ result Data
returned type
// function body (use needed
void if for
} nothing each
returned argume
) nt
12
Example 1
void Welcome()
{
cout << "Hello World";
}
13
Calling a Function
Boss to worker
#include <iostream> analogy
using namespace std; Work
er
void Welcome() A boss (the calling
{ function or caller) asks
cout << "Hello World";
} a worker (the called
function) to perform a
int main() Bos task and return (i.e.,
{ s report back) the
Welcome();
return 0; results when the task
} is done.
14
Calling a Function
◦Parentheses an operator used to
call function
◦ Pass argument
◦ Function gets its own copy of arguments
◦After finished, passes back result
15
Example 2
int add(int a, int b)
{
return (a + b);
}
16
Example 2
#include <iostream>
using namespace std;
int add(int a, int b) Returns data,
{
return (a + b);
and control goes
} to function’s
int main() caller
{
int res = add(2, 3);
cout << res << endl;
return 0;
}
17
Return
Returns data, and control goes to function’s
caller
◦ If no data to return, use return;
Function ends when reaches right brace
◦ Control goes to caller
18
C++ Function Prototype
◦ In C++, the code of function declaration should be
before the function call.
◦ However, if we want to define a function after the
function call, we need to use the function prototype.
◦ Tells compiler argument type and return type of
function.
◦ Only needed if function definition after function call.
◦ Prototype must match function definition.
19
Function Signature
Function prototype
double maximum( double, double, double );
Function signature
Definition
double maximum( double x, double y, double z )
{
…
}
20
#include <iostream>
using namespace std;
int add(int, int);
int main()
{
int res = add(2, 3);
cout << res << endl;
return 0;
}
int add(int a, int b)
{
return (a + b);
}
21
C++ Function Default Arguments
If we call the function without an
argument, it uses the default value.
If not enough parameters, rightmost go to
their defaults
22
#include <iostream>
using namespace std;
int add(int a = 7, int b = 8)
{
return (a + b);
}
int main()
{
int res = add();
cout << res << endl;
res = add(2);
cout << res << endl;
res = add(2, 3);
cout << res << endl;
return 0;
}
23
#include <iostream>
using namespace std;
// function prototype that specifies default arguments
int boxVolume( int length = 1, int width = 1, int height = 1 );
int main()
{
// no arguments--use default values for all dimensions
cout << "The default box volume is: " << boxVolume();
// specify length; default width and height
cout << "\n\nThe volume of a box with length 10,\n" << "width 1 and height 1 is: " << boxVolume(10);
// specify length and width; default height
cout << "\n\nThe volume of a box with length 10,\n“ << "width 5 and height 1 is: " << boxVolume(10, 5);
// specify all arguments
cout << "\n\nThe volume of a box with length 10,\n“ << "width 5 and height 2 is: " << boxVolume(10, 5, 2) << endl;
return 0; // indicates successful termination
} // end main
// function boxVolume calculates the volume of a box
int boxVolume(int length, int width, int height)
{
return length * width * height;
} // end function boxVolume
24
25
Local Variables & Parameters
Local variables
◦ Known only in the function in which they are defined.
◦ All variables declared in function definitions are local
variables.
Parameters
◦ Local variables passed to function when called.
◦ Provide outside information.
26
#include <iostream>
using namespace std;
int add(int a = 7, int b = 8)
{
int res = a + b;
res is a
return res;
} different
variable than
int main()
the one in main
{
int res = add();
cout << res << endl;
res = add(2);
cout << res << endl;
res = add(2, 3);
cout << res << endl;
return 0;
}
27
Remember
Functions cannot be defined inside other
functions
28
Find the output
on your own,
then compare the
result with the
given answer
29
#include <iostream>
using namespace std;
int square(int); // function prototype
int main()
{
for (int x = 1; x <= 10; x++)
{
cout << square(x) << " "; // function call
}
cout << endl;
return 0;
}
// square function definition returns square of an integer
int square(int y) // y is a copy of argument to function
{
return y * y; // returns square of y as an int
} // end function square
30
#include <iostream>
using namespace std;
int square(int); // function prototype
int main()
{
for (int x = 1; x <= 10; x++)
{
cout << square(x) << " "; // function call
}
cout << endl;
return 0;
}
// square function definition returns square of an integer
int square(int y) // y is a copy of argument to function
{
return y * y; // returns square of y as an int
} // end function square
31
#include <iostream>
using namespace std;
double maximum( double, double, double ); // function
prototype
int main()
{
double number1;
double number2;
double number3;
cout << "Enter three floating-point numbers: ";
cin >> number1 >> number2 >> number3;
// number1, number2 and number3 are arguments to
// the maximum function call
cout << "Maximum is: "
<< maximum(number1, number2, number3) << endl;
return 0;
}
32
// function maximum definition x, y and z are parameters
double maximum(double x, double y, double z)
{
double max = x; // assume x is largest
if (y > max) // if y is larger,
max = y; // assign y to max
if (z > max) // if z is larger,
max = z; // assign z to max
return max; // max is largest value
} // end function maximum
33
34
Argument Coercion
The Argument Coercion is one technique by
which the compiler can implicitly convert the
arguments from one type to another type.
35
Argument Coercion
Force arguments to be of proper type
cout << sqrt(4)
◦ Converting int (4) to double (4.0)
Conversion rules
◦ Arguments usually converted automatically
◦ Changing from double to int can truncate data
◦ 3.4 to 3
◦ Mixed type goes to highest type (promotion)
36
Scope Rules
44
45
Scope Rules
Scope?
◦ Portion of program where identifier can be used
File scope
◦ Defined outside a function, known in all functions
◦ Global variables, function definitions and prototypes
Function scope
◦ Can only be referenced inside defining function
Block scope
◦ Begins at declaration, ends at right brace }
◦ Can only be referenced in this range
◦ Local variables, function parameters
46
Example: Guess the Output
static next time
47
48
49
Practice
Write a program that uses a function to read the employee salary and calculate
the taxes according to the following rules.
52
53