Functions: Malaysian Institute of Aviation Technology
Functions: Malaysian Institute of Aviation Technology
FUNCTIONS
Malaysian Institute of Aviation Technology
Introduction
• A function is a set of statements that:
- Take inputs,
- Do some specific computation
- Produces output.
• The idea is to put some commonly or repeatedly
done task together and make a function, so that
instead of writing the same code again and again for
different inputs, we can call the function.
Malaysian Institute of Aviation Technology
Introduction
• Mini-program where a group of statements
are executed.
• Programmer-defined functions.
• Break a large program into smaller sets of
statements according to their tasks.
Malaysian Institute of Aviation Technology
Benefits of Function
• To make program more manageable
– divide-and-conquer approach (construct a
program from smaller components/modules.
• Software reusability
– reuse existing functions for new programs
• Avoid repeating code
Malaysian Institute of Aviation Technology
Malaysian Institute of Aviation Technology
Malaysian Institute of Aviation Technology
Sequence of Execution
Malaysian Institute of Aviation Technology
4 Elements of Function
• Function declaration
• Function definition
• Function prototype
• Calling function
Malaysian Institute of Aviation Technology
Function Declaration
• Function declaration tells compiler about number of
parameters function takes, data-types of parameters and
return type of function.
• Putting parameter names in function declaration is
optional in function declaration, but it is necessary to put
them in definition.
• The example of function declarations:- (parameter names
are not there in the declarations)
Malaysian Institute of Aviation Technology
Function Declaration
Malaysian Institute of Aviation Technology
Function Definition
• Specifies the specification of a function
– return value type, function name, arguments.
• Defines the operation to be performed when a
function is invoked.
Malaysian Institute of Aviation Technology
Function Definition
return_value_type function_name(parameter_list)
{
statements;
}
function header
function body
Malaysian Institute of Aviation Technology
Function Definition
return_value_type function_name(parameter_list)
{
statements;
}
❑ Specifies the type of the value returned by the function
❑ Data types of return value : int (default),char, float, double
❑ If function does not has any return value : void
Function Prototype
• To declare function if the function definition is
written below the main function.
• Otherwise, no need function prototype. (function
definition above the main function)
• Almost similar with function definition header, but
must be written before the main function with
semicolon at the end of statement.
Malaysian Institute of Aviation Technology
Function Prototype
return_value_type function_name(parameter_list);
Calling Function
• Two ways to invoke/call function
– Call-by-value
– Call-by-reference.
• Calling function statement is written in the
caller function (main function).
Malaysian Institute of Aviation Technology
Call-by-Value VS Call-by-
Call-by-value Reference
Call-by-reference
• Copies of the • References of the
arguments’ value are arguments’ value are
made and passed to the passed to the called
called function function
• Changes to the copy do • Called function can
not effect an original modify the original
variable’s value variable’s value
• Available in C language • Possible to simulate
Malaysian Institute of Aviation Technology
Example 1
#include<stdio.h>
void function_name(void);
Function prototype
int main() {
statements;
function_name();
return 0;
} Calling function
Function definition
void function_name(void) {
statements;
}
Malaysian Institute of Aviation Technology
Example 2
#include<stdio.h>
double function_name(int,double);
int main() { Function prototype
int p1, double p2;
statements;
function_name(p1,p2);
return 0;
} Calling function
Example 3
Sample output:
Call-by-value
----------------------
Before func1 is called
n1 = 5
In func1
n1 = 10
Example 4
function prototype
function call
Sample output:
Enter base and power: 5 4
The result is 625.
function definition
Malaysian Institute of Aviation Technology
Variable Scope
• Variables declared in function main() are
known only within function main() – not
accessible outside of the block
• It is applied to variables defined within a block
that is inside other block
• But variables defined in the outer block are
accessible in the inner block
Malaysian Institute of Aviation Technology
Variable Scope
• Variable a is declared in
main()
• Variable b is declared
within while loop block
(inner block)
• a is the outer block
variable therefore it is
accessible within inner
block
• b is not accessible in the
outer block because it is
while loop variable
Malaysian Institute of Aviation Technology
Variable Scope
num2 is declared in main()
Global Variable
• Variables declared outside any function is
called global variables
• Global variables are variables that can be
accessed in any function
• Normally they are declared before function
main()
Malaysian Institute of Aviation Technology
Global Variable
Recursive Function
• Function that calls itself either directly or
indirectly through another function
Malaysian Institute of Aviation Technology
Example 5
Sample output:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
Malaysian Institute of Aviation Technology
Exercise
Malaysian Institute of Aviation Technology
Exercise 1
Write a program that will prompt the user to choose the operation choice
(from 1 to 5). Then it asks the user to input two integer values for the
calculation. See the sample below:
MENU
1. Add
2. Subtract
3. Multiply
4. Divide
5. Modulus
Enter your choice: 1
Enter your two numbers: 12 15
Result: 27
Continue? y (y=yes, n=no)
The program also asks the user to decide whether he/she wants to continue the
operation. If he/she input ‘y’, the program will prompt the user to choose the
operation again. Instead, the program will terminate.
Malaysian Institute of Aviation Technology
Answer 1
#include <stdio.h> int Add(int a,int b){
#include <stdlib.h> return(a+b);
void displaymenu(){ }
printf("========================\n");
printf(" MENU \n"); int Substract(int a, int b){
printf("========================\n"); return(a-b);
printf(" 1.Add\n"); }
printf(" 2.Subtract \n");
printf(" 3.Multiply \n"); int Multiply(int a, int b){
printf(" 4.Divide \n"); return(a*b);
printf(" 5.Modulus \n"); }
}
float Divide(int a,int b){
return(a/b);
}
Malaysian Institute of Aviation Technology
Answer 1 - cont
Int Modulus(int a, int b){
return(a%b);
} do {
printf("Enter your choice(1-5):");
int main(int argc, char *argv[]) scanf("%d:",&yourchoice);
{ printf("Enter your two integer numbers:");
//show menu scanf("%d %d",&a,&b);
displaymenu(); printf("\n");
int yourchoice;
int a;
int b;
char confirm;
Malaysian Institute of Aviation Technology
Answer 1 - cont
switch(yourchoice){
printf("\nPress y or Y to continue:");
case 1:printf("Result:%d",Add(a,b));
scanf("%s",&confirm);
break;
}
case 2:printf("Result:%d",Substract(a,b));
while(confirm=='y'||confirm=='Y');
break;
return 0;
case 3:printf("Result:%d",Multiply(a,b));
}
break;
case 4:printf("Result:%.2f",Divide(a,b));
break;
case 5:printf("Result:%d",Modulus(a,b));
break;
default:printf("invalid");
}
Malaysian Institute of Aviation Technology
Exercise 2
Write a program that use the selection
sort algorithm to sort an integer array in
ascending order.
Answer 2
#include <stdio.h> // swapping the min item with the beginning item of the array
#include <stdlib.h> if(min!=i){
void mysort(int vallist[]){ int temp=vallist[min];
int i,j; vallist[min]=vallist[i];
int min; vallist[i]=temp;
for(i=0;i<10;i++){ }
min=i; }
for(j=i+1;j<10;j++) // Display array after being sorted
if(vallist[min]>vallist[j]){ for(i=0;i<10;i++)printf("%d\n",vallist[i]);
// search for the min item }
min=j;
} int main(int argc, char *argv[])
{
int vallist[]={23,2,34,23,43,22,32,32,43,34};
mysort(vallist);
return 0;
}