You are on page 1of 14

Functions and Structured Programming

Function
- a group of program statements that performs a specific task:
▪ a function that handles all inputs
▪ a function that displays a menu
▪ a function that computes some values
- mostly used to break up a large program into simpler and manageable parts (modules)

2 types of functions:
a) Standard functions
- predefined or built-in functions of the C system compiler
- we could easily identify them since they are the C statements with an open and close parentheses ( )
- examples are main( ), printf( ), scanf( ), getch( ), etc.

b) Programmer-defined functions

Syntax of a Function:

datatype_returned function_name(parameter list)


{
variable declarations;
statements;
return;
}

Each function has a name which is used to refer to that function. Each function name must be unique. A function name
may be any valid identifier. The statements enclosed by curly braces comprise the body of the function.

Function Invocation

A program is made up of one or more functions, one of them is main(). Program execution always begins with main().
To execute a function, a function call is made somewhere in the program. A function call causes the execution of the
statements in the body of a function. To make a function call, simply write down the function name followed by
parentheses ( ) and a semicolon.

Example 1

#include<stdio.h>

void fxn1(void) /* fxn1 is an example of a programmer-defined function. */


{
printf(“\nFirst function”);
}

void fxn2(void) /* void data type means no value will be returned by function fxn2 */
{
printf(“\nSecond function”);
}

void fxn3(void){ /* void inside the parentheses means there is no value to be


passed into the parameter list*/
printf(“\nThird function”);
}

Functions and Structured Programming


Prepared by: Kim L. Faburada 1
int main(void) /* program execution begins with function main */
{
printf(“Text inside function main”);
fxn1(); /* call function fxn1 */
printf(“\nText inside function main”);
fxn2();
printf(“\nSecond function”);
fxn3();

return 0;
}

Output:

Text insText inside function main i


First function
Text inside function main
Second function
e functi Second function
First fu Third function
Text inside function main
Second function
Text inside function main__________________

Problem #1:
Write a function-oriented program that performs a printing task for a long line above and below the words “OFFICIAL
RECEIPT.” Call or invoke this function from the main program two times.

Example 2

#include<stdio.h>

int num1, num2; /* num1 and num2 are examples of globally declared variables */

void input(void) /* a function that accepts user inputs */


{
printf(“Enter first number: “);
scanf(“%d”,&num1);
printf(“Enter second number: “);
scanf(“%d”,&num2);
}

void compute_sum(void) /* a function that calculates the sum of 2 entered numbers */


{
int sum; /* variable sum is declared locally inside function compute_sum */

sum = num1+num2;
printf(“The sum of %d and %d is %d”, num1, num2, sum);
}

int main(void)
{
input();
compute_sum();

return 0;
}

Functions and Structured Programming


Prepared by: Kim L. Faburada 2
Problem #2:

Write a function-oriented program that computes for the diameter, circumference and area of a circle. The program
must have a separate function to:

a) accept an input for radius


b) compute and display the diameter of a circle (diameter = 2*radius)
c) compute and display the circumference of a circle (circumference = 2 * pi * radius)
d) compute and display the area of a circle (area = pi * radius * radius)

Note: Only variables radius and pi must be declared globally. Other variables must be declared locally.

Function Prototype

Example 3

#include<stdio.h>

void fxn1(void); /* function prototype */


void fxn2(void);

int main(void)
{
int a=5;
float b=7..67;
char sample =’H’;

printf(“Text inside function main”);


fxn1();
fxn2();
return 0;
}

void fxn2(void)
{
printf(“\nText inside function fxn2”);
}

void fxn1(void)
{
printf(“\nText inside function fxn1”);
}

Output

Text inside function main


Text inside function fxn1
Text inside function fxn2

The program above shows a function heading written above the main() function or main program. This function
heading tells the C compiler that there are subprograms called fxn1() and fxn2() below the main program.

Functions and Structured Programming


Prepared by: Kim L. Faburada 3
Functions and Structured Programming
Prepared by: Kim L. Faburada 4
Passing No Value

The given codes were examples of programs with function calls that do not pass any value into the parameter list,
thus, void is explicitly written inside the function’s parentheses. The explicit declaration of void is a good programming
practice since it tells the C compiler in advance that no value is to be passed into the parameter list.

Parameter Passing

Functions can be written to accept values (through parameters) and to return a value. This is useful for computational
tasks. The function computes a value using the parameters and returns the value computed.

To define such a function in C, we need to specify the data types and variable names of the parameters and also the
data type of the value to be returned by the function.

Function Format:

char function_name(formal parameter)


{
local variable declaration/s;
float a=5
statement1;

statement N;
return expression;
}

Where the format of the formal parameter is (datatype variable_name)

Examples: float fxn1(int x, float y, char a) /* there are 3 parameters accepted by fxn1 */
float fxn2(int b) /* there is a single parameter accepted by fxn2 */

When called/invoked in the calling function, the basic format is: function_name(actual parameter)

Where the format of the actual parameter is (variable_name1,… variableN);

