Lecture 5 - Functions - Part 1
Lecture 5 - Functions - Part 1
Functions (part 1)
Concordia University
• Loops in C++
• While
• Do/while
• For
• Stream manipulation functions.
void function1() {
Statement;
}
void function2() {
Statement;
}
Dr. Fadi Alzhouri 3
The Use of Functions
• A piece of program to complete a specific task that can be used
several times by being called.
• Avoiding repetition
• Functions' motivations?
• Divide and Conquer: Divide the problem into smaller pieces,
you conquer the complexity of the problem.
• Reusability: Can be used in more than one place in a program
or in different programs
Dr. Fadi Alzhouri 4
Functions types
I. Predefined Functions:
• C++ Standard Library (cout and cin)
Three
similar
loops
• C++ has many libraries which are predefined that you can
simply use them
• The math library has tens of math functions that you can call
• You need to include the header file <cmath>
• E.g. sqrt, ceil, etc.
Header file
• Parameter list
• Comma separated list of parameters
• Data type needed for each parameter
• If no parameters, use void or leave blank
• Return-value-type
• Data type of result returned (use void if nothing returned)
• return keyword
• 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 the caller
Function definition
Calling/invoking a Function
• Example:
int square(int);
• Function takes an int and returns an int
• Prototype appears before main()
21
Example: Min function
The second Function min takes 3 arguments (all int) and returns int value.
22
Example: Min function (cont.)
Algorithm 1
23
Example: Min function (cont.)
Algorithm 2
24
Default Arguments
X 10
X 10
y
X 5
y
X 5
y
33
Reference Variables
34
Practice
Choose the correct answer for the following questions. Be
sure to select all correct choices.
1- What is the correct prototype?
a) int square(x);
b) int square(int x);
c) int square(int);
d) int int square(int &x);
a) Hello Adam
Hello Adam
b) Hello Adam
Hello Tom
c) Hello Tom
Hello Tom
b) Error
a) 1020
b) 2020
c) 1010
b) 2010
a b operation
15 20 *
40 34 +
Etc.