Programming Fundamentals: Dr. Sheikh Faisal Rashid Department of Computer Science and Engineering UET Lahore
Programming Fundamentals: Dr. Sheikh Faisal Rashid Department of Computer Science and Engineering UET Lahore
FUNDAMENTALS
Dr. Sheikh Faisal Rashid
shfaisal@gmail.com,uet.edu.pk
Department of Computer Science and
Engineering UET Lahore
FUNCTIONS
Outline
• In this lesson, we will:
• Review mathematical functions
• Look at the use of functions in C++
• Describe function declarations
• Their relation to the domain and range
• Parameters and arguments
• Example: a fast sine function
• Side effects
• Functions with no return values
• The void keyword
• A second-last look at understanding int main()
Using functions
• In secondary school mathematics courses, you were
introduced to numerous functions:
sin x , cos x , etc.
• The trigonometric functions
• Possibly including hyperbolic functions and the xinverses of these
e , ln x , log 10 x
• The exponential and logarithmic functions
x
• The absolute value
x
• The square root
x , x
• The ceiling and floor functions
• The greatest common divisor and least common multiple functions
• The maximum or minimum of two arguments
gcd m , n , lcm m , n
max m , n , min m , n
Using functions
• All of these have some properties in common:
• Each function requires a fixed number of arguments that must be of
a certain type, either integers or real numbers
• Given the same arguments, the functions return the same value
return 0;
}
Using functions
• In each case, the argument is of type double
sin : R R
• This function:
• Has the identifier p
• Takes a variable parameter x that must be a floating-point number
• Returns a floating-point number
Function definitions
• The function int main() simply returned 0
• To evaluate def
p x 3x2 4 x 2
we must perform an arithmetic calculation
• These require:
• Five multiplications and two addition/subtractions
• One multiplication and two addition/subtractions (or just one?)
The greatest common divisor
• The greatest common divisor (gcd) is another function you saw
in secondary school
• E.g., gcd(42, 70) = 14
• It depends on two integer parameters and returns an integer
gcd : Z Z N
mn
lcm m , n
gcd m , n
Side effects
• In mathematics, the result of a function depends entirely
on the arguments
• Anything else a function does is called a side-effect
• The side-effect of the int main() function is to print “Hello world!”
to the console output
return;
} Just return, don’t return any value
– You can even leave this off
Why not void main() ?
• The function declaration for main() has it returning an
int
• Executing programs can cause other programs to execute
• When a program exits, the value returned by main() could be used by
the program that launched it
• The value 0 is generally used to indicate “a successful execution”
• If something went wrong, the program could return a non-zero
integer that can be used to flag what the issue was