Computer Science, City University of
Semester B 2021-22
CS2310 Computer Programming
Copyright By PowCoder代写 加微信 powcoder
LT7: Function
What is function?
A collection of statements that perform a specific task.
Functions are used to break a problem down into manageable pieces
KISS principle: “Keep it simple, Stupid!”
Break the problem down into small functions, each does only one simple task, and does it correctly
A function can be invoked multiple times. No need to repeat the same code in multiple parts of the program.
Structured programming guidelines
Flow of control in a program should be as simple as possible
Construction of program should embody a top-down design
Decompose a problem into small problems repeatedly until they are simple enough to be coded easily
From another perspective, each problem can be viewed from different levels of abstraction (or details)
Top-down approach of problem solving is well exercised by human beings
Function in C++
The C++ standard library provides a rich collection of functions
Mathematical calculations (#include
String manipulations (#include
Input/output (#include
Some functions are defined in multiple library in some platform, e.g. function sqrt is defined in both cmath and iostream in VS
How to use function written by others?
#include
using namespace std;
void main()
float area,side;
cout << "Enter the area of a square:";
cin >> area;
side=sqrt(area);
cout << "The square has perimeter: “ << 4*side;
Tell compiler that you are going to use functions defined in iostream package
Pass area to the function sqrt which will return the square root of area
Function invocation
During program execution, when a function name followed by parentheses is encountered, the function is invoked and the program control is passed to that function; when the function ends, program control is returned to the statement immediately after the function call in the original function
Write your own function
(User defined functions)
Define a function printHello which accepts an integer n as input
The function should print "Hello" n times, where n is an integer
Function Components
void printHello (int n){
for (i=0; i
return f1;
return f2;
getInput int n1,
double n2 char char getInput(int n1,double n2){
………………………..
Examples: Function w/o return value
Function Parameter return value Examples:
printHello nil nil void printHello(){
cout << "Hello\n";
printHellos int n nil void printHello(int n){
for (i=0;i
cout << findMax(4, 3); //print x (4)
When y>x, the expression findMax(x, y) should evaluate to a value of y
cout << findMax(3, 4); //print y (4)
Function definition
int findMax (int n1, int n2) {
if (n1 > n2)
return n1;
return n2;
The return type of the variable is int
When there are more than one arguments, they are separated by a comma.
The type of each variable should be specified individually.
int findMax (int a, b);
Calling findMax()
max=findMax(x, y);
The value of this expression is 4. Assign 4 to max
The variable max will hold the value of x when x>y.
Otherwise, max will hold the value of y.
Flow of control
int findMax (int n1, int n2) {
if (n1>n2)
return n1;
return n2;
void main(){
max=findMax(x, y);
When findMax() is called,
the value of x(3) is copied to the variable n1
the value of y(4) is copied to the variable n2
Finding the max of 3 numbers, i, j, k
int i,j,k;
cin >> I >> j >> k;
//find the max of i, j, k
___ = findMax(___, ___);
___ = findMax(___, ___);
cout << "max is “ << max; int i,j,k; cin >> i >> j >>k;
//find the max of i, j, k
max = findMax(i, j); /*m stores 3*/
max = findMax(max, k); /*m stores 2*/
cout <<"max is " << max;
What is the output of the following program?
void f(int y, int x){
cout << "x=" << x << endl;
cout << "y=" << y << endl;
void main(){
int x=3, y=4;
Parameter Passing: Default Parameters
We can also provide some default values for certain parameters
void f(int a, int b, int c = 0){
Default parameter with a default value
Parameter Passing: Default Parameters
If no value is passed to the default parameter, the complier will use its default value in the function call
void f(int a, int b, int c = 0){
void main(){
f(3, 4)// c = 0 in the function call
f(3, 4, 5)// c= 5 in the function call
Parameter Passing: Default Parameters
All the default parameters must locate at the right-hand side of normal parameters
Invalid examples:
void f(int a, int b = 0, int c, int d = 0){
// invalid definition, the default parameter b
// locates at left-hand side of c
void f(int a, int b, int c = 0, int d = 0){
// valid definition
Parameters Passing: arrays
When passing an array to a function, we only need to specify the array name
The following example is invalid
void f(int x[20]){
void main(){
int y[20];
f(y[0]); //invalid, type mismatch
Parameters Passing: arrays
void f(int a[3]){
cout << a[0] <
if (a[i][k] < a[i][k - 1]) {
tmp = a[i][k]; // swap neighbors
a[i][k] = a[i][k - 1];
a[i][k - 1] = tmp;
void main()
int a[3][3] = { 0 };
for (int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
cin >> a[i][j];
sort2D(a);
Defining and calling functions
void main(){
A function should be defined before use.
void main(){
f(); //f() is undefined
Syntax Error
Function Prototype
C++ language allows us to define the function prototype and then call the function
Function prototype
Specifies the function name, input and output type.
The following statement specifies that f is a function, there is no input and no return value
void f(void);
The function can be implemented later
Function Prototype
void f (void);
void main(){
//define f() here
int findMax (int, int);
void main(){
int x=findMax (3,4);
int findMax (int n1, int n2){
//define findMax() here
Function Prototype
The prototype
int findMax (int, int);
specifies that findMax is a function name.
The return type is int.
There are two arguments and their types are int.
Another way to write the prototype is:
int findMax (int n1, int n2);
However, the variable names are optional.
Function Prototype
In C++, function prototypes and definitions can be stored separately
Header file (.h):
With extension .h, .e.g stdio.h, string.h
Contain function prototypes only
To be included in the program that will call the function
Implementation file (.cpp):
Contain function implementation (definition)
The name of .h and .cpp files should be the same
Function Prototype
#include “mylib.h”
void main(){
int x,y=2,z=3;
x=calMin(y,z);
int calMin(int,int);
int calMin(int a,int b){
Function prototype (cont’d)
void is used if a function takes no arguments
Prototypes allow the compiler to check the code more thoroughly
Values passed to a function are coerced where necessary, e.g., printDouble (4) where the integer 4 will be promoted as a double data type 4
#include
using namespace std;
void printDouble(double d){
cout <
A recurrence relation: (induction)
n! = n*(n-1)! for n>0
3! = 3 * 2!
= 3 * 2 * 1!
= 3 * 2 * 1 * 0!
= 3 * 2 * 1 * 1
Iterative vs. Recursive
int factorial(int n)
int i, fact = 1;
for (i = 1; i <= n; i++) fact = i * fact; return fact; int factorial(int n) if (n==0) return 1; return n*factorial(n-1); Checkpoints There is no infinite recursion (check exist condition) Each stopping case performs the correct action for that case For each of cases that involve recursion, if all recursive calls perform their actions correctly, then the entire case performs correctly. Static variable in function (optional) Question: In C++, all the variable inside a function call will be deleted by the compiler after the execution of the function block. How to count how many function calls when running a recursion? The keyword static will keep the variable after it exists even after the function call int factorial(int n){ static int count; Static variable which will not disappear after the execution of the current function call. Hence, it can be used to count the number of function calls during a recursion Compiler will assign 0 to static variable if no initialization. Functions help programmer write a more simple program and make the problem more easy to solve return_type Function_name(paramaters); Function prototype must declared before it can be used. Header files can be used to store function prototypes but not the body. Parameters can be passed with call by value or call by pointer. Instruction Instruction Instruction Function (…..){ Instruction Instruction Instruction Instruction Instruction Instruction Function (…..){ Instruction Instruction Instruction /docProps/thumbnail.jpeg 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com