CSE 021 - Lec09 - Functions - 28.12.21
CSE 021 - Lec09 - Functions - 28.12.21
Programming
CSE 021 Fall 2021
2
Introduction to Functions
• A program may perform the same operation repeatedly,
causing a large and confusing program due to redundancy.
• redundancy can be reduced by creating a grouping of predefined
statements for repeatedly used operations
3
Divide and Conquer
• Construct a program from smaller void function1( ) {
statement
pieces or components called statement
modules. }
void function4( ) {
statement
statement
}
4
Benefits of Modularizing a Program
with Functions
• Modularized program: program wherein each task within the
program is in its own function
5
Function Definition and Call
• A function is a named series of statements.
• C standard library provides a rich collection of built-in functions
• such as scanf(), printf() etc.
6
Function Definition and Call
• A common analogy for call to function is the hierarchical
form of management
A boss (the calling function or caller) asks
a worker (the called function) to perform
a task and report back when it’s done
7
Function Definition
• Function definition: specifies what function does
8
Function Definition (Cont.)
• Function header: first line of function, which includes…
• Return value type: data type of the result
• void indicates that the function returns nothing
• Function name: any valid identifier
• Parameter list: comma separated list, declares parameters
• A type must be listed explicitly for each parameter.
• Can be empty or void for no parameters
• Placing a semicolon after the parameter-list’s right parenthesis in a function
definition is an error
9
Function Name
• Functions are given names and should be descriptive of the
task carried out by the function
• Often includes a verb
10
Function Body
• Block: set of statements that belong together as a group
enclosed in curly brackets ( { } )
12
Calling a Function
• Call a function to execute it
• When a function is called:
• jumps to the function and executes statements in the block
• jumps back to part of program that called the function
• Known as function return
13
Calling a Function: Example
#include <stdio.h>
14
Function Prototype
• Compiler uses function prototypes to validate function calls.
• A function prototype (omitting the semicolon) is generally
the same as the functions definition’s first line (function
header) without the semicolon
• Include parameter names in function prototypes for
documentation purposes
• The compiler ignores these names
15
Function Prototype
informs the compiler the type
of result value to return to
the caller.
Syntax
return_value_type function_name (parameter list type) ;
informs the compiler the
expected type of parameters
to receive from the caller
• Note: Forgetting the semicolon at the end of a function prototype is a syntax error.
16
Function Prototype (Cont.)
• The function prototype, function header, and function calls
should all agree in the number, type, and order of arguments and
parameters.
• The function prototype and function header must have the same
return type.
• The compiler compares function’s call to its prototype to ensure
that:
• the number of arguments is correct,
• the arguments are of the correct types,
• the argument types are in the correct order, and
• the return type is consistent with the context in which the function is
called.
17
Calling a Function: Example
#include <stdio.h>
void print_message();
int main(void) {
int num1, num2;
printf("Welcome!");
print_message();
Welcome!
scanf("%d", &num1);
Please enter a number:
printf("Let's add another number..\n");
print_message(); 10
scanf("%d", &num2); Let's add another number..
printf("You entered %d & %d", num1, num2); Please enter a number:
} 5
You entered 10 & 5
void print_message(){
printf("Please enter a number:\n");
}
18
Void and Value-Returning Functions
• There are two ways to return control from a called function
to the point at which a function was invoked.
• A value-returning function:
• Executes the statements it contains, and then it returns a value
back to the statement that called it.
• Return one value using a return statement
• A void function:
• Simply executes the statements it contains and then terminates.
• A function with no return statement
19
Main’s Return Type
• main’s int return value indicates whether the program
executed correctly.
• The C standard indicates that main implicitly returns 0 if
you omit the return statement at the end of main
• You can explicitly return nonzero values from main to
indicate that a problem occurred during your program’s
execution
Example: square Function
• Consider a program that uses a function square to
calculate and print the squares of the integers from 1 to 7
1 4 9 16 25 36 49
Example: square Function
#include <stdio.h>
int square(int number); // function prototype
int main(void) {
// loop 7 times and calculate and output square of x each time
for(int x = 1; x <= 7; ++x) {
printf("%d ", square(x)); // function call
}
} 1 4 9 16 25 36 49
23
Pass by Value: Example
#include <stdio.h>
void change(int x); // function prototype
int main(void) {
int x = 5;
printf("x = %d\n", x);
change(x); // function call
printf("x = %d\n", x);
}
x = 5
/* function definition x = 10
Change the value of the parameter and display it*/ x = 5
void change(int x) {
// change the value of the parameter
x = 10;
printf("x = %d\n", x);
}
Pass by Reference: Example
#include <stdio.h>
void changeArray(int a[]); // function prototype
void displayArray(int a[], int size); // function prototype
int main(void) {
int a[3] = {1,2,3};
displayArray(a, 3); // function call
changeArray(a); // function call
displayArray(a, 3); // function call
}
1 2 3
void changeArray(int a[]) { 0 2 3
a[0] = 0;
}
void displayArray(int a[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", a[i]);
}
Designing a Program to Use Functions
• In a flowchart, function call shown as rectangle with vertical
bars at each side
• Function name written in the symbol
• Typically draw separate flow chart for each function in the
program
• End terminal symbol usually reads Return
function_name( )
26
Designing a Program to Use Functions
27
Headers
• Each standard library has a corresponding header containing
• the function prototypes for all the functions in that library
• definitions of various data types and constants needed by those
functions
• You can create custom headers, which are included in
quotes ("") rather than angle brackets (<>).
28
Math Library Functions
• Math library functions (header math.h) perform common
mathematical calculations
• printf("%.2f", sqrt(900.0));
• Calls function sqrt to calculate the square root of 900.0, then prints the
result as 30.00
• sqrt takes a double argument and returns a double result
• Function arguments may be constants, variables, or expressions
• The following table summarizes several C math library functions
• In the table, the variables x and y are of type double.
29
Math Library Functions
Function Description
sqrt(x) square root of x
cbrt(x) cube root of x (C99 and C11 only)
exp(x) exponential function e to the power of x
log(x) natural logarithm of x (base e)
log10(x) logarithm of x (base 10)
fabs(x) absolute value of x as a floating-point number
ceil(x) rounds x to the smallest integer not less than x
floor(x) rounds x to the largest integer not greater than x
pow(x, y) x raised to power y left parenthesis x to the power of y right parenthesis
fmod(x, y) remainder of x/y as a floating-point number
sin(x) trigonometric sine of x (x in radians)
cos(x) trigonometric cosine of x (x in radians)
tan(x) trigonometric tangent of x (x in radians)
30
Be Ready for a Quiz on
Next Week
End of Lecture!
Thanks for your Attention!
31