You are on page 1of 24

COMP1011_20201A

: Programming Fundamentals

Instructor: Ameer Tamoor Khan Room: P504

Email: 18042271r@connect.polyu.hk
 Tutorial 3

 Program Module.
 Math Library.
 Functions.
 Function Definition
 Function Prototype.
 Function: Passing By Value Or By Reference.
 Header Files.
 Random Numbers.
 Random Number Generation.
 Program Module

 C program executes in Hierarchical manner, from Main()


top to bottom.
 For example:
 main function calls average function to calculate average.
 Average function calculate average and call display
function to display result. Average()
 Display function will report back to average function.
 Average function will then report back to main function.

 Note: main function doesn’t know anything about display


function. Display()
 Math Library

Math library is a built-in library of C to perform certain maths operations.


Includes a header file name #include <math.h> to use this library.

For example:
 printf(“%f”, exp(1))
 Equivalent to e1 = 2.718.

Some common maths function are given below.


 Math Library

Function Description Example Function Description Example

sqrt(x) square root of x sqrt(900.0) is 30.0 floor(x) rounds x to the largest integer not floor(9.2) is 9.0
sqrt(9.0) is 3.0 greater floor(−9.8) is −10.0
than x
c brt(x) cube root of x (C99 and C11 only) cbrt(27.0) is 3.0
cbrt(−8.0) is −2.0
pow(x, y) x raised to power y Left parenthesis x to the power y right parenthesis. pow(2, 7) is 128.0
exp(x) exponential function E to the power x. exp(1.0) is 2.718282 pow(9, .5) is 3.0
exp(2.0) is 7.389056
fmod(x, y) remainder of as aStart fraction x over y end fraction. fmod(13.657, 2.333) is
log(x) natural logarithm of x (base e) log(2.718282) is 1.0 floating-point number 1.992
log(7.389056) is 2.0

log10(x) logarithm of x (base 10) log10(1.0) is 0.0 sin(x) trigonometric sine of x (x in sin(0.0) is 0.0
log10(10.0) is 1.0 radians)
log10(100.0) is 2.0

fabs(x) absolute value of x as a floating-point fabs(13.5) is 13.5 cos(x) trigonometric cosine of x (x cos(0.0) is 1.0
number fabs(0.0) is 0.0 in radians)
fabs(−13.5) is 13.5
tan(x) trigonometric tangent of x (x tan(0.0) is 0.0
c eil(x) rounds x to the smallest integer not ce il(9.2) is 10.0
less than x ce il(−9.8) is −9.0 in radians)
 Functions

• Functions
• Modularize a program
• Software reusability
• Call function multiple times
• 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
 Function Definition

Function prototype
 Tells compiler argument type and return type of function
 int square( int );
 Function takes an int and returns an int
 Explained in more detail later

Calling/invoking a function
 square(x);
 Parentheses an operator used to call function
 Pass argument x
 Function gets its own copy of arguments
 After finished, passes back result
 Function Definition

Format for function definition


return-value-type function-name( parameter-list )
{
declarations and statements
}
Parameter list
 Comma separated list of arguments
 Data type needed for each argument
 If no arguments, use void or leave blank
Return-value-type
 Data type of result returned (use void if nothing returned)
 Function Definition

 Example function
int square( int y )
{
return y * y;
}
 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 caller
 Functions cannot be defined inside other functions
 Function Definition: Example

Function prototype: specifies


data types of arguments and
return values. square expects
and int, and returns an int.

Parentheses () cause function to be


called. When done, it returns the
result.

Definition of square. y is a copy of the


argument passed. Returns y * y, or y
squared.
 Function Prototype

 Function prototype contains


 Function name
 Parameters (number and data type)
 Return type (void if returns nothing)
 Only needed if function definition after function call
 Prototype must match function definition
 Function prototype
double maximum( double, double, double );
 Definition
double maximum( double x, double y, double z )
{

}
 Function Prototype
 Function signature
 Part of prototype with name and parameters
 double maximum( double, double, double );
 Argument Coercion
 Force arguments to be of proper type
 Converting int (4) to double (4.0)