Examples: fxn1(m, n, z); /* where m is integer, n is float and z is a character */


fxn2(t); /* where t is an integer */

Formal Parameter

- a variable that accepts a value from the calling function


- this is a variable which is seen in the function heading
- its name can be the same as that of the actual parameter
- sometimes called dummy parameter or dummy variable because its purpose is only to accept whatever
value passed from the calling function

Actual Parameter

- a variable that passes a value to a called function


- a variable which is seen in the function call

When passing parameters, the number of actual parameters should coincide with the number of formal parameters.
They should also be declared in sequence.

Functions and Structured Programming


Prepared by: Kim L. Faburada 5
Example 4

/* This is an example of a program that passes a value to a called function without returning any value
to the calling environment
*/

#include<stdio.h>

void fxn1(int); /* function prototype */


void fxn2(char, int);

int main(void)
{
int x =2;
char y=’b’;

fxn1(x); /* calls function fxn1 and passes the value of x to the first parameter which is m */
fxn2(y, 3);
fxn2(‘k’,x);
return 0;
}
z = ‘k’ w=2
void fxn2(char z, int w) /* function fxn2 consists of 2 formal parameters, namely, z and w */
{
printf(“\n%d %c”,w, z);
}

void fxn1(int m) // m =2
{
printf(“%d “,m);
}

Output

2
3b
2k
2k

Problem 3:

Write a function-oriented program that computes the area of a rectangle. Inputs must be done inside function main()
and must be passed to a function that computes and displays the area.

Hint: Formula: Area = Length * Width;


Two (2) values must be passed into the formal parameters of the called function
You must not use global variables this time to be able to apply parameter passing by value

Functions and Structured Programming


Prepared by: Kim L. Faburada 6
Functions and Structured Programming
Prepared by: Kim L. Faburada 7
The return statement

- may or may not include an expression


examples:
return;
return x;
return ++x; /* if the value of x is 3 then it returns 4 to the calling environment */
return (0);
return (a*b);

When a return statement is encountered, execution of the function is passed back to the calling environment as well.
Moreover, this value will be converted, if necessary to the type of the function as specified in the function definition.

Example 5

/* This is an example of a program that passes a value to a called function by returning a value
to the calling function
*/

#include<stdio.h>

int fxn1(int); /* function prototype */

int main(void)
{
int age, b;

printf(“Enter your age: “);


scanf(“%d”, &age);
b = fxn1(age);
printf(“\nNext year you will be %d”, b);

return (0);
}

int fxn1(int num) /* a function that accepts an integer and returns an integer value to the calling function
*/
{
int x;

printf(“\nThe age accepted is %d”, num);


x = num + 1;
return x; /* if num = 5, then 6 is returned to the calling environment */
} /* when a function returns no value, you can simply write return 0 to tell the computer
explicitly that the function returns nothing */

Functions and Structured Programming


Prepared by: Kim L. Faburada 8
Example 6

#include<stdio.h>

int fxn1(int B)
{
int m = 7;
B = ++m *B;
return B;
}

void fxn2(int x, y)
{
int h = 3;

x+= h + y++;
++h;
printf(“\n%d %d %d”,x, y, h);
return; /* datatype_returned by your function is specified as void since it returns nothing*/
}

int main(void)
{

int x, y = 5;

x = fxn1(y); /* variable x accepts the value being returned by fxn1 */


printf(“%d %d”, x, y);
fxn2(x, y);
printf(“\n%d %d, x, y);

return 0;
}

Output

Problem 4:
Edit your program in problem 2. This time, do not use global variables. Meaning, all variables must be declared locally
inside a function. Use parameter passing by value. See to it that each function that you create performs a specific task.

Problem 5:
Write a function-oriented program that computes the factorial value of an input n! then display the computed factorial
value on screen. (Example: The factorial value of 5 is 5*4*3*2*1 which is equal to 120).

Problem 6:
Write a function-oriented program that calculates the sum of the squares from 1 to n. Thus, if the input is 4, the output
should be 30 because 12 + 22 + 32 + 42= 30.

Functions and Structured Programming


Prepared by: Kim L. Faburada 9
Problem 7:
Write a function-oriented program that calculates the sum of the sequence number from 1 to n. Thus, if the input is 4,
the output should be 10 because 1 + 2 + 3 + 4 = 10.

Problem 8
Write a function-oriented program that calculates the power value of the input based number and exponent number.
Then display the power value.

Sample input/output:

Enter base number: 6 /* 6 is the first user input */


Enter exponent number: 3 /* 3 is the second user input */
Power value: 216 /* this is the result because 63 is equivalent to 216 */

Problem 9
Write a function-oriented program that will display all odd and even numbers given from n to 1. Use a separate
function to display all even and another separate function to display all odd numbers.

Sample input/output:

Enter a number: 9
Even numbers: 8 6 4 2
Odd numbers: 9 7 5 3 1

Pointer Declaration and Assignment

