0% found this document useful (0 votes)
14 views31 pages

CSE 021 - Lec09 - Functions - 28.12.21

Uploaded by

akramreda120
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views31 pages

CSE 021 - Lec09 - Functions - 28.12.21

Uploaded by

akramreda120
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Introduction to Computer

Programming
CSE 021 Fall 2021

LECTURE 09: Functions


Dr. Basma Hassan
[email protected]
Lecture Topics
• Introduction to Functions
• Program Modularization
• Local Variables
• Function Prototype
• Void and Value-Returning Functions
• Passing Arguments by Value and by Reference
• Designing a Program to Use Functions
• Headers
• Math Library Functions

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

• Function: group of statements within a program that


perform as specific task
• Usually one task of a large program
• Functions can be executed in order to perform overall program task
• Known as divide and conquer approach

3
Divide and Conquer
• Construct a program from smaller void function1( ) {
statement
pieces or components called statement
modules. }

• Each piece is more manageable


void function2( ) {
statement
than the original program. statement
}
• Using functions to divide and void function3( ) {
conquer a large task. statement
statement
}

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

• The benefits of using functions include:


• Simpler code
• Code reuse
• write the code once and call it multiple times
• Better testing and debugging
• Can test and debug each function individually
• Faster development
• Easier facilitation of teamwork
• Different team members can write different functions

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.

• A function definition is the statements defining the function


• consists of the new function's name, inputs, and return.
• A function call is an invocation of the function's name, causing
the function’s statements to execute.
• Causes execution to jump to the function's statements.
• Execution returns to the original location after executing the function's
last statement.

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

The worker may call other


worker functions, and the boss
will be unaware of this

7
Function Definition
• Function definition: specifies what function does

Syntax Function header

return_value_type function_name (parameter list) {


Statement
Statement Return statement
…… (OPTIONAL)
return [expression]
}

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

• Function naming rules:


• Cannot use keywords as a function name
• Cannot contain spaces
• First character must be a letter or underscore
• All other characters must be a letter, number or underscore
• Uppercase and lowercase characters are distinct

10
Function Body
• Block: set of statements that belong together as a group
enclosed in curly brackets ( { } )

• The statements within braces form the function body, which


also is a block.
• Blocks can be nested
• Functions cannot be nested
• defining a function inside another function is a syntax error
Local Variables
• Local variable: variable defined in function definitions
• Belongs to the function in which it was defined
• Only statements inside that function can access it, error will occur if another
function tries to access the variable
• Can’t be accessed outside the function in which it is defined
• Parameters are also local variables of that function.
• Different functions may have local variables with the same
name
• Each function does not see the other function’s local variables, so
no confusion.

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>

// A function that print a message


void print_message(){
printf("Please enter a number:\n");
}

int main(void) { Welcome!


int num1, num2; Please enter a number:
printf("Welcome!"); 10
print_message(); Let's add another number..
scanf("%d", &num1); Please enter a number:
printf("Let's add another number..\n"); 5
print_message(); You entered 10 & 5
scanf("%d", &num2);
printf("You entered %d & %d", num1, num2);
}

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

/* square function definition


returns the square of its parameter*/
int square(int number) {
// returns square of number as an int
return number * number;
}
Passing Arguments by Value and by
Reference
• Pass-by-value—a copy of the argument’s value is passed
• Changes to the copy do not affect an original variable’s
• Pass-by-reference—the called function can modify the original
variable’s value
• Use pass-by-value when the called function does not need to
modify the value of the caller’s original variable
• Prevents accidental side effects (variable modifications)
• In C, all arguments are passed by value
• Array arguments are automatically passed by reference, but array
element is passed by value.
• Pointers, show how to achieve pass-by-reference (next lecture)

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

You might also like