printf(“%d’, sqrt(4))
 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)
 Int * double (int will be promoted to double before multiplication)
 Int a = 2; double b = 2.1;
 Printf(“%d”, a*b); (Will give you a warning and will result in random number “1279658840,” as more precedence is to double)
 Printf(“%f”, a*b); (This is the right way)
 Function: Passing By Value Or By Reference

 In many programming languages, there are two ways to pass arguments—pass-by-value and
pass-by-reference.
 When arguments are passed by value, a copy of the argument’s value is made and passed to
the called function.
 Changes to the copy do not affect an original variable’s value in the caller.
 When an argument is passed by reference, the caller allows the called function to modify the
original variable’s value.
 Pass-by-value should be used whenever the called function does not need to modify the value
of the caller’s original variable.
 Header Files

• Header files contain


• Function prototypes
• Definitions of data types and constants
• Header files ending with .h
• Programmer-defined header files
#include “myheader.h”
• Library header files
#include <math.h>
 Random Numbers

• rand function (<stdlib>)


• i = rand();
• Generates unsigned integer between 0 and RAND_MAX (usually 32767)
• Scaling and shifting
• Modulus (remainder) operator: %
• 10 % 3 is 1
• x % y is between 0 and y – 1
• Example
i = rand() % 6 + 1;
• “rand() % 6” generates a number between 0 and 5 (scaling)
• “+ 1” makes the range 1 to 6 (shift)
 Random Number Generation

• Calling rand() repeatedly


• Gives the same sequence of numbers
• Pseudorandom numbers
• Preset sequence of "random" numbers
• Same sequence generated whenever program run
• To get different random sequences
• Provide a seed value
• Like a random starting point in the sequence
• The same seed will give the same sequence
• srand(seed);
• <stdlib>
• Used before rand() to set the seed
 Random Number Generation

• Can use the current time to set the seed


• No need to explicitly set seed every time
• srand( time( 0 ) );
• time( 0 );
• <time>
• Returns current time in seconds
• General shifting and scaling
• Number = shiftingValue + rand() % scalingFactor
• shiftingValue = first number in desired range
• scalingFactor = width of desired range
Activities
1. Identify the errors.

(a) (b)

(c) (d)
2. First, write a function min that takes two inputs, i.e., integers (int), to find the minimum of two numbers. Next,
write the main() function that does the following:
 Initialize two int variables.
 Pass them to the min function.
 Return the minimum of two numbers.
 Print that number.
 Prototype: int min(int, int);
3. To determine whether a year is a leap year or not is a bit tricky. We usually assume that if the year number is
evenly divisible by 4, it is a leap year. But it is not the only case. A year is a leap year if −
 It is evenly divisible by 100
 If it is divisible by 100, then it should also be divisible by 400.
 Except this, all other years evenly divisible by 4 are leap years.

 Write a function isLeapYear, pass any year to it, and return 1 (if leap year), otherwise, return 0(not leap year).
 Prototype: int isLeapYear(int);
4. A proper factor of a number is any factor of the number except the number itself. For example, 6 has factors 1,
2, 3, and 6. The proper factors of 6 are 1, 2, and 3.
 Write a function isProperFactor(), that determines if a given integer is a proper factor of another given integer:
 For example, output to the screen if 3 is a proper factor of 6, using the following codes:
 printf("%d a proper factor of %d? %d\n", 3, 6, isProperFactor(6, 3));
 Prototype: int isProperFactor(int, int);

 Repeat the test for the following pairs:


1) 4 is a proper factor of 6?
2) 1 is a proper factor of 6?
3) 6 is a proper factor of 6?
 Your output should look like:
5. Perfect Number: In this exercise, we check whether a number is "perfect". In maths, a number is perfect if it
equals to the sum of its "proper" factors. For example, 6 = 1 + 2 + 3, where 1, 2, and 3 are all the proper factors
of 6.
 Write a function isPerfect (), which takes an integer as input and returns 1 if it is a perfect number, and 0 otherwise.
 Prototype: int isPerfect(int);
The End

You might also like