Pointers
- variables that store memory addresses (memory locations) of another variable
- when a program is run, each of the variables declared in the program is assigned a unique memory location
which stores the value of that variable
- a function call such as scanf(“%d”, &x) causes an appropriate value to be stored at a particular address in
memory where x is a variable and &x is the address or location in memory of its stored value

Syntax: <data type> * <variable name>

Example:
int i, *p; /* declares i to be of type int and p to be of type “pointer” to int */

Addressing and Dereferencing

Figure 1 illustrates what is happening in memory.

int *p, a, b;
?

Variable p a b
Value ? ? ?
Address 0000 0001 0002
Figure 1

Explanation: This causes the compiler to allocate space in memory for two integers and a pointer to int. At this point, the contents
of the variables are garbage, because no values have been assigned. Question marks are placed inside the diagram because we
do not know what values are stored in the three variables.

Functions and Structured Programming


Prepared by: Kim L. Faburada 10
The assignment statements

a = b = 7;
p = &a;

can be illustrated in the memory as

Variable p a b
Value 0001 7 7
Address 0000 0001 0002
Figure 2

Explanation: The first statement stores 7 to variables a and b. The second statement stores the address of a (which is 0001) to p.
In this case, p is now said to “point” to a.

The indirection operator (*) is used to access the value of the variable pointed to by a pointer. Consider the statement

printf(“%d”, *p); /* since p points to a, and a has a value 7, the dereferenced value of p is 7 and that is
what gets printed*/

The statements

*p = 3;
printf(“%d”, a);

prints out 3. The object pointed to by p is assigned the value 3. Since p points to a, the stored value of a in memory is
overwritten with the value 3. Thus, when we print out the value of a, 3 gets printed.

This is what we have in the memory

Variable p a b
Value 0001 73 7
Address 0000 0001 0002
Figure 3

Our next statement

p = &b;

causes p to point at b

Variable p a b
Value 0002 3 7
Address 0000 0001 0002
Figure 4

Functions and Structured Programming


Prepared by: Kim L. Faburada 11
The code

*p = 2 * *p – a;
printf(“%d”, b);

prints out 11.

Explanation: The first statement is read as: “The object pointed to by p is assigned the value 2 times what p is pointing to minus a.
Note that the expression p on the right side of the assignment is evaluated first. This is because the dereference operator (*)
has higher precedence than the binary arithmetic operators.

In a certain sense, the dereference or indirection operator (*) is the inverse of the address operator (&). Consider the
following code:

float x, y, *p;

p = &x;
y = *p;

First, p is assigned the address of x. Then y is assigned the value of the object pointed to by p. The two statements is
equivalent to:
y = x;

Function Using Pointers (Pass-By-Reference)

When an expression is passed as an argument to a function, a copy of the value of the expression is made, and it is
this copy that is passed to the function. This mechanism is known as call-by-value. Suppose that x is a variable and
f() is a function. A function call such as f(x) cannot change the value of a variable x in the calling environment because
only a copy of the value of variable x is passed to f( ). In other programming languages, however, such a function call
can change the value of a variable x in the calling environment. The mechanism that accomplishes this is known as
call-by reference. To get the effect of call-by-reference in C, one must use pointers in the parameter list in the
function definition and pass addresses of variables as arguments in the function call.

The following programs demonstrate how the values of the argument variables that are passed as memory address
have been changed or affected by the operation of the function call by reference:

Example 1

#include<stdio.h>

void swap(int *, int *);

int main(void)
{ int a = 3, b = 7;

printf(“%d %d\n”, a, b); /* 3 7 is printed */


swap(&a, &b);
printf(“%d %d\n”, a, b); /* 7 3 is printed */
return 0;
}

void swap(int *p, int *q)


{
int tmp;

tmp = *p;
*p = *q;
*q = temp;
}

Functions and Structured Programming


Prepared by: Kim L. Faburada 12
Example 2

#include<stdio.h>
int swap(int *, int *, int); /* function prototype */

int main(void)
{

int x, y, t;

system(“cls”);

x =10;
y = 20;
t = 30;

printf(“\n The original value of x: %d”, x);


printf(“\n The original value of y: %d”, y);
printf(“\n The original value of t: %d”, t);
printf(“\n\n Values after calling the function: “);

swap(&x, &y, t);

printf(“\n\n x+1 = %d”, x+1);


printf(“\n y+1 = %d”, y+1);
printf(“\n t+1 = %d”, t+1);

int swap(int *x, int *y, int t)


{
t = *x;
*x = *y;
*y = t;
return 0;
}

Output:

The original value of x: 10


The original value of y: 20
The original value of t: 30

Values after calling the function:

x+1=21
y+1=11
t+1=31

Exercises
Functions and Structured Programming
Prepared by: Kim L. Faburada 13
1) Determine the output of the following codes:

int a = 9;
int *ptr = &a; /* assuming & is 3000 */

*ptr = 11;

printf (“%d”, a);


printf(“\%d”, *ptr);
printf(“\n%d”, ptr);
printf(“\n%d”, a);

Functions and Structured Programming


Prepared by: Kim L. Faburada 14

You might also like