Lecture 7 Functions NewLMS
Lecture 7 Functions NewLMS
Outline
CSC 1113 • Functions
Programming Techniques • How Functions Work
Lecture 7: Functions • Parameters and Arguments
• Categories of functions
– Built-in
– User Defined
Mrs.T.D.Gilmini
Senior Lecturer
Department of Computer Science
Function Function
• Calling a Function
• General form of a function 1. the program control is transferred to the called
return_type function_name( parameter_list ) function
{ body of the function } 2. performs a defined task
• Defining a Function 3. When its return statement is executed or ending
– consists of a function header and a function body closing brace is reached, it returns the program
– return_type is the variable type that the function returns. control back to the main program
– function_name is the actual name of the function
– parameter_list is the list of parameters that the function takes
• pass the required parameters along with the
separated by commas function name
• If no parameters are given, then the function does not take any and should be
defined with an empty set of parenthesis or with the key word void /* function declaration */
• body of the function is a collection of statements that define Int max(int num1, int num2);
what the function does /* calling a function to get max value */
ret = max(a, b);
1
11/30/2023
Functions Arguments
• These variables are called the formal parameters
of the function.
• Two ways arguments can be passed
– Call by value
• copies the actual value of an argument into the formal
parameter of the function.
• changes made to the parameter inside the function have no
effect on the argument.
– Call by reference
• copies the address of an argument into the formal
parameter
• Inside the function, the address is used to access the actual
argument used in the call.
Functions Arguments
• Default - call by value to pass arguments
• Ex 1 : Pass by value
2
11/30/2023
#include <stdio.h>
/* function declaration */
int max(int num1, int num2); Recursion
int main () {
/* local variable definition */
int a = 100; int b = 200; int ret;
• if a programming allows you to call a function
inside the same function that is called recursive
/* calling a function to get max value */ call of the function
ret = max(a, b);
printf( "Max value is : %d\n", ret ); • The C programming language supports recursion
return 0; ie. a function to call itself
}
/* function returning the max between two numbers */ – But while using recursion, programmers need to be
int max(int num1, int num2) careful to define an exit condition from the function,
{ otherwise it will go in infinite loop
/* local variable declaration */
int result;
• Recursive function are very useful to solve many
if (num1 > num2) mathematical problems like to calculate factorial
result = num1; of a number
else
result = num2;
return result;
}
Example-Recursion