0% found this document useful (0 votes)
10 views

Computer Programming Chapter5function

The document discusses functions in C programming. It defines functions, explains function elements like prototypes and definitions, and provides examples of separating code into different functions to perform arithmetic operations like addition and subtraction.

Uploaded by

breakdamt
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)
10 views

Computer Programming Chapter5function

The document discusses functions in C programming. It defines functions, explains function elements like prototypes and definitions, and provides examples of separating code into different functions to perform arithmetic operations like addition and subtraction.

Uploaded by

breakdamt
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/ 58

CHAP 5 :

FUNCTION
Chapter : 5 FUNCTION
• Definitions of function, function ▪ Modular Programming
access and function recall ▪ User defined functions
• Types and prototype of functions ▪ Function elements:
▪ definition
▪ Prototype
▪ function call
Let’s try this…
Write a program that can add, subtract, multiply #include <stdio.h>
and divide two numbers. void main ()
{
int a, b;
printf (“Enter two integers : “);
scanf (“%d %d”,&a,&b);
addresult = a+b;
subresult = a-b;
mulresult = a * b;
divresult = a / b;
printf(“Addition result = %d”, addresult);
printf(“Subtract result = %d”, subresult);
printf(“Multiply result = %d”, mulresult);
printf(“Divide result = %d”, divresult);
}
How function works???
Main program func1()
{
int main () }
{
Call func1
func2()
:
{
Call func2
}
:
Call func3
func3()
{
}
What do you think?
• There are so many functions in
main().
• We can separate the functions (add, subtract, multiply and divide ) into
several functions.
• So, how to divide them ?
What is function?
• Is a program segment that performs specific tasks, made up of C statements

Standard library exit(), scanf(), printf(),


functions clrscr ()
function

User-defined Created by user for


functions specific purposes
4 types of function
1. Receive parameter/argument and Return value
2. Receive parameter/argument and No Return value
3. Not Receive parameter/argument and Return value
4. Not Receive parameter/argument and No Return
Value
Function Receive Not Receive Return Not Return
Parameter Parameter Value (RV) Value (NV)
(RP) (NP)
RPRV x x
RPNV x x
NPRV x x
NPNV x x
Function elements

Function prototype

Function Definition

Function Call
Separate the functions
#include <stdio.h>
void main()
{ int a,b, mulresult, addresult, subresult;
int divresult;
//Input value
//Input value
printf (“Enter two integers : “);
printf (“Enter two integers : “);
scanf (“%d %d”,&a,&b); scanf (“%d %d”,&a,&b);

//Arithmetic operation
addresult = a + b; //Arithmetic operation
subresult = a – b;
addresult = a + b;
mulresult = a * b;
divresult = a / b;
subresult = a – b;
mulresult = a * b;
//Output printing divresult = a / b;
printf(“Addition result = %d”, addresult );
printf(“Subtract result = %d”, subresult );
printf(“Multiply result = %d”, mulresult );
printf(“Divide result = %d”, divresult); //Output printing
printf(“Addition result = %d”, addresult );
} printf(“Subtract result = %d”, subresult );
printf(“Multiply result = %d”, mulresult );
printf(“Divide result = %d”, divresult);
#include <stdio.h> //Arithmetic operation
void Calculate()
int a,b, mulresult, addresult, subresult; {
int divresult; addresult = a + b;
void InputValue(); subresult = a – b;
void Calculate(); Function prototype mulresult = a * b; Function
void PrintResult(); divresult = a / b;} definition
void main() //Output printing
{ void PrintResult()
InputValue(); {
Calculate(); Function call printf(“Addition result = %d”, addresult );
PrintResult(); printf(“Subtract result = %d”, subresult );
} printf(“Multiply result = %d”, mulresult );
printf(“Divide result = %d”, divresult);
//Input value }
void InputValue()
{
printf (“Enter two integers : “);
scanf (“%d %d”,&a,&b);
}
Function Prototype

Must be It tells the There is no


added to a compiler: need for a
C program • what type of value the prototype if
function returns
before the • number and types of the function
parameters
main • order in which these is called
function, parameters are
expected. after its
– if call that function definition.
before defining it.
Example: function prototype

Function prototype Parameters Parameter Function name Function return


type type
float RPRV (int a, char b); a&b int & char RPRV float
@
float RPRV (int a, char b);
void RPNV (int a, char b); a&b int & char RPNV void
@
void RPNV (int a, char b);
float NPRV (void); void NA NPRV float
@
float NPRV (void);
void NPNV (void); void NA NPRV void
@
void NPRV (void);
#include <stdio.h>

void addition ( int, int ); Function Prototype


void subtract ( int, int );
void main ( )
{
int a, b;
scanf ( “%d %d”,&a,&b);
addition(a,b);
subtract(a,b);
}

void addition (int a, int b)


{
addresult = a+b;
printf(“Addition result = %d”, addresult);
}

void subtract (int a, int b)


{
subresult = a-b;
printf(“Subtract result= %d”, subresult);
}
Function Definition

• A function definition has two principal void addition (int a, int b)


{
components: addresult = a+b;
– the first line (including the argument declarations), and printf(“Addition result = %d”, addresult);
– the body of the function. }

• The first line of a function definition contains


– type of the value returned by the function
– the function name, and
– (optionally) a set of arguments, separated by commas and enclosed in
parentheses.
#include <stdio.h>
void addition ( int, int );
void subtract ( int, int );

void main ()
{
int a, b;
scanf ( “%d %d”,&a,&b);
Parameters /
addition(a,b);
subtract(a,b);
arguments data type
}
a and b are
Function Function parameters /
return type name arguments

void addition (int a, int b)


{
addresult = a+b; Function
printf(“Addition result = %d”, addresult); Definition
}

void subtract (int a, int b)


{
subresult = a-b;
printf(“Subtract result = %d”, subresult);
}
Function Definition (cont.)
void addition (int a, int b) First line

{
addresult = a+b;
printf(“Addition result = %d”, addresult);
}

Body
Function Definition (cont.)
• Format of a function definition
Return-value-type function-name (parameter-list)
{
declarations

statements A return value of type void


} indicates a function
does not return a value.
void addition (int a, int b)
{
addresult = a+b;
printf(“Addition result = %d”, addresult);
}
Function Definition (cont.)
• Function Definition: argument/parameter
– The arguments are called formal argument
• because they represent the names of data items that are
transferred into the function from the calling portion of the
program.
– There are also known as parameters or formal parameters.
– The identifiers used as formal arguments are “local”
• because they are not recognized outside of the function.
• the names need not to be same as the names of the actual
arguments in the calling portion of the program.
Arguments / Parameters
a and b are
Arguments /
Parameters
void addtion (int a, int b)
{
addresult = a+b;
printf(“Addition result = %d”, addresult);
}
Function Definition (cont.)
• Function Definition: compound
statement/body
– compound statement / function body defines
the action to be taken by the function.
– can contain expression statements, other
compound statements, control statements, and
so on.
– It should include one or more return statements,
in order to return a value to the calling portion of
the program.
Example
Function prototype & definition
#include <stdio.h>

int mod(int, int); /* Function Prototype */

void main()
{
printf("The mod is: %d ", mod(4,5));
}

int mod(int a, int b) /* Function Definition */

{
OUTPUT?
return a % b;
}
The mod is: 4
Example
• Function with definition but without prototype

#include <stdio.h>

int sum(int a, int b) /* Function Definition */


{
return a+b;
}

void main()
{
printf("The sum is: %d ", sum(4,5));
}
OUTPUT?

The mod is: 4


Function calls

• A function can be accessed (i.e., called) by


– specifying function name, followed by a list of arguments enclosed in
parentheses and separated by commas.
• If the function call does not require any arguments
– empty pair of parentheses must follow the name of the function.
• The arguments appearing in the function call are referred to as actual arguments, in contrast
to the formal arguments that appear in the first line of the function definition.
#include <stdio.h>
void addition ( int, int );
void subtract ( int, int ); Find errors:

void main ()
{
int a, b;
printf("Please enter 2 numbers:");
scanf ( “%d %d”,&a,&b);
addition(a,b); a and b are actual
subtract(a,b); Function calls parameters /
}
arguments in
function call
void addition (int c, int d)
{
addresult = c + d;
Function definition
printf(“Addition result = %d”, addresult);
c, d, e and f are
} formal parameters /
arguments in
void subtract (int e, int f) function definition
{
subresult = e - f; Find output if
printf(“Subtract result = %d”, subresult); a=5 and b = 3
}
Function Calls (cont.)

Need 1 variable to
store results from
Return value function
Ex: B=sum(a)
Function call

Not return sum(a)


Function Calls (cont.)

A function can be called by

• the main function


• other functions
• itself (recursion)

In C, functions call can be

• by value
• by reference
Function Calls (cont.)
• 1. Call by value
– Copy of variable passed to function
– If that variable is modified within the function, only the copy has been modified,
the actual variable is not modified
• 2. Call by reference
– Pass the address of a variable (i.e. a pointer) to a function
– The variable pointed to can be modified within that function
Function Calls (cont.)
• Example Call By Value

finval = FuncByValue(finval);

/*The FuncByValue function*/


finval is type
float float FuncByValue(float fval)
to receive the
result of {
fval*fval return fval*fval;
}
Function Calls (cont.)
• Example Call By Reference
FuncByReference(&finref)

• Use & to pass the address of a variable to the function

• Value of the referenced variable passed to the function is modified


after returning from the function.

the function void FuncByReference(float *fvalptr)


access appears by {
*fvalptr = *fvalptr * *fvalptr;
itself since it does
}
not return a value
Program Example
TYPE OF FUNCTION
Types of function
1. Receive parameter/argument and Return value
2. Receive parameter/argument and Not Return value
3. Not Receive parameter/argument and Return value
4. Not Receive parameter/argument and Not Return Value

Format

function type function_name (parameter_list);

Determine whether Determine whether


function returns a value functions receive a value
1. Receive parameter/argument and Return value
Example:
int function1(int);

returns value receives integer value

float function2(int,int);

returns value receives two integer values

int function3(int,float,int);

returns value receives two integers and a float values


1. Receive parameter/argument and Return value

Prototype: #include <stdio.h>


float calculate_discount(int); float calculate_discount(int);

Call: void main()


{ int quantity;
calculate_discount(kuantiti);
printf(“Enter quantity :”);
scanf(“%d”,&quantity);
Definition: printf(“Discount %d”,calculate_discount(quantity));
}
float calculate_discount(int b)
{ if (b > 1000) float calculate_discount(int quantity)
discount = 0.5; {
else float discount;
if (quantity > 1000)
discount = 0.1;
discount = 0.5;
return discount; else
} discount = 0.1;
return discount;
}
Program Example
2. Receive parameter/argument and Not Return value
Example:
void function1(int);

not return value receives integer value

void function2(int,int);

not return value receives two integer values

void function3(int,float,int);

not return value receives two integers and a float values


2. Receive parameter/argument and Not Return
value
Example 1:

Prototype: #include <stdio.h>


void function1(int);
void function1(int);
Call:
function1(a); void main()
{ int a ;
Definition: printf(“Enter value :”);
scanf(“%d”,&a);
void function1(int a) function1(a);
{ printf(“Value a is %d”,a); } }

void function1(int a)
{ printf(“Value a is %d”,a); }
2. Receive parameter/argument and Not Return
value
Example 2:

Prototype: #include <stdio.h>


void print_discount(int);
void print_discount(int);
void main()
Call: { int quantity;
print_discount(quantity); printf(“Enter quantity : ”);
scanf(“%d”,&quantity);
Definition: print_discount(quantity);
void print_discount(int b) }
{ if (b > 1000) void print_discount(int b)
printf(“Discount = 50%”); { if (b > 1000)
else printf(“Discount = 50%”);
printf(“Discount = 10%”); else
} printf(“Discount = 10%”);
}
Program Example
3. Not Receive parameter/argument and
Return value
3. Not Receive parameter/argument and Return value

Example:
int function1(void);

returns value int not receive value

float function2(void);

returns value float not receive value

int function3(void);

returns value int not receive value


3. Not Receive parameter/argument and
Return value
Example 2:

Prototype: #include <stdio.h>


int print_discount();
int print_discount();
int quantity;

Call: void main()


print_discount(); { printf(“Enter quantity : ”);
scanf(“%d”,&quantity);
Definition: printf(“Discount %d”, print_discount());
int print_discount() }
{ int discount int print_discount()
{ int discount
if (quantity > 1000)
if (quantity > 1000)
discount = 50 discount = 50
else else
discount = 10 discount = 10
return discount; return discount;
} }
Program Example
4. Not Receive parameter/argument and
Not Return value

Example:
void function1(void);

not return value not receive value

void function2(void);

not return value not receive value


4. Not Receive parameter/argument and
Not Return value
Example:

Prototype: #include <stdio.h>


void input();
void input(); //function prototype
Call:
input(); void main()
{
Definition: input(); //function call
}
void input()
{ printf(“Enter input :”); //function definition
scanf(“%d”,&input); void input()
} { printf(“Enter input :”);
scanf(“%d”,&input);
}
Program Example
Class Exercises

A. Give the function prototype for each of the following:


•Function smallest that takes three integers, x, y, z and returns an integer.
•Function instructions that does not receive any arguments and does not return
a value.
•Function inToFloat that takes an integer argument, number, and returns a
floating-point result.
Class exercise : Create function definition
Write a program using switch …
case statement for selection area
of shape depends on the character
entered by the user (R-Rectangle, T-
Triangle and C-Circle). Create
function rectangle(), triangle() and • During class define
circle to calculate and display the
area of the shape. Your program able – the first line (including the argument declarations), and
to display user selection (R,T or C) – the body of the function.
and validate wrong input.
You may use the following equation:

area of rectangle = width ×


length
area of triangle = 12 × base ×
height
area of circle = 3.142 × radius
2
Scope of variable

•Scope determine where the variable will be used.


•Two types of scope: GLOBAL and LOCAL

It’s scope begins at the point of its


declarations and terminates at the end of
GLOBAL variable file.

Example

#include <stdio.h>
Declared before main()
int a,b;
float c;
a, b and c are void main()
global variable {
}
Scope of variable (cont)

Variable that can be accessed inside the


main() function or the function that
LOCAL variable declares it.

Example

Declares inside
#include <stdio.h>
main() function or any
void getvalue();
other functions
void main()
{ int x; }
x is a local variable to main()
function and z is a local void getvalue()
variable to getvalue() function { int z;
…………
}
Scope of variable (cont.)
Example 1:
OUTPUT?

#include <stdio.h> Enter value of a and b: 4 5

int a, b; //global variable


void display();

void main()
{ printf(“\nEnter value of a and b : ”);
scanf(“%d %d”,&a,&b);
display();
}

void display()
{
printf(“Value a is % and b is %d”, a,b);
}
Scope of variable (cont.)
Example 2:

#include <stdio.h>
Output?
int a, b; //global variables
void display();

void main()
{ int c; //local variable
a= 5;
b = 9;
c = 12;
display();
printf(“\nValue c is %d”, c);
}

void display()
{
printf(“\nValue a is %d”,a);
printf(“\nValue b is %d”,b);
printf(“\nValue c is %d”,c);
}
Scope of variable (cont.)

Example 3:
#include <stdio.h> Output?
void display();

void main()
{ int c; // local variable
a= 5;
b = 9;
c = 12;
display();
printf(“\nValue c is %d”, c);
}
void display()
{ int a, b; //local variables
printf(“\nValue a is %d”,a);
printf(“\nValue b is %d”,b);
}
Scope of variable (cont.)
Example 4:

#include <stdio.h>
void function1()
void function1(); { int i,j ;
void function2(); i= 3;
int z; j = i;
printf(“\nValue i is %d”,i);
void main() printf(“\nValue j is %d”,j);
{ function1(); }
x = 7;
z = 15; void function2()
function2(); { int x = 4;
} z = j;
printf(“\nValue x is %d”,x);
printf(“\nValue z is %d”,z);
z is a global variable, so it
}
can be used by any function
including main()
What is the output of this program?
#include<stdio.h>
void change1(int);
int change2(int); void change1(int a)
void main() { a=2*a;
{ printf(“Value of a in change1 function:
int a=5; %d\n",a);
int b; }
printf(“Before change1: a=%d\n",a);
change1(a); int change2(int b)
printf(“After change1: a=%d\n",a); { int a;
b=change2(a); a=4;
printf(“After change2: a=%d b=a + b;
b=%d\n",a,b); return (b);
} }
Program Example : Maximum number
Exercise
Write a program using switch …
case statement for selection area
of shape depends on the character
entered by the user (R-Rectangle, T- Output example:
Triangle and C-Circle). Create Enter shape >> T
function rectangle(), triangle() and Your choice : T
circle to calculate and display the Enter value of base : 10
area of the shape. Your program able Enter value of height : 2
to display user selection (R,T or C) Area of triangle : 240
and validate wrong input.
You may use the following equation: Output example:
Enter shape >> k
area of rectangle = width × WRONG INPUT!! ENTER Again
length
area of triangle = 12 × base ×
height
area of circle = 3.142 × radius
2
Exercise

Q1. Develop a program to find a minimum number between


2 integers values.

Q2. Develop a program to find a maximum number between


3 integers values

You might also like