Professional Documents
Culture Documents
Programming
▪ What is function?
▪ Why do we need function?
▪ Syntax of creating a function and using a function
▪ Function with return type
▪ Function with non-return type
▪ Examples of function
▪ Recursive function
▪ Syntax
▪ example
2
Function
3
Function
❑ What and Why?
▪ A function is a block of code that performs a specific task. A function may return a
value.
▪ Why function?
✓ A large and complex program can be divided into smaller programs
✓ assign task and work in team is easy
✓ Reusable code
4
Function
❑ Type of function
5
Syntax
❑ Function with returning value
c) Parameter of a function
It has parameter type and parameter name
If have more than one, separate them by comma
type functionName(type parameter1){
... .. ... b) Name of function
... .. ... it should start with a verb
return value;
}
void greetMessage(char name[20]){
printf(“Hi, %s”, name);
printf(“Welcome back!”);
a) Void means no returning d) No need to return value since we
value from the function use void in a) }
Function
User-defined
Local variables
function
res=(a+b)*2;
✓ Its value will be destroyed after the function n++;
finish executing return res;
Output: }
int main(){
int num=10;
▪ Global value is variable that creates int res=2;
outside the function below all library inclusion printf("*Start program \n");
✓ Its value can be accessed from any functions printf(“%d”, sum(2,5));
res = sum(2,5)
✓ Its value will be destroyed after the whole printf(“%d”, res);
program finish executing printf(“%d”, n);
Call created function
} 9
Example of functions
❑ Returning Vs. Non-returning value function
▪ Function with returning value ▪ Function with no returning value
10
Q&A
11
Creating a simple function with return value
12
function with input from user
13
Function with return value and with no return value
14
Function in function
15
Using global variable in function
16
Practices
❑ Write a C++ program to solve the following problem.
19
Practice
❑ Write a C++ program to solve the following problem.
20